three-live 1.3.1 → 1.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -1
- package/dist/index.d.ts +191 -0
- package/dist/three-author-engine.js +179 -144
- package/dist/three-author.cjs +153 -144
- package/dist/three-author.d.ts +191 -0
- package/dist/three-author.js +153 -144
- package/dist/three-convert.cjs +150 -141
- package/dist/three-convert.d.ts +191 -0
- package/dist/three-convert.js +150 -141
- 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 +191 -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 +191 -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 +191 -0
- package/dist/three-live-element.js +50 -85
- package/dist/three-live-full.cjs +915 -170
- package/dist/three-live-full.js +917 -172
- package/dist/three-live-full.min.js +915 -170
- 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 +191 -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 +191 -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 +155 -146
- package/dist/three-live.js +155 -146
- package/dist/three-live.min.js +155 -146
- package/dist/three-view.cjs +49 -84
- package/dist/three-view.d.ts +191 -0
- package/dist/three-view.js +50 -85
- package/dist/three-xr.cjs +150 -141
- package/dist/three-xr.d.ts +191 -0
- package/dist/three-xr.js +150 -141
- package/package.json +39 -1
package/dist/three-live-full.js
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 Go=Object.defineProperty,Ho=(e,t)=>{for(var r in t)Go(e,r,{get:t[r],enumerable:!0})},zn={};Ho(zn,{AmbientLight:()=>Wr,BoxGeometry:()=>zr,BufferAttribute:()=>$e,BufferGeometry:()=>Ve,Camera:()=>qr,CapsuleGeometry:()=>Fs,CatmullRomCurve3:()=>hs,CircleGeometry:()=>Vs,Clock:()=>As,Color:()=>ot,ConeGeometry:()=>ss,CubicBezierCurve3:()=>us,Curve3:()=>Ct,CylinderGeometry:()=>$r,DataTexture:()=>ms,DirectionalLight:()=>vs,DodecahedronGeometry:()=>ks,EdgesGeometry:()=>Bs,Euler:()=>Or,Float32BufferAttribute:()=>Ji,Group:()=>xs,HemisphereLight:()=>oi,IKSolver:()=>Zn,IcosahedronGeometry:()=>Is,InstancedMesh:()=>jr,InteractivityVM:()=>yn,LOD:()=>ra,LatheGeometry:()=>Gr,Light:()=>er,Line:()=>Ft,LineBasicMaterial:()=>yr,LineCurve3:()=>os,LineDashedMaterial:()=>Os,LineLoop:()=>zs,LineSegments:()=>$s,LodController:()=>Oi,MAX_BSP_DEPTH:()=>Wn,MAX_CSG_TRIANGLES:()=>jn,MAX_INSTANCES_PER_MESH:()=>Jt,MAX_SHAPE_POINTS:()=>qn,MAX_TEXT_GEOMETRY_CHARS:()=>Xn,Material:()=>et,MathUtils:()=>Qi,Matrix3:()=>Zi,Matrix4:()=>It,Mesh:()=>pt,MeshBasicMaterial:()=>ds,MeshLambertMaterial:()=>gs,MeshPhongMaterial:()=>ys,MeshPhysicalMaterial:()=>bs,MeshStandardMaterial:()=>Qt,Object3D:()=>lt,OctahedronGeometry:()=>Ds,PerspectiveCamera:()=>Ms,PlaneGeometry:()=>rs,PointLight:()=>Xr,Points:()=>Gs,PointsMaterial:()=>ai,PolyhedronFallbackGeometry:()=>za,PolyhedronGeometry:()=>Nt,QuadraticBezierCurve3:()=>ls,Quaternion:()=>Ur,RawShaderMaterial:()=>Ns,RectAreaLight:()=>js,RingGeometry:()=>ni,Scene:()=>Kr,SceneQuotaValidator:()=>dt,ShaderMaterial:()=>ii,SphereGeometry:()=>is,SpotLight:()=>Hs,THREE:()=>Vt,TetrahedronGeometry:()=>_s,Texture:()=>pr,TextureLoader:()=>fs,ThreeLiveElement:()=>ir,ThreeView:()=>Ze,TorusGeometry:()=>ns,TorusKnotGeometry:()=>as,TubeGeometry:()=>cs,Uint16BufferAttribute:()=>es,Uint32BufferAttribute:()=>ts,Vector2:()=>it,Vector3:()=>be,Vector4:()=>Yi,WebGLRenderer:()=>Ss,WireframeGeometry:()=>Us,activateAR:()=>on,applyMeshoptFilter:()=>Mn,authorScriptRunner:()=>gr,buildSandboxWorkerSource:()=>ei,cadPlugin:()=>Pi,clearAuthorWarnings:()=>Ls,computeOutlineClipOffset:()=>Po,contactShadowPlugin:()=>ci,createUSDZBlob:()=>Vr,crossFadeTo:()=>Ks,decimateGeometry:()=>ta,decodeMeshoptBuffer:()=>wn,decodeMeshoptGLB:()=>Mi,encodeMeshoptBuffer:()=>So,environmentMapPlugin:()=>cn,evaluateKawaseBloom:()=>To,evaluateToneMapping:()=>la,exportSceneToCanvas3D:()=>Yr,exportSceneToGLB:()=>Zr,exportSceneToUSDZ:()=>ws,extractMaterialVariants:()=>Pn,extractPrimitiveVariantMappings:()=>Eo,generateUSDZ:()=>Fr,getARCapabilities:()=>mi,getAllowClientScripts:()=>Cs,getAuthorWarnings:()=>Es,getBestARMode:()=>Ya,getEnvironmentSH:()=>Ja,getInteractivityVM:()=>bi,getLodController:()=>ia,getSandboxEngineSrc:()=>Jr,getSandboxIframeSrc:()=>Rs,glbToUSDZ:()=>kr,hotspotPlugin:()=>pn,ikPlugin:()=>Vi,installCadExtension:()=>Tr,installLodExtension:()=>lr,interactivityPlugin:()=>xn,isAllowedSandboxEngineUrl:()=>kt,isQuickLookSupported:()=>sn,isSceneViewerSupported:()=>nn,isWebXRSupported:()=>an,keyframeAnimationPlugin:()=>Qs,lodPlugin:()=>Ui,materialsPlugin:()=>vn,meshoptDecoder:()=>wi,meshoptPlugin:()=>Sn,morphPlugin:()=>Js,noopProxy:()=>tr,parseAnimations:()=>qs,parseHexRgb:()=>An,parseLod:()=>Nr,parseSafeGltfPointer:()=>Mr,postprocessingPlugin:()=>Tn,quatFromUnitVectors:()=>Cr,registerMaterialShader:()=>uo,sampleChannel:()=>sr,sceneToCanvas3D:()=>Zt,sceneToGLB:()=>mr,sceneToUSDZ:()=>fr,selectLodLevelIndex:()=>Lr,selectMaterialVariant:()=>Lo,sendInteractivityEvent:()=>bn,setAllowClientScripts:()=>Da,setEnvironmentSH:()=>un,setMorphTargetWeight:()=>qa,setSandboxEngineSrc:()=>Na,setSandboxIframeSrc:()=>_a,skinningPlugin:()=>tn,solveFABRIK:()=>Ni,solveTwoBoneIK:()=>Li,threeAuthorPlugin:()=>rr,threeMicroPlugin:()=>ja,toGLBData:()=>Dt,toTrustedWorkerScriptURL:()=>Ts,validateSandboxWorkerMessage:()=>ti,variantsPlugin:()=>Rn,warnUnsupported:()=>Lt,webxrPlugin:()=>Cn});function jo(e,t,r){let i=[],s=new Map,n=[],l=[],a=[],o=new Map,u=d=>{let y=s.get(d);return y===void 0&&(y=i.length,i.push({op:d}),s.set(d,y)),y},h=d=>{let y=o.get(d);return y===void 0&&(y=a.length,a.push({id:d}),o.set(d,y)),y},c=(d,y={})=>n.push({declaration:u(d),...y})-1,f=(d,y,M)=>l.push({id:d,type:y,value:M})-1,p=d=>({node:d,socket:"value"}),m=r?.interactivity??r?.gltfExtensions?.KHR_interactivity;if(m&&typeof m=="object"){let d=Array.isArray(m.graphs)?m.graphs[m.graph??0]:m;if(d&&Array.isArray(d.nodes)){let y=Array.isArray(d.declarations)?d.declarations:[];for(let M of y)M?.op&&u(M.op);Array.isArray(d.variables)&&l.push(...d.variables);for(let M of d.events||[])M?.id&&h(M.id);for(let M of d.nodes){if(!M||typeof M!="object")continue;let T=M.op||(typeof M.declaration=="number"?y[M.declaration]?.op:"");n.push(T?{...M,declaration:u(T)}:{...M})}}}let g=(d,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/${d}/extensions/KHR_node_visibility/visible`:`/nodes/${d}/${M}`,x=new Map;e.forEach((d,y)=>{typeof d?.name=="string"&&!x.has(d.name)&&x.set(d.name,y)});let b=(d,y)=>typeof d.target=="string"&&x.has(d.target)?x.get(d.target):typeof d.targetNode=="number"?d.targetNode:y,v=d=>{let y=e[d];return(typeof y?.mesh=="number"?t[y.mesh]?.primitives?.[0]?.material:0)??0};for(let d=0;d<e.length;d++){let y=e[d],M=y?.extras?.interactivity;if(!M||typeof M!="object")continue;let T=(typeof y.mesh=="number"?t[y.mesh]?.primitives?.[0]?.material:0)??0,V=P=>{let R=Array.isArray(P)?P:[P],C=[];for(let L=0;L<R.length;L++){let w=R[L];if(!w||typeof w!="object")continue;let ie=w.action||"interpolate",oe=typeof w.duration=="number"?w.duration:.35;if(ie==="toggleTransform"){let k=w.property==="rotation"||w.property==="scale"?w.property:"translation",J=k==="rotation"?y.rotation||[0,0,0,1]:k==="scale"?y.scale||[1,1,1]:y.translation||[0,0,0],z=`/nodes/${d}/${k}`,Y=f(`__toggle_${d}_${L}`,"bool",!1),le=c("variable/get",{configuration:{variable:Y}}),he=c("math/not",{values:{a:p(le)}}),$=c("variable/set",{configuration:{variable:Y},values:{value:p(he)}}),U=c("pointer/interpolate",{configuration:{pointer:z},values:{value:{value:Array.isArray(w.to)?w.to:J},duration:{value:oe}}}),N=c("pointer/interpolate",{configuration:{pointer:z},values:{value:{value:Array.isArray(w.from)?w.from:J},duration:{value:oe}}});n[$].flows={out:{node:c("flow/branch",{values:{condition:p(le)},flows:{true:{node:U},false:{node:N}}})}},C.push($)}else if(ie==="interpolate"){let k=w.to??w.value;if(k===void 0)continue;let J={value:{value:k},duration:{value:oe}};w.from!==void 0&&(J.from={value:w.from}),C.push(c("pointer/interpolate",{configuration:{pointer:typeof w.pointer=="string"?w.pointer:g(b(w,d),v(b(w,d)),w.property)},values:J}))}else if(ie==="setProperty"){if(w.value===void 0)continue;C.push(c("pointer/set",{configuration:{pointer:typeof w.pointer=="string"?w.pointer:g(b(w,d),v(b(w,d)),w.property)},values:{value:{value:w.value}}}))}else if(ie==="toggleVisibility"){let k=b(w,d),J=f(`__vis_${k}_${L}`,"bool",!0),z=c("variable/get",{configuration:{variable:J}}),Y=c("math/not",{values:{a:p(z)}}),le=c("variable/set",{configuration:{variable:J},values:{value:p(Y)}});n[le].flows={out:{node:c("pointer/set",{configuration:{pointer:`/nodes/${k}/extensions/KHR_node_visibility/visible`},values:{value:p(z)}})}},C.push(le)}else if(ie==="cycleMaterialColor"&&Array.isArray(w.colors)&&w.colors.length>0){let k=typeof w.duration=="number"?w.duration:.25,J=`/materials/${Math.max(0,T)}/pbrMetallicRoughness/baseColorFactor`,z=f(`__color_idx_${d}_${L}`,"int",0),Y=c("variable/get",{configuration:{variable:z}}),le=c("math/add",{values:{a:p(Y),b:{value:1}}}),he=c("math/rem",{values:{a:p(le),b:{value:w.colors.length}}}),$=c("variable/set",{configuration:{variable:z},values:{value:p(he)}}),U={};for(let N=0;N<w.colors.length;N++){let G=w.colors[N],D=Array.isArray(G)&&G.length>=3?[G[0],G[1],G[2],G[3]??1]:[1,1,1,1];U[String(N)]={node:k>0?c("pointer/interpolate",{configuration:{pointer:J},values:{value:{value:D},duration:{value:k}}}):c("pointer/set",{configuration:{pointer:J},values:{value:{value:D}}})}}n[$].flows={out:{node:c("flow/switch",{values:{selection:p(Y)},flows:U})}},C.push($)}else if(ie==="playAnimation")C.push(c("animation/start",{configuration:{animation:w.animation??w.clip??0}}));else if(ie==="stopAnimation")C.push(c("animation/stop"));else if(ie==="sendEvent"){let k={};for(let[J,z]of Object.entries(w.values||{}))k[J]={value:z};C.push(c("event/send",{configuration:{event:h(String(w.event??w.id??"custom"))},values:k}))}}if(!C.length)return null;if(C.length===1)return C[0];let B={};return C.forEach((L,w)=>{B[String(w)]={node:L}}),c("flow/sequence",{flows:B})},q=(P,R,C)=>{let B=V(R);B!==null&&c(P,{...C?{configuration:C}:{},flows:{out:{node:B}}})};if(M.onSelect&&q("pointer/onSelect",M.onSelect,{nodeIndex:d}),M.onHoverIn&&q("pointer/onHoverIn",M.onHoverIn,{nodeIndex:d}),M.onHoverOut&&q("pointer/onHoverOut",M.onHoverOut,{nodeIndex:d}),M.onStart&&q("event/onStart",M.onStart),M.onReceive&&typeof M.onReceive=="object")for(let[P,R]of Object.entries(M.onReceive))q("event/receive",R,{event:h(P)})}return n.length?{graphs:[{declarations:i,nodes:n,variables:l,events:a}],graph:0}:null}var $n='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).',Gn="Security Error: client-side scripts require allow-client-scripts opt-in.",Ar="__THREE_LIVE_REGISTRY__";function Se(){let e=typeof globalThis<"u"?globalThis:{};if(!e[Ar]){let t={plugins:[],decoders:new Map};try{Object.defineProperty(e,Ar,{value:t,writable:!1,configurable:!1,enumerable:!1})}catch{e[Ar]=t}}return e[Ar]}var Fe=Se().plugins;function Ti(e){let t=Se();t.workerExtensionInstallers||(t.workerExtensionInstallers=[]),t.workerExtensionInstallers.includes(e)||t.workerExtensionInstallers.push(e)}function He(e){let t=Se().plugins;t.some(r=>r.name===e.name)||t.push(e),e.onRegister?.()}function Hn(){return Se().plugins}var jn=8192,Wn=2048,Xn=128,qn=4096;function Tr(e,t){if(!e||!e.BufferGeometry)return null;let r=e.Vector2,i=e.Vector3,s=e.Quaternion,n=e.Matrix4,l=e.Matrix3,a=e.Color,o=e.BufferAttribute,u=e.BufferGeometry,h=e.Material,c=e.MeshStandardMaterial,f=e.Mesh,p=8192,m=2048,g=128,x=4096,b=(A,S)=>{let _=A==null?NaN:Number(A);return Number.isFinite(_)?_:S};class v{constructor(S){this.currentPoint=new r(0,0),this.segments=[],Array.isArray(S)&&S.length>0&&this.fromPoints(S)}fromPoints(S){if(!S.length)return this;this.moveTo(S[0].x,S[0].y);for(let _=1;_<S.length;_++)this.lineTo(S[_].x,S[_].y);return this}moveTo(S,_){let O=Number(S)||0,I=Number(_)||0;return this.currentPoint.set(O,I),this.segments.push({type:"move",pts:[O,I]}),this}lineTo(S,_){let O=Number(S)||0,I=Number(_)||0;return this.segments.length===0&&this.segments.push({type:"move",pts:[this.currentPoint.x,this.currentPoint.y]}),this.currentPoint.set(O,I),this.segments.push({type:"line",pts:[O,I]}),this}quadraticCurveTo(S,_,O,I){let W=this.currentPoint.x,Q=this.currentPoint.y,K=Number(S)||0,Z=Number(_)||0,X=Number(O)||0,re=Number(I)||0;return this.segments.length===0&&this.segments.push({type:"move",pts:[W,Q]}),this.currentPoint.set(X,re),this.segments.push({type:"quad",pts:[W,Q,K,Z,X,re]}),this}bezierCurveTo(S,_,O,I,W,Q){let K=this.currentPoint.x,Z=this.currentPoint.y,X=Number(S)||0,re=Number(_)||0,se=Number(O)||0,te=Number(I)||0,ue=Number(W)||0,ce=Number(Q)||0;return this.segments.length===0&&this.segments.push({type:"move",pts:[K,Z]}),this.currentPoint.set(ue,ce),this.segments.push({type:"cubic",pts:[K,Z,X,re,se,te,ue,ce]}),this}absarc(S,_,O,I,W,Q=!1){return this.absellipse(S,_,O,O,I,W,Q,0)}arc(S,_,O,I,W,Q=!1){return this.absarc(this.currentPoint.x+(Number(S)||0),this.currentPoint.y+(Number(_)||0),O,I,W,Q)}absellipse(S,_,O,I,W,Q,K=!1,Z=0){let X=Number(S)||0,re=Number(_)||0,se=Math.max(0,Number(O)||0),te=Math.max(0,Number(I)||0),ue=Number(W)||0,ce=Number(Q)||0,fe=K?1:0,me=Number(Z)||0;this.segments.push({type:"arc",pts:[X,re,se,te,ue,ce,fe,me]});let de=Math.cos(me),ge=Math.sin(me),Me=se*Math.cos(ce),ye=te*Math.sin(ce);return this.currentPoint.set(X+Me*de-ye*ge,re+Me*ge+ye*de),this}ellipse(S,_,O,I,W,Q,K=!1,Z=0){return this.absellipse(this.currentPoint.x+(Number(S)||0),this.currentPoint.y+(Number(_)||0),O,I,W,Q,K,Z)}closePath(){if(this.segments.length>0){let S=this.segments[0],_=0,O=0;if(S.type==="arc"){let I=S.pts[0],W=S.pts[1],Q=S.pts[2],K=S.pts[3],Z=S.pts[4],X=S.pts[7],re=Math.cos(X),se=Math.sin(X),te=Q*Math.cos(Z),ue=K*Math.sin(Z);_=I+te*re-ue*se,O=W+te*se+ue*re}else _=S.pts[0],O=S.pts[1];Math.hypot(this.currentPoint.x-_,this.currentPoint.y-O)>1e-6&&this.lineTo(_,O)}return this}getPoints(S=12){let _=Math.max(1,Math.min(128,Math.floor(Number(S)||12))),O=[],I=(W,Q)=>{if(O.length>0){let K=O[O.length-1];if(Math.hypot(K.x-W,K.y-Q)<1e-6)return}O.push(new r(W,Q))};for(let W of this.segments){let Q=W.pts;if(W.type==="move"||W.type==="line")I(Q[0],Q[1]);else if(W.type==="quad"){let K=Q[0],Z=Q[1],X=Q[2],re=Q[3],se=Q[4],te=Q[5];I(K,Z);for(let ue=1;ue<=_;ue++){let ce=ue/_,fe=1-ce;I(fe*fe*K+2*fe*ce*X+ce*ce*se,fe*fe*Z+2*fe*ce*re+ce*ce*te)}}else if(W.type==="cubic"){let K=Q[0],Z=Q[1],X=Q[2],re=Q[3],se=Q[4],te=Q[5],ue=Q[6],ce=Q[7];I(K,Z);for(let fe=1;fe<=_;fe++){let me=fe/_,de=1-me,ge=de*de,Me=me*me;I(ge*de*K+3*ge*me*X+3*de*Me*se+Me*me*ue,ge*de*Z+3*ge*me*re+3*de*Me*te+Me*me*ce)}}else if(W.type==="arc"){let K=Q[0],Z=Q[1],X=Q[2],re=Q[3],se=Q[4],te=Q[5],ue=Q[6]!==0,ce=Q[7],fe=Math.PI*2,me=te-se,de=Math.abs(me)<1e-9;for(;me<0;)me+=fe;for(;me>fe;)me-=fe;me<1e-9&&(me=de?0:fe),ue&&!de&&(me=me===fe?-fe:me-fe);let ge=Math.cos(ce),Me=Math.sin(ce),ye=Math.max(2,_);for(let Ce=0;Ce<=ye;Ce++){let Ae=Ce/ye,Pe=se+Ae*me,Le=X*Math.cos(Pe),Ne=re*Math.sin(Pe);I(K+Le*ge-Ne*Me,Z+Le*Me+Ne*ge)}}}if(O.length>2){let W=O[0],Q=O[O.length-1];Math.hypot(W.x-Q.x,W.y-Q.y)<1e-6&&O.pop()}return O}getSpacedPoints(S=12){return this.getPoints(S)}clone(){let S=new this.constructor;return S.currentPoint.copy(this.currentPoint),S.segments=this.segments.map(_=>({type:_.type,pts:[..._.pts]})),Array.isArray(this.holes)&&(S.holes=this.holes.map(_=>_.clone())),S}}class d extends v{constructor(S){super(S),this.holes=[]}extractPoints(S=12){return{shape:this.getPoints(S),holes:this.holes.map(_=>_.getPoints(S))}}}function y(A){let S=0,_=A.length;for(let O=0,I=_-1;O<_;I=O++)S+=A[I].x*A[O].y-A[O].x*A[I].y;return S*.5}function M(A,S,_,O,I,W,Q,K){let Z=Q-_,X=K-O,re=I-_,se=W-O,te=A-_,ue=S-O,ce=Z*Z+X*X,fe=Z*re+X*se,me=Z*te+X*ue,de=re*re+se*se,ge=re*te+se*ue,Me=ce*de-fe*fe;if(Math.abs(Me)<1e-12)return!1;let ye=1/Me,Ce=(de*me-fe*ge)*ye,Ae=(ce*ge-fe*me)*ye;return Ce>=-1e-7&&Ae>=-1e-7&&Ce+Ae<=1+1e-7}function T(A,S){let _=A.slice();y(_)<0&&_.reverse();let O=_.map(Z=>new r(Z.x,Z.y)),I=_.map((Z,X)=>X),W=[];for(let Z of S){if(!Z||Z.length<3)continue;let X=Z.slice();y(X)>0&&X.reverse();let re=[],se=-1/0,te=0;for(let ue=0;ue<X.length;ue++){let ce=X[ue],fe=O.length;O.push(new r(ce.x,ce.y)),re.push(fe),ce.x>se&&(se=ce.x,te=ue)}W.push({pts:X,indices:re,maxX:se,maxIdx:te})}W.sort((Z,X)=>X.maxX-Z.maxX);let Q=(Z,X,re)=>(X.x-Z.x)*(re.y-Z.y)-(X.y-Z.y)*(re.x-Z.x),K=(Z,X,re)=>{for(let se=0;se<re.length;se++){let te=re[se],ue=re[(se+1)%re.length];if(Q(Z,X,te)*Q(Z,X,ue)<0&&Q(te,ue,Z)*Q(te,ue,X)<0)return!0}return!1};for(let Z of W){let X=Z.pts[Z.maxIdx],re=X.x,se=I.length,te=I.map(de=>O[de]),ue=de=>Math.hypot(te[de].x-re,te[de].y-X.y),ce=te.map((de,ge)=>ge).sort((de,ge)=>+(te[de].x<re)-+(te[ge].x<re)||ue(de)-ue(ge)),fe=ce[0];for(let de of ce){let ge=te[de],Me=te[(de+se-1)%se],ye=te[(de+1)%se],Ce=Q(ge,ye,X)>=0,Ae=Q(Me,ge,X)>=0;if((Q(Me,ge,ye)>=0?Ce&&Ae:Ce||Ae)&&!K(X,ge,te)&&!W.some(Pe=>K(X,ge,Pe.pts))){fe=de;break}}let me=[];for(let de=0;de<=fe;de++)me.push(I[de]);for(let de=0;de<=Z.indices.length;de++){let ge=Z.indices[(Z.maxIdx+de)%Z.indices.length];me.push(ge)}for(let de=fe;de<I.length;de++)me.push(I[de]);I=me}return{merged:I.map(Z=>O[Z]),mergedIndices:I,allVertices:O}}function V(A,S){let _=[],O=A.slice();if(O.length<3)return _;let I=O.length*O.length+64,W=0;for(;O.length>2&&I-- >0;){let Q=O.length,K=O[(W+Q-1)%Q],Z=O[W%Q],X=O[(W+1)%Q],re=S[K],se=S[Z],te=S[X];if((se.x-re.x)*(te.y-re.y)-(se.y-re.y)*(te.x-re.x)>1e-9){let ue=!0;for(let ce=0;ce<Q;ce++){let fe=O[ce];if(fe===K||fe===Z||fe===X)continue;let me=S[fe];if(M(me.x,me.y,re.x,re.y,se.x,se.y,te.x,te.y)&&Math.hypot(me.x-re.x,me.y-re.y)>=1e-6&&Math.hypot(me.x-se.x,me.y-se.y)>=1e-6&&Math.hypot(me.x-te.x,me.y-te.y)>=1e-6){ue=!1;break}}if(ue){_.push([K,Z,X]),O.splice(W%Q,1),W=Math.max(0,W%Q-1);continue}}W++,W>=Q*2&&(_.push([K,Z,X]),O.splice((W-1)%Q,1),W=0)}return _}function q(A,S){let _=A instanceof d?A.extractPoints(S):{shape:A.getPoints(S),holes:[]},O=_.shape.length;for(let I of _.holes)O+=I.length;if(O>x)throw new RangeError(`SecurityError: shape point count (${O}) exceeds MAX_SHAPE_POINTS (${x})`);return _}class P extends u{constructor(S=new d,_=12){super();let O=Array.isArray(S)?S:[S],I=[],W=[],Q=[],K=[];for(let Z of O){if(!(Z instanceof v))continue;let X=q(Z,_);if(X.shape.length<3)continue;let{mergedIndices:re,allVertices:se}=T(X.shape,X.holes),te=V(re,se),ue=I.length/3,ce=1/0,fe=1/0,me=-1/0,de=-1/0;for(let ye of se)ye.x<ce&&(ce=ye.x),ye.y<fe&&(fe=ye.y),ye.x>me&&(me=ye.x),ye.y>de&&(de=ye.y);let ge=Math.max(1e-6,me-ce),Me=Math.max(1e-6,de-fe);for(let ye of se)I.push(ye.x,ye.y,0),W.push(0,0,1),Q.push((ye.x-ce)/ge,(ye.y-fe)/Me);for(let[ye,Ce,Ae]of te)K.push(ue+ye,ue+Ce,ue+Ae)}R(this,I,W,Q,K)}}function R(A,S,_,O,I){return A.setAttribute("position",new o(S,3)),A.setAttribute("normal",new o(_,3)),A.setAttribute("uv",new o(O,2)),A.setIndex(I),A}function C(A){let S=A.length,_=[];for(let O=0;O<S;O++){let I=A[(O+S-1)%S],W=A[O],Q=A[(O+1)%S],K=W.x-I.x,Z=W.y-I.y,X=Math.hypot(K,Z)||1;K/=X,Z/=X;let re=Q.x-W.x,se=Q.y-W.y,te=Math.hypot(re,se)||1;re/=te,se/=te;let ue=Z,ce=-K,fe=se,me=-re,de=ue+fe,ge=ce+me,Me=Math.hypot(de,ge);if(Me>1e-6){de/=Me,ge/=Me;let ye=Math.max(.35,de*ue+ge*ce);_.push(new r(de/ye,ge/ye))}else _.push(new r(ue,ce))}return _}class B extends u{constructor(S=new d,_={}){super();let O=Array.isArray(S)?S:[S],I=Math.max(1,Math.min(64,Math.floor(b(_.curveSegments,12)))),W=b(_.depth??_.amount,1),Q=Math.max(1,Math.min(32,Math.floor(b(_.steps,1)))),K=!!(_.bevelEnabled??!1),Z=K?Math.max(0,b(_.bevelThickness,.06)):0,X=K?Math.max(0,b(_.bevelSize,Z*.8)):0,re=K?b(_.bevelOffset,0):0,se=K?Math.max(1,Math.min(8,Math.floor(b(_.bevelSegments,2)))):0,te=[],ue=[],ce=[],fe=[];for(let me of O){if(!(me instanceof v))continue;let de=q(me,I);if(de.shape.length<3)continue;let ge=de.shape.slice();y(ge)<0&&ge.reverse();let Me=[];for(let xe of de.holes){if(xe.length<3)continue;let Te=xe.slice();y(Te)>0&&Te.reverse(),Me.push(Te)}let{mergedIndices:ye,allVertices:Ce}=T(ge,Me),Ae=V(ye,Ce),Pe=[ge,...Me],Le=[];for(let xe of Pe){let Te=C(xe);for(let De of Te)Le.push(De)}let Ne=1/0,Ge=1/0,ze=-1/0,Je=-1/0;for(let xe of Ce)xe.x<Ne&&(Ne=xe.x),xe.y<Ge&&(Ge=xe.y),xe.x>ze&&(ze=xe.x),xe.y>Je&&(Je=xe.y);let je=Math.max(1e-6,ze-Ne),nt=Math.max(1e-6,Je-Ge),Bt=-Z,zt=W+Z,bt=te.length/3;for(let xe=0;xe<Ce.length;xe++){let Te=Ce[xe],De=Le[xe]??new r(0,0),Oe=Te.x+De.x*re,Ue=Te.y+De.y*re;te.push(Oe,Ue,Bt),ue.push(0,0,-1),ce.push((Oe-Ne)/je,(Ue-Ge)/nt)}for(let[xe,Te,De]of Ae)fe.push(bt+xe,bt+De,bt+Te);let xt=te.length/3;for(let xe=0;xe<Ce.length;xe++){let Te=Ce[xe],De=Le[xe]??new r(0,0),Oe=Te.x+De.x*re,Ue=Te.y+De.y*re;te.push(Oe,Ue,zt),ue.push(0,0,1),ce.push((Oe-Ne)/je,(Ue-Ge)/nt)}for(let[xe,Te,De]of Ae)fe.push(xt+xe,xt+Te,xt+De);let Xe=[];if(K&&se>0)for(let xe=0;xe<se;xe++){let Te=xe/se*Math.PI/2;Xe.push({z:-Z*Math.cos(Te),expand:re+X*Math.sin(Te)})}for(let xe=0;xe<=Q;xe++){let Te=xe/Q;Xe.push({z:Te*W,expand:re+X})}if(K&&se>0)for(let xe=1;xe<=se;xe++){let Te=xe/se*Math.PI/2;Xe.push({z:W+Z*Math.sin(Te),expand:re+X*Math.cos(Te)})}let at=0;for(let xe of Pe){let Te=xe.length;for(let De=0;De<Xe.length-1;De++){let Oe=Xe[De],Ue=Xe[De+1];for(let Ke=0;Ke<Te;Ke++){let ct=(Ke+1)%Te,vt=xe[Ke],Mt=xe[ct],wt=Le[at+Ke],St=Le[at+ct],At=vt.x+wt.x*Oe.expand,Tt=vt.y+wt.y*Oe.expand,_t=Mt.x+St.x*Oe.expand,mt=Mt.y+St.y*Oe.expand,zo=Mt.x+St.x*Ue.expand,$o=Mt.y+St.y*Ue.expand,En=vt.x+wt.x*Ue.expand,Ln=vt.y+wt.y*Ue.expand,Nn=_t-At,_n=mt-Tt,Dn=0,In=En-At,kn=Ln-Tt,Fn=Ue.z-Oe.z,$t=_n*Fn-Dn*kn,Gt=Dn*In-Nn*Fn,Ht=Nn*kn-_n*In,Ai=Math.hypot($t,Gt,Ht)||1;$t/=Ai,Gt/=Ai,Ht/=Ai;let jt=te.length/3;te.push(At,Tt,Oe.z,_t,mt,Oe.z,zo,$o,Ue.z,En,Ln,Ue.z),ue.push($t,Gt,Ht,$t,Gt,Ht,$t,Gt,Ht,$t,Gt,Ht);let Vn=Ke/Te,On=(Ke+1)/Te,Un=De/(Xe.length-1),Bn=(De+1)/(Xe.length-1);ce.push(Vn,Un,On,Un,On,Bn,Vn,Bn),fe.push(jt,jt+1,jt+2,jt,jt+2,jt+3)}}at+=Te}}R(this,te,ue,ce,fe)}}function L(A){return{x:A.x,y:A.y,z:A.z,nx:A.nx,ny:A.ny,nz:A.nz,u:A.u,v:A.v}}function w(A){return{x:A.x,y:A.y,z:A.z,nx:-A.nx,ny:-A.ny,nz:-A.nz,u:A.u,v:A.v}}function ie(A,S,_){let O=A.nx+(S.nx-A.nx)*_,I=A.ny+(S.ny-A.ny)*_,W=A.nz+(S.nz-A.nz)*_,Q=Math.hypot(O,I,W)||1;return{x:A.x+(S.x-A.x)*_,y:A.y+(S.y-A.y)*_,z:A.z+(S.z-A.z)*_,nx:O/Q,ny:I/Q,nz:W/Q,u:A.u+(S.u-A.u)*_,v:A.v+(S.v-A.v)*_}}function oe(A){if(A.length<3)return null;let S=A[0],_=A[1],O=A[2],I=_.x-S.x,W=_.y-S.y,Q=_.z-S.z,K=O.x-S.x,Z=O.y-S.y,X=O.z-S.z,re=W*X-Q*Z,se=Q*K-I*X,te=I*Z-W*K,ue=Math.hypot(re,se,te);if(ue<1e-9)return null;re/=ue,se/=ue,te/=ue;let ce=re*S.x+se*S.y+te*S.z;return{vertices:A,nx:re,ny:se,nz:te,w:ce}}function k(A){A.vertices.reverse();for(let S=0;S<A.vertices.length;S++)A.vertices[S]=w(A.vertices[S]);A.nx=-A.nx,A.ny=-A.ny,A.nz=-A.nz,A.w=-A.w}let J=1e-5,z=0,Y=1,le=2,he=3;function $(A,S,_,O,I,W,Q,K,Z){let X=0,re=[];for(let se=0;se<I.vertices.length;se++){let te=I.vertices[se],ue=A*te.x+S*te.y+_*te.z-O,ce=ue<-J?le:ue>J?Y:z;X|=ce,re.push(ce)}switch(X){case z:{A*I.nx+S*I.ny+_*I.nz>0?W.push(I):Q.push(I);break}case Y:K.push(I);break;case le:Z.push(I);break;case he:{let se=[],te=[],ue=I.vertices.length;for(let ge=0;ge<ue;ge++){let Me=(ge+1)%ue,ye=re[ge],Ce=re[Me],Ae=I.vertices[ge],Pe=I.vertices[Me];if(ye!==le&&se.push(Ae),ye!==Y&&te.push(ye!==le?L(Ae):Ae),(ye|Ce)===he){let Le=Pe.x-Ae.x,Ne=Pe.y-Ae.y,Ge=Pe.z-Ae.z,ze=A*Le+S*Ne+_*Ge,Je=Math.abs(ze)>1e-12?(O-(A*Ae.x+S*Ae.y+_*Ae.z))/ze:.5,je=ie(Ae,Pe,Math.max(0,Math.min(1,Je)));se.push(je),te.push(L(je))}}let{nx:ce,ny:fe,nz:me,w:de}=I;se.length>=3&&K.push({vertices:se,nx:ce,ny:fe,nz:me,w:de}),te.length>=3&&Z.push({vertices:te,nx:ce,ny:fe,nz:me,w:de});break}default:break}}class U{constructor(S,_=0){this.nx=0,this.ny=0,this.nz=0,this.w=0,this.hasPlane=!1,this.polygons=[],this.front=null,this.back=null,S&&S.length>0&&this.build(S,_)}invert(){for(let _=0;_<this.polygons.length;_++)k(this.polygons[_]);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 S=this.front;this.front=this.back,this.back=S}clipPolygons(S,_=0){if(!this.hasPlane||S.length===0)return S.slice();if(_>=m)throw new RangeError(`SecurityError: CSG BSP depth exceeds MAX_BSP_DEPTH (${m})`);let O=[],I=[];for(let W=0;W<S.length;W++)$(this.nx,this.ny,this.nz,this.w,S[W],O,I,O,I);return this.front&&O.length>0&&(O=this.front.clipPolygons(O,_+1)),this.back?I=I.length>0?this.back.clipPolygons(I,_+1):[]:I=[],O.concat(I)}clipTo(S,_=0){this.polygons.length>0&&(this.polygons=S.clipPolygons(this.polygons,0)),_<m&&(this.front&&this.front.clipTo(S,_+1),this.back&&this.back.clipTo(S,_+1))}allPolygons(S=[]){for(let _=0;_<this.polygons.length;_++)S.push(this.polygons[_]);return this.front&&this.front.allPolygons(S),this.back&&this.back.allPolygons(S),S}build(S,_=0){if(!S.length)return;if(!this.hasPlane){let W=S[S.length>>1];this.nx=W.nx,this.ny=W.ny,this.nz=W.nz,this.w=W.w,this.hasPlane=!0}if(_>=m)throw new RangeError(`SecurityError: CSG BSP depth exceeds MAX_BSP_DEPTH (${m})`);let O=[],I=[];for(let W=0;W<S.length;W++)$(this.nx,this.ny,this.nz,this.w,S[W],this.polygons,this.polygons,O,I);O.length>0&&(this.front||(this.front=new U),this.front.build(O,_+1)),I.length>0&&(this.back||(this.back=new U),this.back.build(I,_+1))}}function N(A,S){if(!S&&A._csgPolygons)return A._csgPolygons;let _=A.attributes.position;if(!_||_.count===0)return[];let O=A.attributes.normal,I=A.attributes.uv,W=A.index?A.index.array:null,Q=Math.floor(W?W.length/3:_.count/3);if(Q>p)throw new RangeError(`SecurityError: CSG input triangle count (${Q}) exceeds MAX_CSG_TRIANGLES (${p})`);let K=S?S.elements:null,Z=K?K[0]*(K[5]*K[10]-K[9]*K[6])-K[4]*(K[1]*K[10]-K[9]*K[2])+K[8]*(K[1]*K[6]-K[5]*K[2])<0:!1,X=K?new l().getNormalMatrix(S).elements:null,re=te=>{let ue=_.getX(te),ce=_.getY(te),fe=_.getZ(te),me=O?O.getX(te):NaN,de=O?O.getY(te):NaN,ge=O?O.getZ(te):NaN;if(K&&X){let Ce=K[0]*ue+K[4]*ce+K[8]*fe+K[12],Ae=K[1]*ue+K[5]*ce+K[9]*fe+K[13],Pe=K[2]*ue+K[6]*ce+K[10]*fe+K[14];ue=Ce,ce=Ae,fe=Pe;let Le=X[0]*me+X[3]*de+X[6]*ge,Ne=X[1]*me+X[4]*de+X[7]*ge,Ge=X[2]*me+X[5]*de+X[8]*ge,ze=Math.hypot(Le,Ne,Ge)||1;me=Le/ze,de=Ne/ze,ge=Ge/ze}let Me=I?I.getX(te):0,ye=I?I.getY(te):0;return{x:ue,y:ce,z:fe,nx:me,ny:de,nz:ge,u:Me,v:ye}},se=[];for(let te=0;te<Q;te++){let ue=W?W[te*3]:te*3,ce=W?W[te*3+1]:te*3+1,fe=W?W[te*3+2]:te*3+2,me=oe(Z?[re(ue),re(fe),re(ce)]:[re(ue),re(ce),re(fe)]);me&&se.push(me)}return se}function G(A){let S=[],_=[],O=[],I=[];for(let Q of A){let K=Q.vertices;if(K.length<3)continue;let Z=S.length/3;for(let X of K)S.push(X.x,X.y,X.z),Number.isFinite(X.nx)&&X.nx*X.nx+X.ny*X.ny+X.nz*X.nz>.5?_.push(X.nx,X.ny,X.nz):_.push(Q.nx,Q.ny,Q.nz),O.push(X.u,X.v);for(let X=1;X<K.length-1;X++)I.push(Z,Z+X,Z+X+1)}let W=R(new u,S,_,O,I);return W._csgPolygons=A,W}function D(A,S,_){if(A.length+S.length>p)throw new RangeError(`SecurityError: Combined CSG triangle count (${A.length+S.length}) exceeds MAX_CSG_TRIANGLES (${p})`);if(A.length===0)return _==="union"?S:[];if(S.length===0)return _==="intersect"?[]:A;let O=1/0,I=1/0,W=1/0,Q=-1/0,K=-1/0,Z=-1/0;for(let ue=0;ue<S.length;ue++){let ce=S[ue].vertices;for(let fe=0;fe<ce.length;fe++){let me=ce[fe];me.x<O&&(O=me.x),me.y<I&&(I=me.y),me.z<W&&(W=me.z),me.x>Q&&(Q=me.x),me.y>K&&(K=me.y),me.z>Z&&(Z=me.z)}}O-=1e-4,I-=1e-4,W-=1e-4,Q+=1e-4,K+=1e-4,Z+=1e-4;let X=[],re=[];for(let ue=0;ue<A.length;ue++){let ce=A[ue],fe=ce.vertices,me=1/0,de=1/0,ge=1/0,Me=-1/0,ye=-1/0,Ce=-1/0;for(let Ae=0;Ae<fe.length;Ae++){let Pe=fe[Ae];Pe.x<me&&(me=Pe.x),Pe.y<de&&(de=Pe.y),Pe.z<ge&&(ge=Pe.z),Pe.x>Me&&(Me=Pe.x),Pe.y>ye&&(ye=Pe.y),Pe.z>Ce&&(Ce=Pe.z)}Me<O||me>Q||ye<I||de>K||Ce<W||ge>Z?re.push(ce):X.push(ce)}if(X.length===0)return _==="union"?A.concat(S):_==="subtract"?A:[];let se=new U(X),te=new U(S);return _==="union"?(se.clipTo(te),te.clipTo(se),te.invert(),te.clipTo(se),te.invert(),se.build(te.allPolygons()),re.concat(se.allPolygons())):_==="subtract"?(se.invert(),se.clipTo(te),te.clipTo(se),te.invert(),te.clipTo(se),te.invert(),se.build(te.allPolygons()),se.invert(),re.concat(se.allPolygons())):(se.invert(),te.clipTo(se),te.invert(),se.clipTo(te),te.clipTo(se),se.build(te.allPolygons()),se.invert(),se.allPolygons())}function F(A,S,_,O=null,I=null){let W=N(A,O),Q=N(S,I);return G(D(W,Q,_))}function E(A,S,_){let O=A instanceof f||!!A?.isMesh,I=S instanceof f||!!S?.isMesh,W=O?A.geometry:A,Q=I?S.geometry:S,K=null;if(I)if(S.updateMatrix(),O){A.updateMatrix();let se=new n().makeScale(1/(A.scale.x||1),1/(A.scale.y||1),1/(A.scale.z||1)),te=Math.hypot(A.quaternion.x,A.quaternion.y,A.quaternion.z,A.quaternion.w)||1,ue=new n().compose(new i(0,0,0),new s(-A.quaternion.x/te,-A.quaternion.y/te,-A.quaternion.z/te,A.quaternion.w/te),new i(1,1,1)),ce=new n().makeTranslation(-A.position.x,-A.position.y,-A.position.z);K=se.multiply(ue).multiply(ce).multiply(S.matrix)}else K=S.matrix;let Z=F(W,Q,_,null,K),X=O?A.material:new c,re=new f(Z,X);return O&&(re.position.copy(A.position),re.quaternion.copy(A.quaternion),re.scale.copy(A.scale),re.name=A.name),re}let H={toGeometry:F,subtract(A,S){return E(A,S,"subtract")},union(A,S){return E(A,S,"union")},intersect(A,S){return E(A,S,"intersect")}},ee={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 ne extends u{constructor(S="",_={}){super();let O=String(S??"").slice(0,g),I=Math.max(.005,Math.min(100,b(_.size,.2))),W=!!(_.bevelEnabled??!1),Q=W?Math.max(0,Math.min(2,b(_.bevelThickness,I*.04))):0,K=W?Math.max(0,Math.min(2,b(_.bevelSize,I*.03))):0,Z=Math.max(.001,Math.min(20,b(_.depth??_.height,I*.2)))+Q*2,X=I*.085+K,re=I*.68,se=I*.82,te=[],ue=[],ce=[],fe=[],me=(Me,ye,Ce,Ae,Pe,Le,Ne)=>{let Ge=Ce-Me,ze=Ae-ye,Je=Math.hypot(Ge,ze),je=1,nt=0;Je>1e-6&&(je=Ge/Je,nt=ze/Je);let Bt=-nt*Pe,zt=je*Pe,bt=je*Pe*.6,xt=nt*Pe*.6,Xe=Me-bt+Bt,at=ye-xt+zt,xe=Me-bt-Bt,Te=ye-xt-zt,De=Ce+bt-Bt,Oe=Ae+xt-zt,Ue=Ce+bt+Bt,Ke=Ae+xt+zt,ct=(vt,Mt,wt,St,At,Tt,_t)=>{let mt=te.length/3;te.push(vt[0],vt[1],vt[2],Mt[0],Mt[1],Mt[2],wt[0],wt[1],wt[2],St[0],St[1],St[2]),ue.push(At,Tt,_t,At,Tt,_t,At,Tt,_t,At,Tt,_t),ce.push(0,0,1,0,1,1,0,1),fe.push(mt,mt+1,mt+2,mt,mt+2,mt+3)};ct([Xe,at,Ne],[xe,Te,Ne],[De,Oe,Ne],[Ue,Ke,Ne],0,0,1),ct([xe,Te,Le],[Xe,at,Le],[Ue,Ke,Le],[De,Oe,Le],0,0,-1),ct([Xe,at,Le],[xe,Te,Le],[xe,Te,Ne],[Xe,at,Ne],-je,-nt,0),ct([De,Oe,Le],[Ue,Ke,Le],[Ue,Ke,Ne],[De,Oe,Ne],je,nt,0),ct([xe,Te,Le],[De,Oe,Le],[De,Oe,Ne],[xe,Te,Ne],nt,-je,0),ct([Ue,Ke,Le],[Xe,at,Le],[Xe,at,Ne],[Ue,Ke,Ne],-nt,je,0)},de=0,ge=0;for(let Me=0;Me<O.length;Me++){let ye=O[Me];if(ye===`
|
|
17
|
-
`){de=0,ge-=I*1.35;continue}if(ye===" "||ye===" "){de+=se*(ye===" "?.75:3);continue}if(ye==="\r")continue;let Ce=ye.toUpperCase(),Ae=ye!==Ce&&ye>="a"&&ye<="z",Pe=ee[Ce]??ee["?"],Le=Ae?I*.76:I,Ne=Ae?re*.88:re;for(let Ge of Pe)for(let ze=0;ze<Ge.length-1;ze++){let Je=Ge[ze],je=Ge[ze+1];me(de+Je[0]*Ne,ge+Je[1]*Le,de+je[0]*Ne,ge+je[1]*Le,X,-Z*.5,Z*.5)}de+=Ae?se*.88:se}R(this,te,ue,ce,fe),_.center!==!1?this.center():this.computeBoundingBox()}}function ae(A){if(!A)return;let S=A,_=A.userData?.xr?.text??A.userData?.xr?.label??A.userData?.xr?.title??A.userData?.xr?.caption??A.userData?.xr?.spatialLabel;if(_!=null&&_!==!1){let I=S.geometry?.attributes?.position;if((!I||I.count===0)&&A.userData._textApplied!==!0){let W="",Q=.08,K=.015,Z;if(typeof _=="string"||typeof _=="number")W=String(_);else if(typeof _=="object"){let X=_;W=String(X.text??X.value??""),X.size!==void 0&&(Q=Number(X.size)||.08),(X.depth!==void 0||X.height!==void 0)&&(K=Number(X.depth??X.height)||Q*.2),(typeof X.color=="string"||typeof X.color=="number")&&(Z=X.color)}W.trim().length>0&&(S.geometry=new ne(W,{size:Q,depth:K}),A.userData._textApplied=!0,S.material instanceof h?Z!==void 0&&A.userData._autoTextColorApplied!==!0&&(S.material.color=new a(Z),A.userData._autoTextColorApplied=!0):S.material=new c({color:Z??16317180}))}}let O=A.userData?.csg;if(O&&typeof O=="object"&&A.userData._csgApplied!==!0&&S.geometry instanceof u&&S.geometry.attributes.position?.count>0){A.userData._csgApplied=!0;let I=Array.isArray(O)?O:[O],W=S.geometry;for(let Q of I){if(!Q||typeof Q!="object")continue;let K=Q,Z=String(K.op??K.operation??"subtract"),X=Z==="union"||Z==="intersect"?Z:"subtract",re=K.target??K.mesh??K.geometry;if(re instanceof f||re instanceof u)try{let se=X==="union"?H.union(S,re):X==="intersect"?H.intersect(S,re):H.subtract(S,re);S.geometry!==W&&S.geometry.dispose?.(),S.geometry=se.geometry}catch(se){typeof console<"u"&&console.warn("[three-live] userData.csg skipped:",se)}}}}let j={Path:v,Shape:d,ShapeGeometry:P,ExtrudeGeometry:B,TextGeometry:ne,CSG:H,MAX_CSG_TRIANGLES:p,MAX_BSP_DEPTH:m,MAX_TEXT_GEOMETRY_CHARS:g,MAX_SHAPE_POINTS:x,materializeDeclarativeGeometry:ae};return t&&typeof t=="object"&&(t.authorNamespace||(t.authorNamespace={}),Object.assign(t.authorNamespace,j),t._cadMaterialize=ae,t.materializeDeclarativeGeometry=A=>{t._cadMaterialize?.(A),t._lodMaterialize?.(A)}),j}var Pi={name:"cad",onRegister(){Ti(Tr);let e=Se(),t=e.threeNamespace??(typeof globalThis<"u"?globalThis.THREE:void 0);t&&Tr(t,e)}};function Ee(){let e=new Float32Array(16);return e[0]=1,e[5]=1,e[10]=1,e[15]=1,e}function Ri(e,t,r,i,s){let n=1/Math.tan(t/2);e.fill(0),e[0]=n/r,e[5]=n,e[11]=-1;let l=1/(i-s);return e[10]=(s+i)*l,e[14]=2*s*i*l,e}function Pr(e,t,r,i){let[s,n,l]=t,[a,o,u]=i,[h,c,f]=r,p=s-h,m=n-c,g=l-f,x=Math.hypot(p,m,g);x<=1e-5?(p=0,m=0,g=1):(p/=x,m/=x,g/=x);let b=o*g-u*m,v=u*p-a*g,d=a*m-o*p;x=Math.hypot(b,v,d),x<=1e-5?(b=0,v=0,d=0):(b/=x,v/=x,d/=x);let y=m*d-g*v,M=g*b-p*d,T=p*v-m*b;return x=Math.hypot(y,M,T),x<=1e-5?(y=0,M=0,T=0):(y/=x,M/=x,T/=x),e[0]=b,e[1]=y,e[2]=p,e[3]=0,e[4]=v,e[5]=M,e[6]=m,e[7]=0,e[8]=d,e[9]=T,e[10]=g,e[11]=0,e[12]=-(b*s+v*n+d*l),e[13]=-(y*s+M*n+T*l),e[14]=-(p*s+m*n+g*l),e[15]=1,e}function ke(e,t,r){let i=t[0],s=t[1],n=t[2],l=t[3],a=t[4],o=t[5],u=t[6],h=t[7],c=t[8],f=t[9],p=t[10],m=t[11],g=t[12],x=t[13],b=t[14],v=t[15],d=r[0],y=r[1],M=r[2],T=r[3];return e[0]=d*i+y*a+M*c+T*g,e[1]=d*s+y*o+M*f+T*x,e[2]=d*n+y*u+M*p+T*b,e[3]=d*l+y*h+M*m+T*v,d=r[4],y=r[5],M=r[6],T=r[7],e[4]=d*i+y*a+M*c+T*g,e[5]=d*s+y*o+M*f+T*x,e[6]=d*n+y*u+M*p+T*b,e[7]=d*l+y*h+M*m+T*v,d=r[8],y=r[9],M=r[10],T=r[11],e[8]=d*i+y*a+M*c+T*g,e[9]=d*s+y*o+M*f+T*x,e[10]=d*n+y*u+M*p+T*b,e[11]=d*l+y*h+M*m+T*v,d=r[12],y=r[13],M=r[14],T=r[15],e[12]=d*i+y*a+M*c+T*g,e[13]=d*s+y*o+M*f+T*x,e[14]=d*n+y*u+M*p+T*b,e[15]=d*l+y*h+M*m+T*v,e}function or(e,t,r,i){let s=t[0],n=t[1],l=t[2],a=t[3],o=s+s,u=n+n,h=l+l,c=s*o,f=s*u,p=s*h,m=n*u,g=n*h,x=l*h,b=a*o,v=a*u,d=a*h,y=i[0],M=i[1],T=i[2];return e[0]=(1-(m+x))*y,e[1]=(f+d)*y,e[2]=(p-v)*y,e[3]=0,e[4]=(f-d)*M,e[5]=(1-(c+x))*M,e[6]=(g+b)*M,e[7]=0,e[8]=(p+v)*T,e[9]=(g-b)*T,e[10]=(1-(c+m))*T,e[11]=0,e[12]=r[0],e[13]=r[1],e[14]=r[2],e[15]=1,e}function Ye(e,t,r=0){let i=t[0],s=t[1],n=t[2],l=t[4],a=t[5],o=t[6],u=t[8],h=t[9],c=t[10],f=c*a-o*h,p=-c*l+o*u,m=h*l-a*u,g=i*f+s*p+n*m;return!g||r>0&&(!Number.isFinite(g)||Math.abs(g)<=r)||(g=1/g,e[0]=f*g,e[1]=p*g,e[2]=m*g,e[3]=(-c*s+n*h)*g,e[4]=(c*i-n*u)*g,e[5]=(-h*i+s*u)*g,e[6]=(o*s-n*a)*g,e[7]=(-o*i+n*l)*g,e[8]=(a*i-s*l)*g),e}function Ci(e,t){let r=t[0],i=t[1],s=t[2],n=t[3],l=t[4],a=t[5],o=t[6],u=t[7],h=t[8],c=t[9],f=t[10],p=t[11],m=t[12],g=t[13],x=t[14],b=t[15],v=r*a-i*l,d=r*o-s*l,y=r*u-n*l,M=i*o-s*a,T=i*u-n*a,V=s*u-n*o,q=h*g-c*m,P=h*x-f*m,R=h*b-p*m,C=c*x-f*g,B=c*b-p*g,L=f*b-p*x,w=v*L-d*B+y*C+M*R-T*P+V*q;return w?(w=1/w,e[0]=(a*L-o*B+u*C)*w,e[1]=(s*B-i*L-n*C)*w,e[2]=(g*V-x*T+b*M)*w,e[3]=(f*T-c*V-p*M)*w,e[4]=(o*R-l*L-u*P)*w,e[5]=(r*L-s*R+n*P)*w,e[6]=(x*y-m*V-b*d)*w,e[7]=(h*V-f*y+p*d)*w,e[8]=(l*B-a*R+u*q)*w,e[9]=(i*R-r*B-n*q)*w,e[10]=(m*T-g*y+b*v)*w,e[11]=(c*y-h*T-p*v)*w,e[12]=(a*P-l*C-o*q)*w,e[13]=(r*C-i*P+s*q)*w,e[14]=(g*d-m*M-x*v)*w,e[15]=(h*M-c*d+f*v)*w,e):null}function Kn(e,t,r,i,s){let n=s[0]*t+s[4]*r+s[8]*i+s[12],l=s[1]*t+s[5]*r+s[9]*i+s[13],a=s[2]*t+s[6]*r+s[10]*i+s[14],o=s[3]*t+s[7]*r+s[11]*i+s[15],u=o!==0?1/o:1;e[0]=n*u,e[1]=l*u,e[2]=a*u}function Wo(e,t,r,i,s,n,l,a,o,u,h,c,f,p,m,g,x=0){let b=u-l,v=h-a,d=c-o,y=f-l,M=p-a,T=m-o,V=s*T-n*M,q=n*y-i*T,P=i*M-s*y,R=b*V+v*q+d*P;if(R>-1e-7&&R<1e-7)return!1;let C=1/R,B=e-l,L=t-a,w=r-o,ie=C*(B*V+L*q+w*P);if(ie<-x||ie>1+x)return!1;let oe=L*d-w*v,k=w*b-B*d,J=B*v-L*b,z=C*(i*oe+s*k+n*J);if(z<-x||ie+z>1+x)return!1;let Y=C*(y*oe+M*k+T*J);if(Y>1e-4&&Y<g.distance){g.distance=Y,g.point=[e+i*Y,t+s*Y,r+n*Y];let le=v*T-d*M,he=d*y-b*T,$=b*M-v*y,U=Math.hypot(le,he,$)||1;return g.normal=[le/U,he/U,$/U],!0}return!1}function Rr(e,t){let r=Array.isArray(e?.nodes)?e.nodes.length:0,i=[];for(let h=0;h<r;h++)i.push(Ee());if(r===0)return i;let s=new Set;for(let h of e.nodes)if(Array.isArray(h.children))for(let c of h.children)s.add(c);let n=new Set,l=128,a=(h,c,f=0)=>{if(f>l||h<0||h>=r||n.has(h))return;n.add(h);let p=e.nodes[h];if(!p)return;let m=Ee();if(t&&t[h])m.set(t[h]);else if(p.matrix&&p.matrix.length===16)m.set(p.matrix);else{let x=p.translation||[0,0,0],b=p.rotation||[0,0,0,1],v=p.scale||[1,1,1];or(m,b,x,v)}let g=i[h];if(c?ke(g,c,m):g.set(m),Array.isArray(p.children))for(let x of p.children)typeof x=="number"&&a(x,g,f+1)},o=[],u=e.scenes&&e.scenes[e.scene!==void 0?e.scene:0];if(u&&Array.isArray(u.nodes))o.push(...u.nodes);else for(let h=0;h<r;h++)s.has(h)||o.push(h);for(let h of o)a(h,null);for(let h=0;h<r;h++)!s.has(h)&&!o.includes(h)&&a(h,null);return i}function Ei(e,t){function r(o,u,h,c){let f=typeof o=="number"?o:Number(o);return Number.isFinite(f)?Math.max(u,Math.min(h,f)):c}function i(o,u){let h=o[0]*u[0]+o[1]*u[1]+o[2]*u[2]+1;if(h<1e-6){if(Math.abs(o[0])>Math.abs(o[2])){let x=Math.hypot(o[1],o[0])||1;return[-o[1]/x,o[0]/x,0,0]}let g=Math.hypot(o[2],o[1])||1;return[0,-o[2]/g,o[1]/g,0]}let c=o[1]*u[2]-o[2]*u[1],f=o[2]*u[0]-o[0]*u[2],p=o[0]*u[1]-o[1]*u[0],m=Math.hypot(c,f,p,h)||1;return[c/m,f/m,p/m,h/m]}function s(o,u,h,c,f){let p=u[0]-o[0],m=u[1]-o[1],g=u[2]-o[2],x=Math.hypot(p,m,g),b=h[0]-u[0],v=h[1]-u[1],d=h[2]-u[2],y=Math.hypot(b,v,d);if(x<1e-6||y<1e-6)return{rootPos:[o[0],o[1],o[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=[p/x,m/x,g/x],T=[b/y,v/y,d/y],V=c[0]-o[0],q=c[1]-o[1],P=c[2]-o[2],R=Math.hypot(V,q,P),C=R>1e-6?[V/R,q/R,P/R]:M,B=Math.abs(x-y)+1e-5,L=Math.max(B,x+y-1e-5),w=Math.max(B,Math.min(L,R>1e-6?R:B)),ie=r((x*x+w*w-y*y)/(2*x*w),-1,1,1),oe=Math.sqrt(Math.max(0,1-ie*ie)),k=f?f[0]-o[0]:p,J=f?f[1]-o[1]:m,z=f?f[2]-o[2]:g,Y=k*C[0]+J*C[1]+z*C[2],le=k-C[0]*Y,he=J-C[1]*Y,$=z-C[2]*Y,U=Math.hypot(le,he,$);if(U<=1e-6){let A=Math.abs(C[1])<.99?0:1,S=Math.abs(C[1])<.99?1:0,_=0;le=C[1]*_-C[2]*S,he=C[2]*A-C[0]*_,$=C[0]*S-C[1]*A,U=Math.hypot(le,he,$)||1}let N=[le/U,he/U,$/U],G=[o[0]+C[0]*(x*ie)+N[0]*(x*oe),o[1]+C[1]*(x*ie)+N[1]*(x*oe),o[2]+C[2]*(x*ie)+N[2]*(x*oe)],D=[o[0]+C[0]*w,o[1]+C[1]*w,o[2]+C[2]*w],F=D[0]-G[0],E=D[1]-G[1],H=D[2]-G[2],ee=Math.hypot(F,E,H),ne=ee>1e-6?[F/ee,E/ee,H/ee]:C,ae=[G[0]+ne[0]*y,G[1]+ne[1]*y,G[2]+ne[2]*y],j=[(G[0]-o[0])/x,(G[1]-o[1])/x,(G[2]-o[2])/x];return{rootPos:[o[0],o[1],o[2]],midPos:G,effectorPos:ae,rootRotation:i(M,j),midRotation:i(T,ne)}}function n(o,u,h=8,c=.001){let f=o.length;if(f<2)return{positions:o.map(R=>[R[0],R[1],R[2]]),rotations:[],iterations:0};let p=o.map(R=>[R[0],R[1],R[2]]),m=[],g=[],x=0;for(let R=0;R<f-1;R++){let C=p[R+1][0]-p[R][0],B=p[R+1][1]-p[R][1],L=p[R+1][2]-p[R][2],w=Math.hypot(C,B,L);m.push(w),x+=w,g.push(w>1e-6?[C/w,B/w,L/w]:[0,1,0])}let b=[p[0][0],p[0][1],p[0][2]],v=Math.round(r(h,1,32,8)),d=r(c,1e-5,.1,.001),y=u[0]-b[0],M=u[1]-b[1],T=u[2]-b[2],V=Math.hypot(y,M,T),q=0;if(V>=x&&x>1e-6){let R=V>1e-6?[y/V,M/V,T/V]:g[0];p[0]=[b[0],b[1],b[2]];for(let C=0;C<f-1;C++){let B=m[C];p[C+1]=[p[C][0]+R[0]*B,p[C][1]+R[1]*B,p[C][2]+R[2]*B]}q=1}else for(let R=1;R<=v;R++){let C=p[f-1];if(Math.hypot(C[0]-u[0],C[1]-u[1],C[2]-u[2])<=d)break;q=R;let B=(L,w,ie,oe,k)=>{let J=w[0]-L[0],z=w[1]-L[1],Y=w[2]-L[2],le=Math.hypot(J,z,Y);if(le>1e-6){let he=ie/le;return[L[0]+J*he,L[1]+z*he,L[2]+Y*he]}return[L[0]+oe[0]*ie*k,L[1]+oe[1]*ie*k,L[2]+oe[2]*ie*k]};p[f-1]=[u[0],u[1],u[2]];for(let L=f-2;L>=0;L--)p[L]=B(p[L+1],p[L],m[L],g[L],-1);p[0]=[b[0],b[1],b[2]];for(let L=0;L<f-1;L++)p[L+1]=B(p[L],p[L+1],m[L],g[L],1)}let P=[];for(let R=0;R<f-1;R++){let C=p[R+1][0]-p[R][0],B=p[R+1][1]-p[R][1],L=p[R+1][2]-p[R][2],w=Math.hypot(C,B,L),ie=w>1e-6?[C/w,B/w,L/w]:g[R];P.push(i(g[R],ie))}return{positions:p,rotations:P,iterations:q}}function l(o){if(!o||typeof o!="object"||Array.isArray(o))return null;let u=o;if(u.enabled===!1)return null;let h=d=>{if(typeof d!="string")return;let y=d.trim().slice(0,64);return/^[A-Za-z0-9_.:-]+$/.test(y)?y:void 0},c=d=>Array.isArray(d)&&d.length===3&&d.every(y=>typeof y=="number"&&Number.isFinite(y))?[r(d[0],-1e3,1e3,0),r(d[1],-1e3,1e3,0),r(d[2],-1e3,1e3,0)]:void 0,f=h(u.root),p=h(u.effector);if(!f||!p)return null;let m=h(u.mid),g=c(u.target)??h(u.target);if(!g)return null;let x=u.pole??u.poleTarget,b=c(x)??h(x),v=u.solver==="fabrik"?"fabrik":u.solver==="two-bone"||m?"two-bone":"fabrik";return{root:f,...m?{mid:m}:{},effector:p,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 a=Object.freeze({solveTwoBone:s,solveFABRIK:n,parseIKTrait:l});return t&&typeof t=="object"&&(t.authorNamespace=t.authorNamespace||{},t.authorNamespace.IKSolver=a),{clampNum:r,parseIKTrait:l,quatFromUnitVectors:i,solveTwoBoneIK:s,solveFABRIK:n,IKSolver:a}}var Wt=Ei(),Yn=Wt.clampNum,Xo=Wt.parseIKTrait,Cr=Wt.quatFromUnitVectors,Li=Wt.solveTwoBoneIK,Ni=Wt.solveFABRIK,Zn=Wt.IKSolver;function _i(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 qo(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 Ko(e,t,r,i,s){let n=Yn(s,0,1,1),l=t[0]+(r[0]-t[0])*n,a=t[1]+(r[1]-t[1])*n,o=t[2]+(r[2]-t[2])*n,u=l-e[0],h=a-e[1],c=o-e[2],f=Math.hypot(u,h,c);if(f>1e-6&&i>1e-6){let b=i/f;return[e[0]+u*b,e[1]+h*b,e[2]+c*b]}let p=r[0]-e[0],m=r[1]-e[1],g=r[2]-e[2],x=Math.hypot(p,m,g);if(x>1e-6&&i>1e-6){let b=i/x;return[e[0]+p*b,e[1]+m*b,e[2]+g*b]}return[l,a,o]}function Yo(e,t){let r=e?.modelRootMatrix;if(!r||r.length!==16)return t;let i=new Float32Array(16);return Ci(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 Di(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 Ii(e,t,r){if(Array.isArray(e))return[e[0],e[1],e[2]];let i=t.get(e);if(i)return _i(i);let s;if(e==="head"?s=r?.headPose?.position??r?.headPose??r?.cameraPosition:e==="hand-left"?s=r?.handPoses?.left?.position??r?.handPoses?.left??r?.hands?.left?.position??r?.hands?.left:e==="hand-right"&&(s=r?.handPoses?.right?.position??r?.handPoses?.right??r?.hands?.right?.position??r?.hands?.right),(Array.isArray(s)||ArrayBuffer.isView(s))&&s.length>=3){let n=s;return Yo(r,[n[0],n[1],n[2]])}return null}function ki(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 Zo(e){return[-e[0],-e[1],-e[2],e[3]]}function Fi(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 Qo(e,t){if(t>=1)return e;if(t<=0)return[0,0,0,1];let[r,i,s,n]=e;n<0&&(r=-r,i=-i,s=-s,n=-n);let l=Math.acos(Math.min(1,n)),a=Math.sin(l);if(a<1e-9)return[0,0,0,1];let o=Math.sin(l*t)/a;return Fi([r*o,i*o,s*o,Math.cos(l*t)])}function Jo(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,s=e[0]/t,n=e[1]/t,l=e[2]/t,a=e[4]/r,o=e[5]/r,u=e[6]/r,h=e[8]/i,c=e[9]/i,f=e[10]/i,p=s+o+f,m;if(p>0){let g=Math.sqrt(p+1)*2;m=[(u-c)/g,(h-l)/g,(n-a)/g,.25*g]}else if(s>o&&s>f){let g=Math.sqrt(1+s-o-f)*2;m=[.25*g,(a+n)/g,(h+l)/g,(u-c)/g]}else if(o>f){let g=Math.sqrt(1+o-s-f)*2;m=[(a+n)/g,.25*g,(c+u)/g,(h-l)/g]}else{let g=Math.sqrt(1+f-s-o)*2;m=[(h+l)/g,(c+u)/g,.25*g,(n-a)/g]}return Fi(m)}function el(e,t,r){let[i,s,n,l]=r,a=1-2*(s*s+n*n),o=2*(i*s-n*l),u=2*(i*n+s*l),h=2*(i*s+n*l),c=1-2*(i*i+n*n),f=2*(s*n-i*l),p=2*(i*n-s*l),m=2*(s*n+i*l),g=1-2*(i*i+s*s);for(let x=0;x<3;x++){let b=t[x*4],v=t[x*4+1],d=t[x*4+2];e[x*4]=a*b+o*v+u*d,e[x*4+1]=h*b+c*v+f*d,e[x*4+2]=p*b+m*v+g*d}}function Er(e,t){let r=t[0]-e[0],i=t[1]-e[1],s=t[2]-e[2],n=Math.hypot(r,i,s);return n>1e-9?[r/n,i/n,s/n]:null}function Qn(e){e?.normalMatrix&&e?.transform&&Ye(e.normalMatrix,e.transform)}var Jn=new WeakMap;function tl(e){let t=Jn.get(e);return t||(t=new Int32Array(e.nodes.length).fill(-1),e.nodes.forEach((r,i)=>{for(let s of Array.isArray(r?.children)?r.children:[])typeof s=="number"&&s>=0&&s<t.length&&(t[s]=i)}),Jn.set(e,t)),t}function rl(e,t,r){let i=e?.gltf,s=i?.nodes;if(!Array.isArray(s)||s.length===0)return!1;let n=new Map;s.forEach((P,R)=>{typeof P?.name=="string"&&P.name&&!n.has(P.name)&&n.set(P.name,R)});let l=(t.mid?[t.root,t.mid,t.effector]:[t.root,t.effector]).map(P=>n.get(P));if(l.some(P=>P===void 0))return!1;let a=l,o=tl(i);for(let P=1;P<a.length;P++){let R=o[a[P]],C=0;for(;R>=0&&R!==a[P-1]&&C++<256;)R=o[R];if(R!==a[P-1])return!1}let u=a[0],h=e.initialNodeTransforms,c=new Map,f=[],p=[u];for(;p.length&&f.length<4096;){let P=p.pop();if(c.has(P))continue;let R=h?.[P],C=s[P];c.set(P,{t:R?[R.t[0],R.t[1],R.t[2]]:C?.translation?[...C.translation]:[0,0,0],r:R?[R.r[0],R.r[1],R.r[2],R.r[3]]:C?.rotation?[...C.rotation]:[0,0,0,1],s:R?[R.s[0],R.s[1],R.s[2]]:C?.scale?[...C.scale]:[1,1,1]}),f.push(P);for(let B of Array.isArray(C?.children)?C.children:[])typeof B=="number"&&p.push(B)}let m=o[u],g=m>=0&&e.worldMatrices?.[m]?.length===16?Float32Array.from(e.worldMatrices[m]):Ee(),x=new Map,b=()=>{let P=(R,C)=>{let B=c.get(R);if(!B)return;let L=Ee();or(L,B.r,B.t,B.s);let w=Ee();ke(w,C,L),x.set(R,w);for(let ie of Array.isArray(s[R]?.children)?s[R].children:[])typeof ie=="number"&&P(ie,w)};P(u,g)},v=P=>{let R=x.get(P);return[R[12],R[13],R[14]]};b();let d=a.map(v),y=P=>{if(typeof P=="string"&&!r.has(P)){let R=n.get(P),C=R!==void 0?x.get(R)??e.worldMatrices?.[R]:void 0;if(C&&C.length===16)return[C[12],C[13],C[14]]}return Ii(P,r,e)},M=y(t.target);if(!M)return!0;let T=t.pole?y(t.pole)??void 0:void 0,V=ea(d,t,M,T),q=Yn(t.weight,0,1,1);for(let P=0;P<a.length-1;P++){let R=Er(v(a[P]),v(a[P+1])),C=Er(V[P],V[P+1]);if(!R||!C)continue;let B=Qo(Cr(R,C),q),L=a[P],w=o[L],ie=w===m||w<0?g:x.get(w)??g,oe=Jo(ie),k=c.get(L);k.r=Fi(ki(Zo(oe),ki(B,ki(oe,k.r)))),b()}if(Array.isArray(e.worldMatrices))for(let[P,R]of x)e.worldMatrices[P]?.set&&e.worldMatrices[P].set(R);for(let P of e.meshes??[]){let R=x.get(P?.nodeIndex);R&&P.transform?.set&&(P.transform.set(R),Qn(P))}return!0}function ea(e,t,r,i){if(t.solver==="two-bone"&&e.length===3){let s=Li(e[0],e[1],e[2],r,i);return[e[0],s.midPos,s.effectorPos]}return Ni(e,r,t.iterations,t.tolerance).positions}function il(e,t,r){let i=e.__ikRestOffsets,s=e.__ikRestMats;if(!(!i||!s))for(let n=0;n<t.length-1;n++){let l=t[n]?.transform??t[n]?.modelMatrix,a=s[n],o=Er([0,0,0],i[n]),u=Er(r[n],r[n+1]);!l||l.length<16||!a||a.length<16||!o||!u||(el(l,a,Cr(o,u)),Qn(t[n]))}}var Vi={name:"ik",onRegister(){let e=Se();Ti(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 s=i?.userData?.xr?.ik??i?.extras?.xr?.ik??i?.extensions?.ANDROID_xr_scenecore?.ik;if(!s)continue;let n=Xo(s);if(!n||n.weight<=0)continue;if(!r){r=new Map;for(let d of t)d&&typeof d.name=="string"&&d.name&&r.set(d.name,d)}if(rl(e,n,r))continue;let l=r.get(n.root),a=r.get(n.effector),o=n.mid?r.get(n.mid):void 0;if(l||Di(i,n.root),a||Di(i,n.effector),n.mid&&!o&&Di(i,n.mid),!l||!a)continue;let u=Ii(n.target,r,e);if(!u)continue;let h=n.pole?Ii(n.pole,r,e)??void 0:void 0,c=o?[l,o,a]:[l,a],f=c.map(d=>d.name||"").join(">");if(!i.__ikRestOffsets||i.__ikRestKey!==f){let d=c.map(_i),y=[];for(let M=0;M<d.length-1;M++)y.push([d[M+1][0]-d[M][0],d[M+1][1]-d[M][1],d[M+1][2]-d[M][2]]);i.__ikRestOffsets=y,i.__ikRestKey=f,i.__ikRestMats=c.map(M=>Array.from(M.transform??M.modelMatrix??[]))}let p=i.__ikRestOffsets,m=[_i(l)],g=[];for(let d=0;d<p.length;d++){let y=m[d],M=p[d];m.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=ea(m,n,u,h),b=m[0],v=[m[0]];for(let d=1;d<c.length;d++){let y=p[d-1],M=[b[0]+y[0],b[1]+y[1],b[2]+y[2]],T=[b[0]+(x[d][0]-x[d-1][0]),b[1]+(x[d][1]-x[d-1][1]),b[2]+(x[d][2]-x[d-1][2])],V=Ko(b,M,T,g[d-1],n.weight);qo(c[d],V),b=V,v.push(V)}il(i,c,v)}}};function lr(e,t){let r=(h,c,f,p)=>{let m=typeof h=="number"?h:Number(h);return Number.isFinite(m)?Math.max(c,Math.min(f,m)):p};function i(h,c,f=0,p=.05,m){if(!h||!h.length)return-1;let g=h[0]>0?[0,...h]:h,x=Number.isFinite(c)?Math.max(0,c):0,b=Number.isFinite(p)?Math.max(0,Math.min(.5,p)):.05;if(typeof m=="number"&&Number.isFinite(m)&&m>0){let y=f===-1?m*(1-b):m*(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(f<0||f>=g.length||f===v)return v;if(v>f){let y=f;for(let M=f+1;M<=v&&x>=g[M]*(1+b);M++)y=M;return y}let d=f;for(let y=f;y>v&&x<g[y]*(1-b);y--)d=y-1;return d}function s(h){if(!h)return null;let c=h===!0?{distances:[4,10],ratios:[.5,.25]}:Array.isArray(h)?{distances:h}:typeof h=="object"?h:null;if(!c||c.enabled===!1)return null;let f=r(c.hysteresis,0,.5,.05),p=[],m;if(Array.isArray(c.levels)&&c.levels.length>0){let v=c.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 T=M,V=r(T.distance,0,1e4,y===0?0:y*4),q=typeof T.hysteresis=="number"?r(T.hysteresis,0,.5,f):void 0,P=typeof T.ratio=="number"?r(T.ratio,.05,1,.5):void 0,R=typeof T.childIndex=="number"&&Number.isFinite(T.childIndex)?Math.max(0,Math.round(T.childIndex)):void 0,C=typeof T.node=="string"&&/^[A-Za-z0-9_.:-]+$/.test(T.node.trim())?T.node.trim().slice(0,64):void 0;p.push({distance:V,...q!==void 0?{hysteresis:q}:{},...P!==void 0?{ratio:P}:{},...R!==void 0?{childIndex:R}:{},...C?{node:C}:{}})}p.sort((y,M)=>y.distance-M.distance),p.length>0&&p[0].distance>0&&p.unshift({distance:0,childIndex:0});let d=0;p=p.slice(0,8).map((y,M)=>{let T=M===0?0:Math.max(d,y.distance);return d=T,{...y,distance:T,childIndex:y.childIndex??M}})}if(Array.isArray(c.ratios)&&c.ratios.length>0){let v=[];for(let d of c.ratios.slice(0,7))typeof d=="number"&&v.push(r(d,.05,1,.5));v.length>0&&(m=v)}if(p.length===0){let v=Array.isArray(c.distances)?c.distances:[],d=[];for(let M of v.slice(0,8))typeof M=="number"&&d.push(r(M,0,1e4,4));if(d.length===0&&m&&m.length>0)for(let M=0;M<m.length;M++)d.push((M+1)*4);if(d.length===0&&c.cullDistance===void 0)return null;d.length===0||d[0]>0?d.unshift(0):m&&m.length===d.length&&m[0]===1&&(m=m.slice(1));let y=0;for(let M=0;M<Math.min(8,d.length);M++){let T=M===0?0:Math.max(y,d[M]);y=T;let V=M>0&&m?m[M-1]:void 0;p.push({distance:T,childIndex:M,...V!==void 0?{ratio:V}:{}})}}else if(!m){let v=[];for(let d=1;d<p.length;d++)typeof p[d].ratio=="number"&&v.push(p[d].ratio);v.length>0&&(m=v)}let g=p.map(v=>v.distance),x=g[g.length-1]??0,b=c.cullDistance!==void 0&&c.cullDistance!==null&&c.cullDistance!==!1?r(c.cullDistance,Math.max(1,x),1e4,100):void 0;return{levels:p,distances:g,...m?{ratios:m}:{},hysteresis:f,...b!==void 0?{cullDistance:b}:{}}}function n(h,c){let f=h?.attributes?.position;if(!f||!f.array||f.count<3)return h;let p=r(c,.05,1,.5),m=f.array,g=f.count,x=h.attributes?.normal?.array,b=h.attributes?.uv?.array,v=h.index?.array,d=Math.floor((v?v.length:g)/3);if(d<1)return h;let y=Math.max(1,Math.min(d,Math.round(d*p))),M=1/0,T=1/0,V=1/0,q=-1/0,P=-1/0,R=-1/0;for(let U=0;U<g;U++){let N=m[U*3],G=m[U*3+1],D=m[U*3+2];N<M&&(M=N),G<T&&(T=G),D<V&&(V=D),N>q&&(q=N),G>P&&(P=G),D>R&&(R=D)}let C=Math.max(1e-5,q-M),B=Math.max(1e-5,P-T),L=Math.max(1e-5,R-V),w=Math.max(C,B,L),ie=U=>{let N=Math.max(1,Math.round(C/w*U)),G=Math.max(1,Math.round(B/w*U)),D=Math.max(1,Math.round(L/w*U)),F=new Map,E=new Int32Array(g),H=[],ee=[],ne=[],ae=[];for(let I=0;I<g;I++){let W=m[I*3],Q=m[I*3+1],K=m[I*3+2],Z=Math.min(N-1,Math.max(0,Math.floor((W-M)/C*N))),X=Math.min(G-1,Math.max(0,Math.floor((Q-T)/B*G))),re=Math.min(D-1,Math.max(0,Math.floor((K-V)/L*D))),se=Z+X*N+re*N*G,te=F.get(se);te===void 0?(te=ae.length,F.set(se,te),H.push(W,Q,K),x&&ee.push(x[I*3],x[I*3+1],x[I*3+2]),b&&ne.push(b[I*2],b[I*2+1]),ae.push(1)):(H[te*3]+=W,H[te*3+1]+=Q,H[te*3+2]+=K,x&&(ee[te*3]+=x[I*3],ee[te*3+1]+=x[I*3+1],ee[te*3+2]+=x[I*3+2]),ae[te]++),E[I]=te}let j=[],A=new Set;for(let I=0;I<d;I++){let W=v?v[I*3]:I*3,Q=v?v[I*3+1]:I*3+1,K=v?v[I*3+2]:I*3+2,Z=E[W],X=E[Q],re=E[K];if(Z===X||X===re||re===Z)continue;let se=Math.min(Z,X,re),te=Math.max(Z,X,re),ue=Z+X+re-se-te,ce=`${se}_${ue}_${te}`;A.has(ce)||(A.add(ce),j.push(Z,X,re))}let S=ae.length,_=new Float32Array(S*3),O=x?new Float32Array(S*3):null;for(let I=0;I<S;I++){let W=1/ae[I];if(_[I*3]=H[I*3]*W,_[I*3+1]=H[I*3+1]*W,_[I*3+2]=H[I*3+2]*W,O){let Q=ee[I*3],K=ee[I*3+1],Z=ee[I*3+2],X=Math.hypot(Q,K,Z)||1;O[I*3]=Q/X,O[I*3+1]=K/X,O[I*3+2]=Z/X}}return{pos:_,norm:O,uv:b?new Float32Array(ne):null,tris:j,triCount:j.length/3,vertCount:S}},oe=Math.max(2,Math.round(Math.sqrt(y/4))),k=ie(oe);if(k.triCount>y*1.25&&oe>2){let U=Math.max(2,Math.round(oe*Math.sqrt(y/k.triCount)));if(U!==oe){let N=ie(U);N.triCount>=Math.min(4,y)&&(k=N)}}else if(k.triCount<Math.min(4,y)){let U=ie(Math.max(oe*2,8));U.triCount>k.triCount&&(k=U)}let J=k.tris;if(p<1&&k.triCount>y){let U=[],N=k.triCount/y;for(let G=0;G<y;G++){let D=Math.min(k.triCount-1,Math.floor(G*N));U.push(k.tris[D*3],k.tris[D*3+1],k.tris[D*3+2])}J=U}if(J.length<3){J=[];for(let U=0;U<y*3;U++)J.push(v?v[U]:U);k={pos:m.slice(),norm:x?x.slice():null,uv:b?b.slice():null,tris:J,triCount:y,vertCount:g}}let z=e??t?.threeNamespace??(typeof globalThis<"u"?globalThis.THREE:void 0),Y=z?.BufferGeometry??h.constructor,le=z?.BufferAttribute??f.constructor,he=new Y;he.setAttribute("position",new le(k.pos,3)),k.norm&&he.setAttribute("normal",new le(k.norm,3)),k.uv&&he.setAttribute("uv",new le(k.uv,2));let $=k.vertCount>65535?new Uint32Array(J):new Uint16Array(J);return typeof he.setIndex=="function"?he.setIndex(new le($,1)):he.index=new le($,1),he}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 c of h)c&&(c.parent=this,this.children.push(c));return this}};class a extends l{constructor(){super(),this.isLOD=!0,this.type="LOD",this.autoUpdate=!0,this.levels=[],this._currentLevel=0}addLevel(c,f=0,p=.05){if(!c)return this;let m=Math.max(0,Number.isFinite(Number(f))?Number(f):0),g=r(p,0,.5,.05),x=this.levels.length;for(let d=0;d<this.levels.length;d++)if(m<this.levels[d].distance){x=d;break}this.levels.splice(x,0,{object:c,distance:m,hysteresis:g}),this.add(c);let b=this.levels.map(d=>d.object),v=this.children.filter(d=>!b.includes(d));this.children=[...b,...v];for(let d=0;d<this.levels.length;d++)this.levels[d].object.visible=d===this._currentLevel;return this.syncUserDataTrait(),this}getCurrentLevel(){return this._currentLevel}getObjectForDistance(c){if(!this.levels.length)return null;let f=i(this.levels.map(p=>p.distance),c,this._currentLevel,this.levels[0]?.hysteresis??.05,this.userData?.xr?.lod?.cullDistance);return f>=0&&f<this.levels.length?this.levels[f].object:null}update(c){if(this.levels.length===0||!c)return;let f=c.position??{x:0,y:0,z:0},p=this.position??{x:0,y:0,z:0},m=Math.hypot((Number(f.x)||0)-(Number(p.x)||0),(Number(f.y)||0)-(Number(p.y)||0),(Number(f.z)||0)-(Number(p.z)||0)),g=i(this.levels.map(x=>x.distance),m,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 c=this.userData.xr.lod?.cullDistance;this.userData.xr.lod={levels:this.levels.map((f,p)=>({distance:f.distance,hysteresis:f.hysteresis,childIndex:p,...f.object?.name?{node:f.object.name}:{}})),distances:this.levels.map(f=>f.distance),hysteresis:this.levels[0]?.hysteresis??.05,...c!==void 0?{cullDistance:c}:{}}}}function o(h){if(!h||h._lodMaterialized||!h.userData?.xr?.lod||h.isLOD||Array.isArray(h.children)&&h.children.length>0)return;let c=h.geometry?.attributes?.position;if(!c||!c.array||c.count<3)return;let f=s(h.userData.xr.lod);if(!f||f.levels.length<2)return;h._lodMaterialized=!0;let p=h.geometry;h._lodOriginalGeometry=p;let m=e??t?.threeNamespace??(typeof globalThis<"u"?globalThis.THREE:void 0),g=m?.Mesh??h.constructor,x=m?.BufferGeometry??p.constructor,b=typeof h.name=="string"&&h.name.trim()?h.name.trim():"Mesh",v=new g(p,h.material);v.name=`${b}_LOD0`,v.visible=!0,v.castShadow=!!h.castShadow,v.receiveShadow=!!h.receiveShadow,h.add(v);for(let d=1;d<f.levels.length;d++){let y=f.levels[d].ratio??f.ratios?.[d-1]??Math.max(.05,Math.pow(.5,d)),M=n(p,y),T=new g(M,h.material);T.name=`${b}_LOD${d}`,T.visible=!1,T.castShadow=!!h.castShadow,T.receiveShadow=!!h.receiveShadow,h.add(T)}h.geometry=new x,h.userData.xr.lod={...f,levels:f.levels.map((d,y)=>({...d,childIndex:y,node:`${b}_LOD${y}`}))}}let u={LOD:a,decimateGeometry:n,selectLodLevelIndex:i,parseLod:s,materializeLodGeometry:o};return t&&typeof t=="object"&&(t.authorNamespace||(t.authorNamespace={}),Object.assign(t.authorNamespace,{LOD:a,decimateGeometry:n}),t._lodMaterialize=o,t.materializeDeclarativeGeometry=h=>{t._cadMaterialize?.(h),t._lodMaterialize?.(h)}),u}var ur=lr(),ta=ur.decimateGeometry,Lr=ur.selectLodLevelIndex,Nr=ur.parseLod,Eu=ur.materializeLodGeometry,ra=ur.LOD,hr=new WeakMap;function ia(e){return e&&typeof e=="object"?hr.get(e):void 0}var Oi=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 s=t.get(i.nodeIndex);s||(s=[],t.set(i.nodeIndex,s)),s.push(i)}let r=i=>{let s=[],n=new Set,l=[i];for(;l.length>0;){let a=l.pop();if(n.has(a)||a<0||a>=e.length)continue;n.add(a);let o=t.get(a);o&&s.push(...o);let u=e[a]?.children;if(Array.isArray(u))for(let h=u.length-1;h>=0;h--)typeof u[h]=="number"&&l.push(u[h])}return s};for(let i=0;i<e.length;i++){let s=e[i];if(!s||typeof s!="object")continue;let n=s.extras?.xr?.lod??s.extensions?.ANDROID_xr_scenecore?.lod??s.extensions?.MOZ_hubs_components?.lod,l=Array.isArray(s.extensions?.MSFT_lod?.ids)?s.extensions.MSFT_lod.ids.filter(p=>typeof p=="number"&&Number.isInteger(p)&&p>=0&&p<e.length):[],a=Nr(n);if(!a&&l.length>0&&(a=Nr({distances:l.map((p,m)=>m*4)})),!a)continue;let o=l.length>0?l:Array.isArray(s.children)?s.children.filter(p=>typeof p=="number"&&Number.isInteger(p)&&p>=0&&p<e.length):[],u=[],h=[];if(o.length>0){let p=Math.min(o.length,a.levels.length);for(let m=0;m<p;m++){let g=o[m];u.push(g),h.push(r(g))}}else{let p=t.get(i)??[];if(p.length===0)continue;u.push(i),h.push(p)}let c=a.distances.slice(0,h.length);c.length===0&&c.push(0);let f={nodeIndex:i,name:typeof s.name=="string"?s.name:`LOD_${i}`,distances:c,hysteresis:a.hysteresis,...a.cullDistance!==void 0?{cullDistance:a.cullDistance}:{},childNodeIndices:u,levelMeshes:h,activeLevelIndex:0,lastDistance:0};this.applyGroupVisibility(f,0),this.groups.push(f)}}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 s=Lr(r.distances,r.lastDistance,r.activeLevelIndex,r.hysteresis,r.cullDistance);r.activeLevelIndex=s,this.applyGroupVisibility(r,s);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 s=Array.isArray(t)&&i.nodeIndex<t.length?t[i.nodeIndex]:null,n=s&&s[12]||0,l=s&&s[13]||0,a=s&&s[14]||0,o=r?r[0]*n+r[4]*l+r[8]*a+r[12]:n,u=r?r[1]*n+r[5]*l+r[9]*a+r[13]:l,h=r?r[2]*n+r[6]*l+r[10]*a+r[14]:a,c=Math.hypot((e[0]||0)-o,(e[1]||0)-u,(e[2]||0)-h);if(i.lastDistance=c,i.forcedLevelIndex!==void 0&&i.forcedLevelIndex!==null){i.activeLevelIndex!==i.forcedLevelIndex&&(i.activeLevelIndex=i.forcedLevelIndex,this.applyGroupVisibility(i,i.forcedLevelIndex));continue}let f=Lr(i.distances,c,i.activeLevelIndex,i.hysteresis,i.cullDistance);f!==i.activeLevelIndex&&(i.activeLevelIndex=f,this.applyGroupVisibility(i,f))}}applyGroupVisibility(e,t){let r=this.gltf?.nodes;for(let i=0;i<e.levelMeshes.length;i++){let s=i===t;for(let a of e.levelMeshes[i])a.visible=s;let n=e.childNodeIndices[i],l=Array.isArray(r)?r[n]:null;l&&typeof l=="object"&&(l.visible=s,l.extensions=l.extensions||{},l.extensions.KHR_node_visibility={visible:s})}}},Ui={name:"lod",onRegister(){Ti(lr);let e=Se(),t=e.threeNamespace??(typeof globalThis<"u"?globalThis.THREE:void 0);lr(t,e)},onLoadModel(e,t){!e||typeof e!="object"||hr.set(e,new Oi(e,t))},onUpdate(e){let t=hr.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},s=r?.radius??3,n=r?.phi??0,l=r?.theta??0,a=Math.cos(n),o=(i.x||0)+s*a*Math.sin(l),u=(i.y||0)+s*Math.sin(n),h=(i.z||0)+s*a*Math.cos(l);t.update([o,u,h])},onBeforeDrawScene(e,t,r,i){let s=hr.get(e);s&&s.update(i)},onDestroy(e,t){t&&typeof t=="object"&&hr.delete(t)}},sl={5120:1,5121:1,5122:2,5123:2,5125:4,5126:4};function Xt(e,t,r,i){if(!r||r.bufferView===void 0)return null;let s=e.bufferViews?.[r.bufferView];if(!s)return null;let n=Number(r.count??0);if(!Number.isInteger(n)||n<=0)return null;let l=r.componentType??5126,a=sl[l];if(!a)throw new RangeError(`glTF accessor has unsupported componentType ${l}`);let o=a*i,u=s.byteStride&&s.byteStride>0?s.byteStride:o,h=(s.byteOffset||0)+(r.byteOffset||0);if(!Number.isInteger(h)||h<0||u<o||h+(n-1)*u+o>t.byteLength)throw new RangeError(`glTF accessor reads past the end of the binary buffer (${t.byteLength} bytes)`);if(l===5126&&u===o&&h%4===0)return new Float32Array(t,h,n*i);let c=new DataView(t),f=r.normalized===!0,p=new Float32Array(n*i);for(let m=0;m<n;m++){let g=h+m*u;for(let x=0;x<i;x++){let b=g+x*a,v;switch(l){case 5126:v=c.getFloat32(b,!0);break;case 5120:v=c.getInt8(b),f&&(v=Math.max(v/127,-1));break;case 5121:v=c.getUint8(b),f&&(v/=255);break;case 5122:v=c.getInt16(b,!0),f&&(v=Math.max(v/32767,-1));break;case 5123:v=c.getUint16(b,!0),f&&(v/=65535);break;default:v=c.getUint32(b,!0),f&&(v/=4294967295)}p[m*i+x]=v}}return p}function nl(e,t){let r=Number(t.offset?.[0]??0)||0,i=Number(t.offset?.[1]??0)||0,s=Number(t.scale?.[0]??1),n=Number(t.scale?.[1]??1),l=Number(t.rotation??0)||0,a=Math.cos(l),o=Math.sin(l),u=(Number.isFinite(s)?s:1)*a,h=(Number.isFinite(s)?s:1)*o,c=-(Number.isFinite(n)?n:1)*o,f=(Number.isFinite(n)?n:1)*a;for(let p=0;p+1<e.length;p+=2){let m=e[p],g=e[p+1];e[p]=u*m+h*g+r,e[p+1]=c*m+f*g+i}}function qt(e,t,r,i=!0){let s=[],n=null;try{for(let[l,a]of[[35633,t],[35632,r]]){let o=e.createShader(l);if(!o){if(i)throw new Error("Shader allocation failed");return null}if(s.push(o),e.shaderSource(o,a),e.compileShader(o),e.getShaderParameter&&!e.getShaderParameter(o,35713)){if(i)throw new Error(`Shader compile error: ${e.getShaderInfoLog(o)}`);return null}}if(n=e.createProgram(),!n){if(i)throw new Error("Program allocation failed");return null}for(let l of s)e.attachShader(n,l);if(e.linkProgram(n),e.getProgramParameter&&!e.getProgramParameter(n,35714)){let l=i?e.getProgramInfoLog(n):null;if(e.deleteProgram?.(n),n=null,i)throw new Error(`Program link error: ${l}`);return null}return n}finally{for(let l of s)n&&e.detachShader?.(n,l),e.deleteShader?.(l)}}var sa=["neutral","reinhard","none","aces","agx"];function Kt(e){let t=String(e??"").trim().toLowerCase();return sa.includes(t)?t:"neutral"}function al(e){return sa.indexOf(Kt(e))}function ol(e){return new TextDecoder().decode(e)}var na=Se().decoders;function ll(e,t){na.set(e.toLowerCase(),t)}function Yt(e){return na.get(e.toLowerCase())}function aa(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 f=r.getUint8(0);throw f===123||f===32||f===10||f===13?new Error("[three-live] Multi-file JSON .gltf is not supported for performance reasons. Please pack your asset into a single binary .glb file."):new Error(`Invalid GLB magic: 0x${i.toString(16)}`)}let s=r.getUint32(4,!0);if(s!==2)throw new Error(`Unsupported GLB version: ${s}`);let n=r.getUint32(8,!0),l=12,a=null,o=null;for(;l+8<=n&&l+8<=t.byteLength;){let f=r.getUint32(l,!0),p=r.getUint32(l+4,!0),m=l+8;if(m+f>t.byteLength)throw new Error(`Truncated GLB chunk: required ${m+f} bytes, buffer has ${t.byteLength}`);if(p===1313821514){let g=new Uint8Array(t,m,f),x=ol(g);a=JSON.parse(x,(b,v)=>b==="__proto__"||b==="constructor"||b==="prototype"?void 0:v)}else p===5130562&&(o=t.slice(m,m+f));l=m+f}if(!a)throw new Error("Missing JSON chunk in GLB");let u=a.extensionsRequired||[];if(u.includes("KHR_draco_mesh_compression")&&!Yt("draco"))throw new Error("Model requires KHR_draco_mesh_compression. Register a decoder via ThreeLiveElement.registerDecoder('draco', decoder).");for(let f of["EXT_meshopt_compression","KHR_meshopt_compression"])if(u.includes(f)&&!Yt("meshopt"))throw new Error(`Model requires ${f}. Register a decoder via ThreeLiveElement.registerDecoder('meshopt', decoder).`);if(u.includes("KHR_texture_basisu")&&!Yt("ktx2"))throw new Error("Model requires KHR_texture_basisu. Register a decoder via ThreeLiveElement.registerDecoder('ktx2', decoder).");let h=o||new ArrayBuffer(0),c={gltf:a,bin:h,animations:[]};for(let f of Fe)f.onParseGLB?.(c);return c}function ul(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 Dt(e){if(ul(e))return e;if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return aa(e);throw new TypeError("Invalid 3D model input: expected GLBData ({ gltf, bin }) or binary GLB (ArrayBuffer / ArrayBufferView).")}var oa=`#version 300 es
|
|
16
|
+
*/var j0=Object.defineProperty,G0=(e,t)=>{for(var r in t)j0(e,r,{get:t[r],enumerable:!0})},Gc={};G0(Gc,{AIVoiceSession:()=>vu,AmbientLight:()=>Fa,BoxGeometry:()=>La,BufferAttribute:()=>zt,BufferGeometry:()=>$t,Camera:()=>za,CapsuleGeometry:()=>Tl,CatmullRomCurve3:()=>Jo,CircleGeometry:()=>Pl,Clock:()=>ml,Color:()=>Br,ConeGeometry:()=>Wo,CubicBezierCurve3:()=>Zo,Curve3:()=>hi,CylinderGeometry:()=>Ra,DataTexture:()=>tl,DirectionalLight:()=>ul,DodecahedronGeometry:()=>Al,EdgesGeometry:()=>El,Euler:()=>Ca,Float32BufferAttribute:()=>Oo,Group:()=>ll,HemisphereLight:()=>Za,IKSolver:()=>eh,IMAGE_SYSTEM_PROMPT:()=>eu,IcosahedronGeometry:()=>Sl,InstancedMesh:()=>Da,InteractivityVM:()=>Qu,LOD:()=>ah,LatheGeometry:()=>Ia,Light:()=>fi,LightShadow:()=>ka,Line:()=>Pi,LineBasicMaterial:()=>zn,LineCurve3:()=>Yo,LineDashedMaterial:()=>Nl,LineLoop:()=>Ll,LineSegments:()=>Rl,LodController:()=>wo,MAX_BSP_DEPTH:()=>Xc,MAX_CSG_TRIANGLES:()=>Kc,MAX_INSTANCES_PER_MESH:()=>Hi,MAX_SHADOW_LIGHTS:()=>Jn,MAX_SHAPE_POINTS:()=>Qc,MAX_TEXT_GEOMETRY_CHARS:()=>Yc,MAX_TSL_NODES:()=>Ah,MAX_TSL_UNIFORMS:()=>Th,Material:()=>_r,MathUtils:()=>Uo,Matrix3:()=>zo,Matrix4:()=>Ai,Mesh:()=>Yr,MeshBasicMaterial:()=>nl,MeshLambertMaterial:()=>al,MeshPhongMaterial:()=>sl,MeshPhysicalMaterial:()=>ol,MeshStandardMaterial:()=>Gi,Object3D:()=>zr,OctahedronGeometry:()=>_l,PART_STRIDE_BYTES:()=>Km,PART_STRIDE_WORDS:()=>Wm,PerspectiveCamera:()=>cl,PlaneGeometry:()=>Ho,PointLight:()=>Ba,Points:()=>Il,PointsMaterial:()=>Qa,PolyhedronFallbackGeometry:()=>Qh,PolyhedronGeometry:()=>pi,QuadraticBezierCurve3:()=>Qo,Quaternion:()=>Dn,RawShaderMaterial:()=>vl,RectAreaLight:()=>Dl,RingGeometry:()=>Ya,SCENE_PBR_WGSL:()=>Ws,SCENE_PICK_WGSL:()=>_c,SCENE_SHADOW_WGSL:()=>Mc,SCENE_UNIFORM_BYTES:()=>qm,SHADOW_MAP_TEXTURE_UNIT:()=>sc,Scene:()=>Va,SceneQuotaValidator:()=>Qr,ShaderMaterial:()=>Ka,SphereGeometry:()=>qo,SpotLight:()=>$l,TEXTURE_PROMPT_SUFFIX:()=>lu,THREE:()=>Ni,TSL_EXTENSION_NAME:()=>Ui,TSL_TIME_PERIOD_SEC:()=>Ph,TSL_WGSL_UNIFORM_BYTES:()=>Um,TetrahedronGeometry:()=>wl,Texture:()=>kn,TextureLoader:()=>rl,ThreeLiveElement:()=>di,ThreeView:()=>ir,TorusGeometry:()=>Ko,TorusKnotGeometry:()=>Xo,TubeGeometry:()=>el,Uint16BufferAttribute:()=>jo,Uint32BufferAttribute:()=>Go,VERTEX_STRIDE_BYTES:()=>Ym,VERTEX_STRIDE_FLOATS:()=>Xm,Vector2:()=>ar,Vector3:()=>Ze,Vector4:()=>Bo,WebGLRenderer:()=>fl,WebGPUSceneAccelerator:()=>Cc,WireframeGeometry:()=>Cl,acquireSceneWebGPUDevice:()=>Ri,activateAR:()=>Uu,aiPlugin:()=>Ts,applyMeshoptFilter:()=>tc,authorScriptRunner:()=>Bn,browserImageCodec:()=>On,buildImageMessages:()=>ru,buildImageUserText:()=>tu,buildSandboxWorkerSource:()=>Ha,buildSelectIndex:()=>ns,cadPlugin:()=>lo,clearAuthorWarnings:()=>xl,compileFromImage:()=>au,compileTslToGlsl:()=>$o,compileTslToWgsl:()=>bc,computeOutlineClipOffset:()=>Tm,computeWorldSceneBounds:()=>uc,connectVoice:()=>xs,contactShadowPlugin:()=>Ps,createAIChatProvider:()=>_u,createAIImageProvider:()=>uu,createUSDZBlob:()=>Aa,createWebSpeechRecognizer:()=>wu,crossFadeTo:()=>Eu,decimateGeometry:()=>nh,decodeMeshoptBuffer:()=>rc,decodeMeshoptGLB:()=>Fs,defineModelViewer:()=>rf,describeEditResult:()=>Ms,describeSelection:()=>ss,describeVoiceSelection:()=>Ji,detectImageMime:()=>nu,doesMeshCastShadow:()=>on,doesMeshReceiveShadow:()=>js,editScene:()=>Tu,encodeMeshoptBuffer:()=>_m,environmentMapPlugin:()=>Hu,evaluateKawaseBloom:()=>Am,evaluateToneMapping:()=>fh,exportSceneToCanvas3D:()=>Ua,exportSceneToGLB:()=>Oa,exportSceneToUSDZ:()=>hl,extractMaterialVariants:()=>pc,extractPrimitiveVariantMappings:()=>Bm,extractScript:()=>As,fitDirectionalShadowMatrix:()=>cc,fitSpotShadowMatrix:()=>Os,fmtShaderFloat:()=>Xr,formatSpatialPriors:()=>us,geminiLiveAdapter:()=>xu,generateUSDZ:()=>Sa,getARCapabilities:()=>Ns,getAllowClientScripts:()=>yl,getAuthorWarnings:()=>bl,getBestARMode:()=>Qf,getEnvironmentSH:()=>em,getInteractivityVM:()=>$s,getLodController:()=>sh,getSandboxEngineSrc:()=>Ga,getSandboxIframeSrc:()=>gl,getSelection:()=>yr,getShadowMapStats:()=>Im,getWebGPUSceneAccelerator:()=>hn,glbToUSDZ:()=>_a,hideSelectionChips:()=>Hn,hotspotPlugin:()=>Ku,ikPlugin:()=>vo,imageRepairMessage:()=>iu,indexedDbTextureCache:()=>mu,installCadExtension:()=>ha,installLodExtension:()=>Tn,installProceduralExtension:()=>ga,installTslExtension:()=>Ta,interactivityPlugin:()=>Ju,isAllowedImageUrl:()=>$r,isAllowedSandboxEngineUrl:()=>Ti,isQuickLookSupported:()=>Bu,isSceneViewerSupported:()=>zu,isWebXRSupported:()=>Vu,keyframeAnimationPlugin:()=>Iu,lodPlugin:()=>Mo,matchSelection:()=>Ol,materialsPlugin:()=>ec,meshoptDecoder:()=>Bs,meshoptPlugin:()=>ic,morphPlugin:()=>$u,noopProxy:()=>qi,normalizeImageInput:()=>hs,normalizeRendererPreference:()=>Tc,normalizeShadowMapsMode:()=>lc,packUniformVec4:()=>Pa,parseAnimations:()=>Cu,parseHexRgb:()=>nc,parseLod:()=>da,parseSafeGltfPointer:()=>Yn,parseSelectReply:()=>Zl,parseTexturePack:()=>hu,parseVoiceCommand:()=>Wl,postprocessingPlugin:()=>ac,prepareAlbedo:()=>cu,proceduralPlugin:()=>_o,quatFromUnitVectors:()=>fa,realtimeAdapter:()=>bu,registerMaterialShader:()=>cm,remapClipDepthToZeroOne:()=>aa,resetSceneWebGPUDevice:()=>n0,resolveActiveShadowLights:()=>Gs,resolveSceneRenderBackend:()=>Js,resolveSelection:()=>Yl,resolveSelectionWithModel:()=>Jl,sampleChannel:()=>en,sceneSelectEntries:()=>Vn,sceneToCanvas3D:()=>Vi,sceneToGLB:()=>En,sceneToUSDZ:()=>In,selectByVoice:()=>qn,selectCamera:()=>os,selectLodLevelIndex:()=>pa,selectMaterialVariant:()=>zm,selectMessages:()=>Ql,selectNamesByVoice:()=>Mu,sendInteractivityEvent:()=>Zu,serializeTexturePack:()=>fu,serializeTslToUsda:()=>Do,setAllowClientScripts:()=>jh,setEnvironmentSH:()=>ju,setMaterialUniform:()=>xc,setMorphTargetWeight:()=>Xf,setSandboxEngineSrc:()=>Uh,setSandboxIframeSrc:()=>Oh,setSceneWebGPUDeviceForTests:()=>i0,setSelectOnTap:()=>Ss,setSelection:()=>Ar,shadowMapsPlugin:()=>mc,showSelectionChips:()=>gu,skinningPlugin:()=>ku,solveFABRIK:()=>mo,solveTwoBoneIK:()=>fo,speakableName:()=>ws,startVoiceEdit:()=>_s,textureRequests:()=>ps,threeAuthorPlugin:()=>Wi,threeMicroPlugin:()=>tf,toGLBData:()=>zi,toTrustedWorkerScriptURL:()=>pl,tslPlugin:()=>vc,tslSafeMod:()=>Lo,tslTypeArity:()=>nr,tslTypeFromArity:()=>Ro,undoEdit:()=>Pu,validateSandboxWorkerMessage:()=>qa,validateTslGraph:()=>Oi,variantsPlugin:()=>dc,warnUnsupported:()=>Zr,webgpuScenePlugin:()=>Ec,webxrPlugin:()=>gc,writeSceneUniforms:()=>qs});function H0(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 I={};return R.forEach((F,V)=>{I[String(V)]={node:F}}),m("flow/sequence",{flows:I})},C=(_,P,R)=>{let I=N(P);I!==null&&m(_,{...R?{configuration:R}:{},flows:{out:{node:I}}})};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 Hc='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).',qc="Security Error: client-side scripts require allow-client-scripts opt-in.",ca="__THREE_LIVE_REGISTRY__";function We(){let e=typeof globalThis<"u"?globalThis:{};if(!e[ca]){let t={plugins:[],decoders:new Map};try{Object.defineProperty(e,ca,{value:t,writable:!1,configurable:!1,enumerable:!1})}catch{e[ca]=t}}return e[ca]}var Lt=We().plugins;function Mn(e){let t=We();t.workerExtensionInstallers||(t.workerExtensionInstallers=[]),t.workerExtensionInstallers.includes(e)||t.workerExtensionInstallers.push(e)}function Rt(e){let t=We().plugins;t.some(r=>r.name===e.name)||t.push(e),e.onRegister?.()}function Wc(){return We().plugins}var Kc=8192,Xc=2048,Yc=128,Qc=4096;function ha(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,$e=Number(ce)||0;return this.segments.length===0&&this.segments.push({type:"move",pts:[pe,xe]}),this.currentPoint.set(Ee,$e),this.segments.push({type:"cubic",pts:[pe,xe,he,Ne,ge,Ae,Ee,$e]}),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,$e=Number(ce)||0,De=pe?1:0,Be=Number(xe)||0;this.segments.push({type:"arc",pts:[he,Ne,ge,Ae,Ee,$e,De,Be]});let Fe=Math.cos(Be),Ve=Math.sin(Be),qe=ge*Math.cos($e),je=Ae*Math.sin($e);return this.currentPoint.set(he+qe*Fe-je*Ve,Ne+qe*Ve+je*Fe),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 $e=Ee/z,De=1-$e;X(De*De*pe+2*De*$e*he+$e*$e*ge,De*De*xe+2*De*$e*Ne+$e*$e*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],$e=ce[7];X(pe,xe);for(let De=1;De<=z;De++){let Be=De/z,Fe=1-Be,Ve=Fe*Fe,qe=Be*Be;X(Ve*Fe*pe+3*Ve*Be*he+3*Fe*qe*ge+qe*Be*Ee,Ve*Fe*xe+3*Ve*Be*Ne+3*Fe*qe*Ae+qe*Be*$e)}}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,$e=ce[7],De=Math.PI*2,Be=Ae-ge,Fe=Math.abs(Be)<1e-9;for(;Be<0;)Be+=De;for(;Be>De;)Be-=De;Be<1e-9&&(Be=Fe?0:De),Ee&&!Fe&&(Be=Be===De?-De:Be-De);let Ve=Math.cos($e),qe=Math.sin($e),je=Math.max(2,z);for(let ut=0;ut<=je;ut++){let it=ut/je,nt=ge+it*Be,ct=he*Math.cos(nt),Je=Ne*Math.sin(nt);X(pe+ct*Ve-Je*qe,xe+ct*qe+Je*Ve)}}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,$e=xe*xe+he*he,De=xe*Ne+he*ge,Be=xe*Ae+he*Ee,Fe=Ne*Ne+ge*ge,Ve=Ne*Ae+ge*Ee,qe=$e*Fe-De*De;if(Math.abs(qe)<1e-12)return!1;let je=1/qe,ut=(Fe*Be-De*Ve)*je,it=($e*Ve-De*Be)*je;return ut>=-1e-7&&it>=-1e-7&&ut+it<=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 $e=he[Ee],De=O.length;O.push(new r($e.x,$e.y)),Ne.push(De),$e.x>ge&&(ge=$e.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(Fe=>O[Fe]),Ee=Fe=>Math.hypot(Ae[Fe].x-Ne,Ae[Fe].y-he.y),$e=Ae.map((Fe,Ve)=>Ve).sort((Fe,Ve)=>+(Ae[Fe].x<Ne)-+(Ae[Ve].x<Ne)||Ee(Fe)-Ee(Ve)),De=$e[0];for(let Fe of $e){let Ve=Ae[Fe],qe=Ae[(Fe+ge-1)%ge],je=Ae[(Fe+1)%ge],ut=ce(Ve,je,he)>=0,it=ce(qe,Ve,he)>=0;if((ce(qe,Ve,je)>=0?ut&&it:ut||it)&&!pe(he,Ve,Ae)&&!se.some(nt=>pe(he,Ve,nt.pts))){De=Fe;break}}let Be=[];for(let Fe=0;Fe<=De;Fe++)Be.push(X[Fe]);for(let Fe=0;Fe<=xe.indices.length;Fe++){let Ve=xe.indices[(xe.maxIdx+Fe)%xe.indices.length];Be.push(Ve)}for(let Fe=De;Fe<X.length;Fe++)Be.push(X[Fe]);X=Be}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,$e=Math.min(Ne.x,ge.x,Ae.x)-1e-7,De=Math.max(Ne.x,ge.x,Ae.x)+1e-7,Be=Math.min(Ne.y,ge.y,Ae.y)-1e-7,Fe=Math.max(Ne.y,ge.y,Ae.y)+1e-7;for(let Ve=0;Ve<ce;Ve++){let qe=O[Ve];if(qe===pe||qe===xe||qe===he)continue;let je=D[qe];if(je.x>=$e&&je.x<=De&&je.y>=Be&&je.y<=Fe&&S(je.x,je.y,Ne.x,Ne.y,ge.x,ge.y,Ae.x,Ae.y)&&(je.x-Ne.x)*(je.x-Ne.x)+(je.y-Ne.y)*(je.y-Ne.y)>=1e-12&&(je.x-ge.x)*(je.x-ge.x)+(je.y-ge.y)*(je.y-ge.y)>=1e-12&&(je.x-Ae.x)*(je.x-Ae.x)+(je.y-Ae.y)*(je.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,[$e,De,Be,Fe]=_(ge);for(let Ve of ge)X.push(Ve.x,Ve.y,0),se.push(0,0,1),ce.push((Ve.x-$e)/Be,(Ve.y-De)/Fe);for(let[Ve,qe,je]of Ae)pe.push(Ee+Ve,Ee+qe,Ee+je)}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 I(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,$e=-pe,De=ge,Be=-Ne,Fe=Ee+De,Ve=$e+Be,qe=Math.hypot(Fe,Ve);if(qe>1e-6){Fe/=qe,Ve/=qe;let je=Math.max(.35,Fe*Ee+Ve*$e);z.push(new r(Fe/je,Ve/je))}else z.push(new r(Ee,$e))}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=[],$e=[],De=[];for(let Be of O){if(!(Be instanceof A))continue;let Fe=C(Be,X);if(Fe.shape.length<3)continue;let Ve=Fe.shape.slice();w(Ve)<0&&Ve.reverse();let qe=[];for(let Pe of Fe.holes){if(Pe.length<3)continue;let at=Pe.slice();w(at)>0&&at.reverse(),qe.push(at)}let{mergedIndices:je,allVertices:ut}=E(Ve,qe),it=N(je,ut),nt=[Ve,...qe],ct=[];for(let Pe of nt){let at=I(Pe);for(let vt of at)ct.push(vt)}let[Je,Dt,Ft,lr]=_(ut);for(let[Pe,at]of[[-xe,-1],[se+xe,1]]){let vt=Ae.length/3;for(let Mt=0;Mt<ut.length;Mt++){let Pt=ut[Mt],Ct=ct[Mt]??new r(0,0),Xt=Pt.x+Ct.x*Ne,Ot=Pt.y+Ct.y*Ne;Ae.push(Xt,Ot,Pe),Ee.push(0,0,at),$e.push((Xt-Je)/Ft,(Ot-Dt)/lr)}for(let[Mt,Pt,Ct]of it)De.push(vt+Mt,vt+(at<0?Ct:Pt),vt+(at<0?Pt:Ct))}let wt=[];if(pe&&ge>0)for(let Pe=0;Pe<ge;Pe++){let at=Pe/ge*Math.PI/2;wt.push({z:-xe*Math.cos(at),expand:Ne+he*Math.sin(at)})}for(let Pe=0;Pe<=ce;Pe++){let at=Pe/ce;wt.push({z:at*se,expand:Ne+he})}if(pe&&ge>0)for(let Pe=1;Pe<=ge;Pe++){let at=Pe/ge*Math.PI/2;wt.push({z:se+xe*Math.sin(at),expand:Ne+he*Math.cos(at)})}let Gt=0;for(let Pe of nt){let at=Pe.length;for(let vt=0;vt<wt.length-1;vt++){let Mt=wt[vt],Pt=wt[vt+1];for(let Ct=0;Ct<at;Ct++){let Xt=(Ct+1)%at,Ot=Pe[Ct],Yt=Pe[Xt],Qt=ct[Gt+Ct],Zt=ct[Gt+Xt],ur=Ot.x+Qt.x*Mt.expand,br=Ot.y+Qt.y*Mt.expand,oi=Yt.x+Zt.x*Mt.expand,Jt=Yt.y+Zt.y*Mt.expand,er=Yt.x+Zt.x*Pt.expand,vi=Yt.y+Zt.y*Pt.expand,Hr=Ot.x+Qt.x*Pt.expand,xr=Ot.y+Qt.y*Pt.expand,cr=oi-ur,Ht=Jt-br,ro=Hr-ur,fn=xr-br,wi=Pt.z-Mt.z,Nr=Ht*wi,Cr=-cr*wi,Er=cr*fn-Ht*ro,li=Math.hypot(Nr,Cr,Er)||1;Nr/=li,Cr/=li,Er/=li;let hr=Ae.length/3;Ae.push(ur,br,Mt.z,oi,Jt,Mt.z,er,vi,Pt.z,Hr,xr,Pt.z),Ee.push(Nr,Cr,Er,Nr,Cr,Er,Nr,Cr,Er,Nr,Cr,Er);let mn=Ct/at,oa=(Ct+1)/at,vr=vt/(wt.length-1),fr=(vt+1)/(wt.length-1);$e.push(mn,vr,oa,vr,oa,fr,mn,fr),De.push(hr,hr+1,hr+2,hr,hr+2,hr+3)}}Gt+=at}}R(this,Ae,Ee,$e,De)}}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 $e=Ne*D.x+ge*D.y+Ae*D.z;return{vertices:W,nx:Ne,ny:ge,nz:Ae,w:$e}}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,$e=Ee<-ee?q:Ee>ee?G:k;he|=$e,Ne.push($e)}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 Ve=0;Ve<Ee;Ve++){let qe=(Ve+1)%Ee,je=Ne[Ve],ut=Ne[qe],it=X.vertices[Ve],nt=X.vertices[qe];if(je!==q&&ge.push(it),je!==G&&Ae.push(je!==q?V(it):it),(je|ut)===H){let ct=nt.x-it.x,Je=nt.y-it.y,Dt=nt.z-it.z,Ft=W*ct+D*Je+z*Dt,lr=Math.abs(Ft)>1e-12?(O-(W*it.x+D*it.y+z*it.z))/Ft:.5,wt=J(it,nt,Math.max(0,Math.min(1,lr)));ge.push(wt),Ae.push(V(wt))}}let{nx:$e,ny:De,nz:Be,w:Fe}=X;ge.length>=3&&pe.push({vertices:ge,nx:$e,ny:De,nz:Be,w:Fe}),Ae.length>=3&&xe.push({vertices:Ae,nx:$e,ny:De,nz:Be,w:Fe});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),$e=z.getY(Ae),De=z.getZ(Ae),Be=O?O.getX(Ae):NaN,Fe=O?O.getY(Ae):NaN,Ve=O?O.getZ(Ae):NaN;if(pe&&he){let ut=pe[0]*Ee+pe[4]*$e+pe[8]*De+pe[12],it=pe[1]*Ee+pe[5]*$e+pe[9]*De+pe[13],nt=pe[2]*Ee+pe[6]*$e+pe[10]*De+pe[14];Ee=ut,$e=it,De=nt;let ct=he[0]*Be+he[3]*Fe+he[6]*Ve,Je=he[1]*Be+he[4]*Fe+he[7]*Ve,Dt=he[2]*Be+he[5]*Fe+he[8]*Ve,Ft=Math.hypot(ct,Je,Dt)||1;Be=ct/Ft,Fe=Je/Ft,Ve=Dt/Ft}let qe=X?X.getX(Ae):0,je=X?X.getY(Ae):0;return{x:Ee,y:$e,z:De,nx:Be,ny:Fe,nz:Ve,u:qe,v:je}},ge=[];for(let Ae=0;Ae<ce;Ae++){let Ee=se?se[Ae*3]:Ae*3,$e=se?se[Ae*3+1]:Ae*3+1,De=se?se[Ae*3+2]:Ae*3+2,Be=re(xe?[Ne(Ee),Ne(De),Ne($e)]:[Ne(Ee),Ne($e),Ne(De)]);Be&&ge.push(Be)}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 $e=D[Ee].vertices;for(let De=0;De<$e.length;De++){let Be=$e[De];Be.x<O&&(O=Be.x),Be.y<X&&(X=Be.y),Be.z<se&&(se=Be.z),Be.x>ce&&(ce=Be.x),Be.y>pe&&(pe=Be.y),Be.z>xe&&(xe=Be.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 $e=W[Ee],De=$e.vertices,Be=1/0,Fe=1/0,Ve=1/0,qe=-1/0,je=-1/0,ut=-1/0;for(let it=0;it<De.length;it++){let nt=De[it];nt.x<Be&&(Be=nt.x),nt.y<Fe&&(Fe=nt.y),nt.z<Ve&&(Ve=nt.z),nt.x>qe&&(qe=nt.x),nt.y>je&&(je=nt.y),nt.z>ut&&(ut=nt.z)}qe<O||Be>ce||je<X||Fe>pe||ut<se||Ve>xe?Ne.push($e):he.push($e)}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)),$e=new a().makeTranslation(-W.position.x,-W.position.y,-W.position.z);pe=ge.multiply(Ee).multiply($e).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 ke={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=[],$e=[],De=[],Be=(qe,je,ut,it,nt,ct,Je)=>{let Dt=ut-qe,Ft=it-je,lr=Math.hypot(Dt,Ft),wt=1,Gt=0;lr>1e-6&&(wt=Dt/lr,Gt=Ft/lr);let Pe=-Gt*nt,at=wt*nt,vt=wt*nt*.6,Mt=Gt*nt*.6,Pt=qe-vt+Pe,Ct=je-Mt+at,Xt=qe-vt-Pe,Ot=je-Mt-at,Yt=ut+vt-Pe,Qt=it+Mt-at,Zt=ut+vt+Pe,ur=it+Mt+at,br=(oi,Jt,er,vi,Hr,xr,cr)=>{let Ht=Ae.length/3;Ae.push(oi[0],oi[1],oi[2],Jt[0],Jt[1],Jt[2],er[0],er[1],er[2],vi[0],vi[1],vi[2]),Ee.push(Hr,xr,cr,Hr,xr,cr,Hr,xr,cr,Hr,xr,cr),$e.push(0,0,1,0,1,1,0,1),De.push(Ht,Ht+1,Ht+2,Ht,Ht+2,Ht+3)};br([Pt,Ct,Je],[Xt,Ot,Je],[Yt,Qt,Je],[Zt,ur,Je],0,0,1),br([Xt,Ot,ct],[Pt,Ct,ct],[Zt,ur,ct],[Yt,Qt,ct],0,0,-1),br([Pt,Ct,ct],[Xt,Ot,ct],[Xt,Ot,Je],[Pt,Ct,Je],-wt,-Gt,0),br([Yt,Qt,ct],[Zt,ur,ct],[Zt,ur,Je],[Yt,Qt,Je],wt,Gt,0),br([Xt,Ot,ct],[Yt,Qt,ct],[Yt,Qt,Je],[Xt,Ot,Je],Gt,-wt,0),br([Zt,ur,ct],[Pt,Ct,ct],[Pt,Ct,Je],[Zt,ur,Je],-Gt,wt,0)},Fe=0,Ve=0;for(let qe=0;qe<O.length;qe++){let je=O[qe];if(je===`
|
|
17
|
+
`){Fe=0,Ve-=X*1.35;continue}if(je===" "||je===" "){Fe+=ge*(je===" "?.75:3);continue}if(je==="\r")continue;let ut=je.toUpperCase(),it=je!==ut&&je>="a"&&je<="z",nt=_e[ut]??_e["?"],ct=it?X*.76:X,Je=it?Ne*.88:Ne;for(let Dt of nt)for(let Ft=0;Ft<Dt.length-1;Ft++){let lr=Dt[Ft],wt=Dt[Ft+1];Be(Fe+lr[0]*Je,Ve+lr[1]*ct,Fe+wt[0]*Je,Ve+wt[1]*ct,he,-xe*.5,xe*.5)}Fe+=it?ge*.88:ge}R(this,Ae,Ee,$e,De),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"?ke.union(D,Ne):he==="intersect"?ke.intersect(D,Ne):ke.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:ke,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 lo={name:"cad",onRegister(){Mn(ha);let e=We(),t=e.threeNamespace??(typeof globalThis<"u"?globalThis.THREE:void 0);t&&ha(t,e)}};function lt(){let e=new Float32Array(16);return e[0]=1,e[5]=1,e[10]=1,e[15]=1,e}function uo(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 q0(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 _n(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 ft(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 Sn(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 rr(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 co(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,I=m*y-p*x,F=h*y-p*v,V=A*F-b*I+w*R+S*P-E*_+N*C;return V?(V=1/V,e[0]=(o*F-l*I+c*R)*V,e[1]=(n*I-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*I-o*P+c*C)*V,e[9]=(i*P-r*I-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 Zc(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 W0(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,I=e-s,F=t-o,V=r-l,Y=R*(I*N+F*C+V*_);if(Y<-v||Y>1+v)return!1;let J=F*b-V*A,re=V*y-I*b,Q=I*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 An(e,t){let r=Array.isArray(e?.nodes)?e.nodes.length:0,i=[];for(let f=0;f<r;f++)i.push(lt());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=lt();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];Sn(g,y,v,A)}let x=i[f];if(m?ft(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 ho(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,I=Math.abs(v-w)+1e-5,F=Math.max(I,v+w-1e-5),V=Math.max(I,Math.min(F,P>1e-6?P:I)),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],ke=Math.hypot(de,me,Se),_e=ke>1e-6?[de/ke,me/ke,Se/ke]: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],I=p[P+1][1]-p[P][1],F=p[P+1][2]-p[P][2],V=Math.hypot(R,I,F);g.push(V),v+=V,x.push(V>1e-6?[R/V,I/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 I=g[R];p[R+1]=[p[R][0]+P[0]*I,p[R][1]+P[1]*I,p[R][2]+P[2]*I]}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 I=(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]=I(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]=I(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],I=p[P+1][1]-p[P][1],F=p[P+1][2]-p[P][2],V=Math.hypot(R,I,F),Y=V>1e-6?[R/V,I/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 ki=ho(),Jc=ki.clampNum,K0=ki.parseIKTrait,fa=ki.quatFromUnitVectors,fo=ki.solveTwoBoneIK,mo=ki.solveFABRIK,eh=ki.IKSolver;function po(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 X0(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 Y0(e,t,r,i,n){let a=Jc(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 Q0(e,t){let r=e?.modelRootMatrix;if(!r||r.length!==16)return t;let i=new Float32Array(16);return co(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 go(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 yo(e,t,r){if(Array.isArray(e))return[e[0],e[1],e[2]];let i=t.get(e);if(i)return po(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 Q0(r,[a[0],a[1],a[2]])}return null}function bo(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 Z0(e){return[-e[0],-e[1],-e[2],e[3]]}function xo(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 J0(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 xo([r*l,i*l,n*l,Math.cos(s*t)])}function ep(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 xo(g)}function tp(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 ma(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 th(e){e?.normalMatrix&&e?.transform&&rr(e.normalMatrix,e.transform)}var rh=new WeakMap;function rp(e){let t=rh.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)}),rh.set(e,t)),t}function ip(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=rp(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 I of Array.isArray(R?.children)?R.children:[])typeof I=="number"&&p.push(I)}let g=l[c],x=g>=0&&e.worldMatrices?.[g]?.length===16?Float32Array.from(e.worldMatrices[g]):lt(),v=new Map,y=()=>{let _=(P,R)=>{let I=m.get(P);if(!I)return;let F=lt();Sn(F,I.r,I.t,I.s);let V=lt();ft(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 yo(_,r,e)},S=w(t.target);if(!S)return!0;let E=t.pole?w(t.pole)??void 0:void 0,N=ih(b,t,S,E),C=Jc(t.weight,0,1,1);for(let _=0;_<o.length-1;_++){let P=ma(A(o[_]),A(o[_+1])),R=ma(N[_],N[_+1]);if(!P||!R)continue;let I=J0(fa(P,R),C),F=o[_],V=l[F],Y=V===g||V<0?x:v.get(V)??x,J=ep(Y),re=m.get(F);re.r=xo(bo(Z0(J),bo(I,bo(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),th(_))}return!0}function ih(e,t,r,i){if(t.solver==="two-bone"&&e.length===3){let n=fo(e[0],e[1],e[2],r,i);return[e[0],n.midPos,n.effectorPos]}return mo(e,r,t.iterations,t.tolerance).positions}function np(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=ma([0,0,0],i[a]),c=ma(r[a],r[a+1]);!s||s.length<16||!o||o.length<16||!l||!c||(tp(s,o,fa(l,c)),th(t[a]))}}var vo={name:"ik",onRegister(){let e=We();Mn(ho),ho(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=K0(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(ip(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||go(i,a.root),o||go(i,a.effector),a.mid&&!l&&go(i,a.mid),!s||!o)continue;let c=yo(a.target,r,e);if(!c)continue;let f=a.pole?yo(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(po),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=[po(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=ih(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=Y0(y,S,E,x[b-1],a.weight);X0(m[b],N),y=N,A.push(N)}np(i,m,A)}}};function Tn(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),I=Math.max(1e-5,_-E),F=Math.max(1e-5,P-N),V=Math.max(R,I,F),Y=te=>{let Z=Math.max(1,Math.round(R/V*te)),ae=Math.max(1,Math.round(I/V*te)),ie=Math.max(1,Math.round(F/V*te)),de=new Map,me=new Int32Array(x),Se=[],ke=[],_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)/I*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&&ke.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&&(ke[ge*3]+=v[O*3],ke[ge*3+1]+=v[O*3+1],ke[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=ke[O*3],ce=ke[O*3+1],pe=ke[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 Pn=Tn(),nh=Pn.decimateGeometry,pa=Pn.selectLodLevelIndex,da=Pn.parseLod,Eg=Pn.materializeLodGeometry,ah=Pn.LOD,Nn=new WeakMap;function sh(e){return e&&typeof e=="object"?Nn.get(e):void 0}var wo=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=da(a);if(!o&&s.length>0&&(o=da({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=pa(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=pa(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})}}},Mo={name:"lod",onRegister(){Mn(Tn);let e=We(),t=e.threeNamespace??(typeof globalThis<"u"?globalThis.THREE:void 0);Tn(t,e)},onLoadModel(e,t){!e||typeof e!="object"||Nn.set(e,new wo(e,t))},onUpdate(e){let t=Nn.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=Nn.get(e);n&&n.update(i)},onDestroy(e,t){t&&typeof t=="object"&&Nn.delete(t)}};function ga(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,$=Number(T?.y)||0,B=Number(T?.z)||0,U=T?.w===void 0?1:Number(T.w)||0,j=2*($*M-B*d),K=2*(B*u-L*M),ue=2*(L*d-$*u);return this.set(u+U*j+($*ue-B*K),d+U*K+(B*j-L*ue),M+U*ue+(L*K-$*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,$=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-$),this.max.set(B+M,U+L,j+$),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,$=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,$!==0?(u.z-this.min.z)/$: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,$=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<=-$&&U>=-$}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,$=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?$: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,$=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,$),B.multiplyMatrices(le.matrixWorld,$),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,$=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($.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 $=0;$<T.count;$++){let B=T.getX($),U=T.getY($),j=T.getZ($);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 $=p.charCodeAt(L);if($===61)break;let B=$<128?g[$]:-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 $=L[1],B=L[2].replace(/\//g," ").split(/[\s,]+/).filter(Boolean);if(B.length<3)return u;if($.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,$=c)=>{if(!T||u<=0||d<=0||T.length<u*d*4)return{uri:"",avgColor:[1,1,1,1]};if(typeof b=="function"){let Oe=b(T,u,d,M,L,$);if(Array.isArray(Oe)&&typeof Oe[0]=="string")return{uri:Oe[0],avgColor:[Oe[1],Oe[2],Oe[3],Oe[4]]}}let B=u>$||d>$?$/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,ze=U===u&&j===d;for(let Oe=0;Oe<j;Oe++){ye[ve++]=0,Te=(Te+we)%65521;let Xe=M?j-1-Oe:Oe,rt=ze?Xe:Math.floor(Xe*d/j),yt=ze?Xe+1:Math.max(rt+1,Math.floor((Xe+1)*d/j));for(let pt=0;pt<U;pt++){let ot=0,bt=0,St=0,dt=0;if(ze){let gt=(rt*u+pt)*4;ot=T[gt]|0,bt=T[gt+1]|0,St=T[gt+2]|0,dt=T[gt+3]|0}else{let gt=Math.floor(pt*u/U),Bt=Math.max(gt+1,Math.floor((pt+1)*u/U)),Nt=0;for(let Vt=rt;Vt<yt&&Vt<d;Vt++)for(let Et=gt;Et<Bt&&Et<u;Et++){let qt=(Vt*u+Et)*4;ot+=T[qt]|0,bt+=T[qt+1]|0,St+=T[qt+2]|0,dt+=T[qt+3]|0,Nt++}Nt>1&&(ot=ot/Nt+.5|0,bt=bt/Nt+.5|0,St=St/Nt+.5|0,dt=dt/Nt+.5|0)}ye[ve++]=ot,we+=ot,Te+=we,ye[ve++]=bt,we+=bt,Te+=we,ye[ve++]=St,we+=St,Te+=we,ye[ve++]=dt,we+=dt,Te+=we,Me+=L?ot/255:A[ot],be+=L?bt/255:A[bt],Ce+=L?St/255:A[St],Ie+=dt/255}we%=65521,Te%=65521}let Ue=43,He=ue,Ke=0;for(;He>0||Ke===0;){let Oe=Math.min(65535,He),Xe=He-Oe===0?1:0;if(oe[Ue++]=Xe,fe.setUint16(Ue,Oe,!0),fe.setUint16(Ue+2,~Oe&65535,!0),Ue+=4,Oe>0&&(oe.set(ye.subarray(Ke,Ke+Oe),Ue),Ue+=Oe,Ke+=Oe,He-=Oe),Xe)break}fe.setUint32(Ue,(Te<<16|we)>>>0),Ue+=4,fe.setUint32(Ue,y(oe.subarray(37,Ue))),Ue+=4,fe.setUint32(Ue,0),fe.setUint32(Ue+4,1229278788),fe.setUint32(Ue+8,2923585666);let et=Math.max(1,U*j),Qe=[Me/et,be/et,Ce/et,Ie/et],tt=["data:image/png;base64,"];for(let Oe=0;Oe<oe.length;Oe+=3){let Xe=oe[Oe]<<16|(oe[Oe+1]??0)<<8|(oe[Oe+2]??0);tt.push(l[Xe>>18&63]+l[Xe>>12&63]+(Oe+1<oe.length?l[Xe>>6&63]:"=")+(Oe+2<oe.length?l[Xe&63]:"="))}return{uri:tt.join(""),avgColor:Qe}},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 $=L/255;if($<=d[0].o){let B=d[0].c;u[L]=P(B[0],B[1],B[2],B[3])}else if($>=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&&$>d[M+1].o;)M++;let B=d[M],U=d[M+1],j=U.o-B.o,K=j>1e-9?($-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},I=(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 $=L<=0?0:L>=1?255:L*255+.5|0;return M[$]};class F{constructor(u,d,M,L,$,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($)||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,$)=>L.o-$.o||L.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 $=(L||"repeat").toLowerCase();this.rx=$==="repeat"||$==="repeat-x",this.ry=$==="repeat"||$==="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 $=(L*T.w+M)*4;return P(T.d[$],T.d[$+1],T.d[$+2],T.d[$+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),$=(T-32)*5;for(let U=0;U<5;U++){let j=x[$+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]),$=M[2].toLowerCase();return $==="pt"?L*=4/3:($==="em"||$==="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 $=1/L;return[M[3]*u*$,-M[2]*d*$,(-M[3]*M[4]+M[2]*M[5])*$,-M[1]*u*$,M[0]*d*$,(M[1]*M[4]-M[0]*M[5])*$]},H=(T,u,d)=>{let[M,L,$,B,U,j]=q(T);return[M*u+L*d+$,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 $=u?u._g:0;if($===1||$===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=$===1?I(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 $=T.canvas._bw,B=T.canvas._bh;if(d<0||d>=$||M<0||M>=B)return;let U=M*$+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,$=T.canvas._bh,B=[],U=$,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 ze=Math.min(be,Ie),Ue=Math.max(be,Ie);B.push([ze,Ue,Ie>be?Me:Ce,(Ie>be?Ce-Me:Me-Ce)/(Ue-ze),Ie>be?1:-1]),ze<U&&(U=ze),Ue>j&&(j=Ue)}}if(B.length===0)return;let K=Math.max(0,Math.floor(U)),ue=Math.min($-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,$)=>{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,$?T.strokeStyle:T.fillStyle),Ce=te(T),[Ie,ze,Ue,He,Ke,et]=q(T),Qe=T.canvas._bw,tt=T.canvas._bh,Oe=new Uint8Array(Qe*tt),Xe=le*ye;if(Xe<=1e-6||ue<=1e-6)return;let rt=1/Xe,yt=1/ue;for(let pt=0;pt<U.length;pt++){let ot=J(U[pt].codePointAt(0)??32);if(ot===32)continue;let bt=we+pt*oe*ye,St=Q(ot,K),dt=G(T,bt,Te),gt=G(T,bt+Xe,Te),Bt=G(T,bt+Xe,Te+ue),Nt=G(T,bt,Te+ue),Vt=Math.max(0,Math.floor(Math.min(dt[0],gt[0],Bt[0],Nt[0]))),Et=Math.min(Qe-1,Math.ceil(Math.max(dt[0],gt[0],Bt[0],Nt[0]))),qt=Math.max(0,Math.floor(Math.min(dt[1],gt[1],Bt[1],Nt[1]))),tr=Math.min(tt-1,Math.ceil(Math.max(dt[1],gt[1],Bt[1],Nt[1])));for(let Mr=qt;Mr<=tr;Mr++){let mr=Mr+.5;for(let qr=Vt;qr<=Et;qr++){let Di=Mr*Qe+qr;if(Oe[Di])continue;let Mi=qr+.5,dn=Ie*Mi+ze*mr+Ue,gn=He*Mi+Ke*mr+et,Wr=(dn-bt)*rt,Kr=(gn-Te)*yt;if(Wr<0||Wr>=1||Kr<0||Kr>=1)continue;let pr=Math.min(9,Wr*10|0),dr=Math.min(13,Kr*14|0);St[dr*10+pr]===1&&($&&pr>0&&pr<9&&dr>0&&dr<13&&St[dr*10+pr-1]&&St[dr*10+pr+1]&&St[(dr-1)*10+pr]&&St[(dr+1)*10+pr]||(Oe[Di]=1,ie(T,Ce,qr,Mr,be(Mi,mr))))}}}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,$,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($??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,$,B){if(!Number.isFinite(u+d+M+L+$+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]*$+U[2]*B+U[4],U[1]*$+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,$,B){return new F(!0,u,d,M,L,$,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,$){if(!Number.isFinite(u+d+M+L))return;M<0&&(u+=M,M=-M),L<0&&(d+=L,L=-L);let B=Array.isArray($)?$:$!==void 0?[$]:[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 $=this._cur.pts,[B,U]=$[$.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,$,B){if(!Number.isFinite(u+d+M+L+$+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,$,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,$=0,B=0,U=Math.PI*2,j=!1){if(!Number.isFinite(u+d+M+L+$+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($),ye=Math.sin($),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,ze=d+be*ye+Ce*fe;Te===0&&(!this._cur||this._cur.pts.length===0)?this.moveTo(Ie,ze):this.lineTo(Ie,ze)}}arc(u,d,M,L,$,B=!1){this.ellipse(u,d,M,M,0,L,$,B)}arcTo(u,d,M,L,$){if(!Number.isFinite(u+d+M+L+$))return;let B=Math.max(0,$);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,ze=Me*Ie-be*Ce;if(Math.abs(ze)<1e-6){this.lineTo(u,d);return}let Ue=Math.acos(Math.max(-1,Math.min(1,Me*Ce+be*Ie)))*.5,He=B/Math.tan(Ue),Ke=Me+Ce,et=be+Ie,Qe=Math.hypot(Ke,et)||1,tt=B/Math.sin(Ue),Oe=u+Ke/Qe*tt,Xe=d+et/Qe*tt;this.arc(Oe,Xe,B,Math.atan2(d+be*He-Xe,u+Me*He-Oe),Math.atan2(d+Ie*He-Xe,u+Ce*He-Oe),ze>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,$)=>ie(this,M,L,$,d(L+.5,$+.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",($,B)=>{L[B*d+$]=1}),this._clip)for(let $=0;$<L.length;$++)L[$]&=this._clip[$];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,$=Math.max(.5,L*d*.5),B=$*$,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,ze,Ue)=>{let He=Me,Ke=be,et=Ce,Qe=Ie,tt=et-He,Oe=Qe-Ke,Xe=Math.hypot(tt,Oe);if(U==="square"&&Xe>1e-6){let dt=tt/Xe*$,gt=Oe/Xe*$;ze&&(He-=dt,Ke-=gt),Ue&&(et+=dt,Qe+=gt),tt=et-He,Oe=Qe-Ke}let rt=tt*tt+Oe*Oe,yt=$+.5,pt=Math.max(0,Math.floor(Math.min(He,et)-yt)),ot=Math.min(j-1,Math.ceil(Math.max(He,et)+yt)),bt=Math.max(0,Math.floor(Math.min(Ke,Qe)-yt)),St=Math.min(K-1,Math.ceil(Math.max(Ke,Qe)+yt));for(let dt=bt;dt<=St;dt++){let gt=dt+.5;for(let Bt=pt;Bt<=ot;Bt++){let Nt=dt*j+Bt;if(oe[Nt])continue;let Vt=Bt+.5,Et=rt>1e-9?((Vt-He)*tt+(gt-Ke)*Oe)/rt:0;if(U==="butt"&&(Et<0&&ze||Et>1&&Ue))continue;Et=Math.max(0,Math.min(1,Et));let qt=He+Et*tt,tr=Ke+Et*Oe;(Vt-qt)*(Vt-qt)+(gt-tr)*(gt-tr)<=B&&(oe[Nt]=1,ie(this,le,Bt,dt,ue(Vt,gt)))}}},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,ze=fe>1e-6?(Te*d%fe+fe)%fe:0;for(let Ue=0;Ue<Ie;Ue++){let[He,Ke]=be[Ue],[et,Qe]=be[(Ue+1)%Ce];if(fe<=1e-6)ve(He,Ke,et,Qe,!Me.closed&&Ue===0,!Me.closed&&Ue===Ie-1);else{let tt=Math.hypot(et-He,Qe-Ke);if(tt<=1e-6)continue;let Oe=0;for(;Oe<tt;){let Xe=ze,rt=0;for(;rt<ye.length&&Xe>=ye[rt];)Xe-=ye[rt],rt++;let yt=Math.min(tt-Oe,rt<ye.length?Math.max(.25,ye[rt]-Xe):tt-Oe);if(rt%2===0){let pt=Oe/tt,ot=(Oe+yt)/tt;ve(He+(et-He)*pt,Ke+(Qe-Ke)*pt,He+(et-He)*ot,Ke+(Qe-Ke)*ot,!0,!0)}Oe+=yt,ze=(ze+yt)%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 $=this._m;if($[0]===1&&$[1]===0&&$[2]===0&&$[3]===1&&$[4]===0&&$[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 $=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=$(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],ze=this.canvas._data,Ue=new Uint32Array(ze.buffer,ze.byteOffset,j*K);if(ye===0&&ve===j-1)Ue.fill(Ie,we*j,(Te+1)*j);else for(let He=we;He<=Te;He++)Ue.fill(Ie,He*j+ye,He*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,$(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,$(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 $=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=$,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))),$=Math.max(1,Math.min(f,Math.floor(Math.abs(Number(M?u.height:d))||1)));return{data:new Uint8ClampedArray(L*$*4),width:L,height:$}}getImageData(u,d,M,L){let $=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&&($+=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=$+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,$=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($)||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,ze=1/this.canvas._sx,Ue=1/this.canvas._sy,He=this.canvas._data,Ke=u.data,et=Math.max(0,Math.floor((Me+ye)*this.canvas._sx)),Qe=Math.min(Ce-1,Math.ceil((Me+we)*this.canvas._sx)-1),tt=Math.max(0,Math.floor((be+ve)*this.canvas._sy)),Oe=Math.min(Ie-1,Math.ceil((be+Te)*this.canvas._sy)-1);for(let Xe=tt;Xe<=Oe;Xe++){let rt=Math.floor((Xe+.5)*Ue)-be;if(!(rt<ve||rt>=Te))for(let yt=et;yt<=Qe;yt++){let pt=Math.floor((yt+.5)*ze)-Me;if(pt<ye||pt>=we)continue;let ot=(rt*j+pt)*4,bt=(Xe*Ce+yt)*4;He[bt]=Ke[ot]|0,He[bt+1]=Ke[ot+1]|0,He[bt+2]=Ke[ot+2]|0,He[bt+3]=Ke[ot+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,$=Number(u?.height)>0?Number(u.height):M.height,B=0,U=0,j=L,K=$,ue=0,le=0,oe=L,fe=$;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,ze,Ue]=q(this),He=1/oe,Ke=1/fe,et=M.width/L,Qe=M.height/$;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,Oe)=>{let Xe=tt+.5,rt=Oe+.5,yt=Me*Xe+be*rt+Ce,pt=Ie*Xe+ze*rt+Ue,ot=(yt-ue)*He,bt=(pt-le)*Ke;if(ot<0||ot>=1||bt<0||bt>=1)return;let St=Math.floor((B+ot*j)*et),dt=Math.floor((U+bt*K)*Qe);if(St<0||St>=M.width||dt<0||dt>=M.height)return;let gt=(dt*M.width+St)*4;ie(this,Te,tt,Oe,P(M.data[gt],M.data[gt+1],M.data[gt+2],M.data[gt+3]*we+128>>8))}),this.canvas._ver++}}let ke=(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={},ke(this,u,d)}get width(){return this._w}set width(u){ke(this,u,this._h)}get height(){return this._h}set height(u){ke(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 $=d.getContext("2d")?.getImageData?.(0,0,M,L);if($?.data)return{data:$.data instanceof Uint8ClampedArray?$.data:new Uint8ClampedArray($.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,$=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($)||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,$=L<8?u:d,B=L<4?d:L===12||L===14?u:M;return((L&1)===0?$:-$)+((L&2)===0?B:-B)};class pe{noise(u,d,M=0){let L=Number(u),$=Number(d),B=Number(M);if(!Number.isFinite(L)||!Number.isFinite($)||!Number.isFinite(B))return 0;let U=Math.floor(L),j=Math.floor($),K=Math.floor(B),ue=U&255,le=j&255,oe=K&255;L-=U,$-=j,B-=K;let fe=L-1,ye=$-1,ve=B-1,we=X(L),Te=X($),Me=X(B),be=O[ue]+le,Ce=O[be]+oe,Ie=O[be+1]+oe,ze=O[ue+1]+le,Ue=O[ze]+oe,He=O[ze+1]+oe;return se(Me,se(Te,se(we,ce(O[Ce],L,$,B),ce(O[Ue],fe,$,B)),se(we,ce(O[Ie],L,ye,B),ce(O[He],fe,ye,B))),se(Te,se(we,ce(O[Ce+1],L,$,ve),ce(O[Ue+1],fe,$,ve)),se(we,ce(O[Ie+1],L,ye,ve),ce(O[He+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,$e=(Math.sqrt(5)-1)/4,De=(5-Math.sqrt(5))/20,Be=(T,u,d)=>xe[T]*u+xe[T+1]*d,Fe=(T,u,d,M)=>xe[T]*u+xe[T+1]*d+xe[T+2]*M,Ve=(T,u,d,M,L)=>he[T]*u+he[T+1]*d+he[T+2]*M+he[T+3]*L;function qe(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 je{constructor(u){let d=qe(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),$=new Uint8Array(512);for(let B=0;B<512;B++){let U=M[B&255];L[B]=U,$[B]=U%12}this.p=M,this.perm=L,this.permMod12=$}noise(u,d){let M=Number(u),L=Number(d);if(!Number.isFinite(M)||!Number.isFinite(L))return 0;let $=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,ze=K&255,Ue=B[Ie+$[ze]]*3,He=B[Ie+ve+$[ze+we]]*3,Ke=B[Ie+1+$[ze+1]]*3,et=0,Qe=.5-fe*fe-ye*ye;Qe>=0&&(Qe*=Qe,et=Qe*Qe*Be(Ue,fe,ye));let tt=0,Oe=.5-Te*Te-Me*Me;Oe>=0&&(Oe*=Oe,tt=Oe*Oe*Be(He,Te,Me));let Xe=0,rt=.5-be*be-Ce*Ce;return rt>=0&&(rt*=rt,Xe=rt*rt*Be(Ke,be,Ce)),70*(et+tt+Xe)}noise3d(u,d,M){let L=Number(u),$=Number(d),B=Number(M);if(!Number.isFinite(L)||!Number.isFinite($)||!Number.isFinite(B))return 0;let U=this.perm,j=this.permMod12,K=(L+$+B)*Ae,ue=Math.floor(L+K),le=Math.floor($+K),oe=Math.floor(B+K),fe=(ue+le+oe)*Ee,ye=L-(ue-fe),ve=$-(le-fe),we=B-(oe-fe),Te,Me,be,Ce,Ie,ze;ye>=ve?ve>=we?(Te=1,Me=0,be=0,Ce=1,Ie=1,ze=0):ye>=we?(Te=1,Me=0,be=0,Ce=1,Ie=0,ze=1):(Te=0,Me=0,be=1,Ce=1,Ie=0,ze=1):ve<we?(Te=0,Me=0,be=1,Ce=0,Ie=1,ze=1):ye<we?(Te=0,Me=1,be=0,Ce=0,Ie=1,ze=1):(Te=0,Me=1,be=0,Ce=1,Ie=1,ze=0);let Ue=ye-Te+Ee,He=ve-Me+Ee,Ke=we-be+Ee,et=ye-Ce+2*Ee,Qe=ve-Ie+2*Ee,tt=we-ze+2*Ee,Oe=ye-1+3*Ee,Xe=ve-1+3*Ee,rt=we-1+3*Ee,yt=ue&255,pt=le&255,ot=oe&255,bt=j[yt+U[pt+U[ot]]]*3,St=j[yt+Te+U[pt+Me+U[ot+be]]]*3,dt=j[yt+Ce+U[pt+Ie+U[ot+ze]]]*3,gt=j[yt+1+U[pt+1+U[ot+1]]]*3,Bt=0,Nt=.6-ye*ye-ve*ve-we*we;Nt>=0&&(Nt*=Nt,Bt=Nt*Nt*Fe(bt,ye,ve,we));let Vt=0,Et=.6-Ue*Ue-He*He-Ke*Ke;Et>=0&&(Et*=Et,Vt=Et*Et*Fe(St,Ue,He,Ke));let qt=0,tr=.6-et*et-Qe*Qe-tt*tt;tr>=0&&(tr*=tr,qt=tr*tr*Fe(dt,et,Qe,tt));let Mr=0,mr=.6-Oe*Oe-Xe*Xe-rt*rt;return mr>=0&&(mr*=mr,Mr=mr*mr*Fe(gt,Oe,Xe,rt)),32*(Bt+Vt+qt+Mr)}noise4d(u,d,M,L){let $=Number(u),B=Number(d),U=Number(M),j=Number(L);if(!Number.isFinite($)||!Number.isFinite(B)||!Number.isFinite(U)||!Number.isFinite(j))return 0;let K=this.perm,ue=($+B+U+j)*$e,le=Math.floor($+ue),oe=Math.floor(B+ue),fe=Math.floor(U+ue),ye=Math.floor(j+ue),ve=(le+oe+fe+ye)*De,we=$-(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),ze=(we<=Me?1:0)+(Te<=Me?1:0)+(Me>be?1:0),Ue=(we<=be?1:0)+(Te<=be?1:0)+(Me<=be?1:0),He=Ce>=3?1:0,Ke=Ie>=3?1:0,et=ze>=3?1:0,Qe=Ue>=3?1:0,tt=Ce>=2?1:0,Oe=Ie>=2?1:0,Xe=ze>=2?1:0,rt=Ue>=2?1:0,yt=Ce>=1?1:0,pt=Ie>=1?1:0,ot=ze>=1?1:0,bt=Ue>=1?1:0,St=we-He+De,dt=Te-Ke+De,gt=Me-et+De,Bt=be-Qe+De,Nt=we-tt+2*De,Vt=Te-Oe+2*De,Et=Me-Xe+2*De,qt=be-rt+2*De,tr=we-yt+3*De,Mr=Te-pt+3*De,mr=Me-ot+3*De,qr=be-bt+3*De,Di=we-1+4*De,Mi=Te-1+4*De,dn=Me-1+4*De,gn=be-1+4*De,Wr=le&255,Kr=oe&255,pr=fe&255,dr=ye&255,B0=(K[Wr+K[Kr+K[pr+K[dr]]]]&31)*4,z0=(K[Wr+He+K[Kr+Ke+K[pr+et+K[dr+Qe]]]]&31)*4,V0=(K[Wr+tt+K[Kr+Oe+K[pr+Xe+K[dr+rt]]]]&31)*4,U0=(K[Wr+yt+K[Kr+pt+K[pr+ot+K[dr+bt]]]]&31)*4,O0=(K[Wr+1+K[Kr+1+K[pr+1+K[dr+1]]]]&31)*4,zc=0,yn=.6-we*we-Te*Te-Me*Me-be*be;yn>=0&&(yn*=yn,zc=yn*yn*Ve(B0,we,Te,Me,be));let Vc=0,bn=.6-St*St-dt*dt-gt*gt-Bt*Bt;bn>=0&&(bn*=bn,Vc=bn*bn*Ve(z0,St,dt,gt,Bt));let Uc=0,xn=.6-Nt*Nt-Vt*Vt-Et*Et-qt*qt;xn>=0&&(xn*=xn,Uc=xn*xn*Ve(V0,Nt,Vt,Et,qt));let Oc=0,vn=.6-tr*tr-Mr*Mr-mr*mr-qr*qr;vn>=0&&(vn*=vn,Oc=vn*vn*Ve(U0,tr,Mr,mr,qr));let jc=0,wn=.6-Di*Di-Mi*Mi-dn*dn-gn*gn;return wn>=0&&(wn*=wn,jc=wn*wn*Ve(O0,Di,Mi,dn,gn)),27*(zc+Vc+Uc+Oc+jc)}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(je.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,$=Number(d?.width??u.width)|0,B=Number(d?.height??u.height)|0;if(!L||!($>0&&B>0)||!L.length)return null;let U=$*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:$,h:B,ch:K,isFloat:u.type===1015||u.type===1016||L instanceof Float32Array||L instanceof Float64Array,flipY:!!u.flipY}},it=(T,u,d,M)=>{let L=Math.min(T.w-1,Math.max(0,u*T.w|0)),$=Math.min(T.h-1,Math.max(0,d*T.h|0)),B=T.flipY?T.h-1-$:$,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},nt=e.MeshStandardMaterial?.prototype&&(Object.getPrototypeOf(e.MeshStandardMaterial.prototype)||e.MeshStandardMaterial.prototype);nt&&typeof nt._packPbr!="function"&&(nt._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 $=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($*B*4);for(let j=0;j<B;j++){let K=(j+.5)/B;for(let ue=0;ue<$;ue++){let le=(ue+.5)/$,oe=(j*$+ue)*4;U[oe]=255,U[oe+1]=M?it(M,le,K,1):255,U[oe+2]=L?it(L,le,K,2):255,U[oe+3]=255}}T=_(U,$,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,$=Math.min(128,M.w),B=Math.min(128,M.h),U=new Uint8ClampedArray($*B*4),j=(K,ue)=>it(M,((K%$+$)%$+.5)/$,((ue%B+B)%B+.5)/B,0)/255;for(let K=0;K<B;K++)for(let ue=0;ue<$;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*$+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,$,B,!1,!0,128).uri,d=1}}return{mrUri:T,normUri:u,normScale:d}});let ct=0,Je=e.Vector2,Dt=e.PlaneGeometry,Ft=e.Mesh,lr=e.Material;class wt extends lr{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 wt({...this,emissive:this._em?this.emissive:void 0})}}class Gt extends Ft{constructor(u){super(new Dt(1,1),u instanceof lr?u:new wt(u||{})),this.isSprite=!0,this.center=new Je(.5,.5),this.userData={xr:{billboard:"spherical"}}}_cloneCustom(){let u=new Gt(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_${++ct}`,this._autoNamed=!0),this._bakedOwner=this):this.name||(this.name=`Sprite_${++ct}`,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),$=Number.isFinite(L)?L:0,B=`${d},${M},${$}`;if(this._bakedKey!==B&&(this._bakedKey!==void 0||d!==.5||M!==.5||$!==0)){let U=new Dt(1,1),j=U.attributes.position?.array,K=.5-d,ue=.5-M,le=Math.cos($),oe=Math.sin($);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(wt.prototype),Object.freeze(Gt.prototype),Je?.prototype){let T=Je.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 $=Number(L)||0,B=d?.x||0,U=d?.y||0;return this.set(B+((M?.x||0)-B)*$,U+((M?.y||0)-U)*$)}),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},at=T=>Math.max(0,Math.min(1,Pe(T,0))),vt=T=>new Je(Pe(T?.x),Pe(T?.y));class Mt{constructor(u="Curve"){this.type=u,this.arcLengthDivisions=200,this._lenCache=null}getPoint(u,d=new Je){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,$=this.getPoint(0);for(let B=1;B<=d;B++){let U=this.getPoint(B/d);L+=Math.hypot(Pe(U.x)-Pe($.x),Pe(U.y)-Pe($.y),Pe(U.z)-Pe($.z)),M.push(L),$=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,$=M[L-1]||0;if($<=0||L<2)return at(u);let B=d!==void 0&&Number.isFinite(Number(d))?Math.max(0,Math.min($,Number(d))):at(u)*$,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]??$)-ue;return(K+(le>1e-12?(B-ue)/le:0))/(L-1)}getTangent(u,d){let M=at(u),L=this.getPoint(Math.max(0,M-1e-4)),$=this.getPoint(Math.min(1,M+1e-4)),B=Pe($.x)-Pe(L.x),U=Pe($.y)-Pe(L.y);if("z"in L||d?.isVector3){let K=Pe($.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 Je).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 $=d[L];Array.isArray($)?M[L]=$.map(B=>B?.clone?B.clone():B&&typeof B=="object"&&"x"in B?vt(B):B):$?.clone?M[L]=$.clone():$&&typeof $=="object"&&"x"in $?M[L]=vt($):M[L]=$}return this}}class Pt extends Mt{constructor(u,d){super("LineCurve"),this.isLineCurve=!0,this.v1=vt(u),this.v2=vt(d)}getPoint(u,d=new Je){let M=Pe(u,0),L=Pe(this.v1.x),$=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,$+(Pe(this.v2.y)-$)*M)}getPointAt(u,d=new Je){return this.getPoint(at(u),d)}}class Ct extends Mt{constructor(u,d,M){super("QuadraticBezierCurve"),this.isQuadraticBezierCurve=!0,this.v0=vt(u),this.v1=vt(d),this.v2=vt(M)}getPoint(u,d=new Je){let M=at(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 Xt extends Mt{constructor(u,d,M,L){super("CubicBezierCurve"),this.isCubicBezierCurve=!0,this.v0=vt(u),this.v1=vt(d),this.v2=vt(M),this.v3=vt(L)}getPoint(u,d=new Je){let M=at(u),L=1-M,$=L*L,B=M*M;return d.set($*L*Pe(this.v0.x)+3*$*M*Pe(this.v1.x)+3*L*B*Pe(this.v2.x)+B*M*Pe(this.v3.x),$*L*Pe(this.v0.y)+3*$*M*Pe(this.v1.y)+3*L*B*Pe(this.v2.y)+B*M*Pe(this.v3.y))}}class Ot extends Mt{constructor(u=[]){super("SplineCurve"),this.isSplineCurve=!0,this.points=Array.isArray(u)?u:[]}getPoint(u,d=new Je){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 $=(L-1)*at(u),B=Math.floor($),U=$-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 Yt extends Mt{constructor(u=0,d=0,M=1,L=1,$=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($,0),this.aEndAngle=Pe(B,Math.PI*2),this.aClockwise=!!U,this.aRotation=Pe(j,0)}getPoint(u,d=new Je){let M=Math.PI*2,L=Pe(this.aStartAngle,0),$=Pe(this.aEndAngle,M)-L;Math.abs($)>=1e-9?($=($%M+M)%M,$<1e-9&&($=M),this.aClockwise&&($=$===M?-M:$-M)):$=0;let B=L+at(u)*$,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 Qt extends Yt{constructor(u=0,d=0,M=1,L=0,$=Math.PI*2,B=!1){super(u,d,M,M,L,$,B,0),this.type="ArcCurve",this.isArcCurve=!0}}class Zt extends Mt{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 $=M.getPoints(32);for(let B=1;B<$.length;B++)L+=Math.hypot(Pe($[B]?.x)-Pe($[B-1]?.x),Pe($[B]?.y)-Pe($[B-1]?.y),Pe($[B]?.z)-Pe($[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 Je).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 $=at(u)*L;for(let B=0;B<M.length;B++)if($<=M[B]||B===M.length-1){let U=B>0?M[B-1]:0,j=M[B]-U,K=j>1e-12?($-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 $ of this.curves){let B=$?.isEllipseCurve?d*2:$?.isLineCurve||$ instanceof(e.LineCurve3||Function)?1:$?.isSplineCurve&&Array.isArray($.points)?d*Math.max(1,$.points.length):d;for(let U of $.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 $=M[0];Math.hypot(Pe(L.x)-Pe($.x),Pe(L.y)-Pe($.y),Pe(L.z)-Pe($.z))>1e-6&&M.push($.clone?$.clone():$)}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 ur=e.BufferAttribute,br=e.Object3D,oi=e.Line,Jt=e.LineSegments,er=e.LineBasicMaterial,vi=e.MeshBasicMaterial,Hr=e.ConeGeometry,xr=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},Ht=T=>{let u=new n;return u.setAttribute("position",new ur(new Float32Array(T),3)),u.__isSegmentPairs=!0,u},ro=[0,1,1,3,3,2,2,0,4,5,5,7,7,6,6,4,0,4,1,5,3,7,2,6],fn=(T,u,d,M,L,$)=>{if(!Number.isFinite(T+u+d+M+L+$)||M<T||L<u||$<d)return new n;let B=[];for(let U of ro)B.push(U&1?M:T,U&2?L:u,U&4?$:d);return Ht(B)};class wi extends Jt{constructor(u=10,d=10,M=4473924,L=8947848){let $=Math.max(1e-4,Math.abs(Pe(u,10))),B=Math.max(1,Math.min(256,Math.floor(Pe(d,10)))),U=new xr(M??4473924),j=new xr(L??8947848),K=$*.5,ue=$/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(Ht(oe.length?oe:fe),new er({color:oe.length?j:U})),this.type="GridHelper",this.isGridHelper=!0,this._size=$,this._divisions=B,this._internalKids=0,fe.length&&oe.length){let ye=new Jt(Ht(fe),new er({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 wi(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 Nr extends Jt{constructor(u=1){let d=Math.max(1e-4,Math.abs(Pe(u,1)));super(Ht([0,0,0,d,0,0]),new er({color:16724736})),this.type="AxesHelper",this.isAxesHelper=!0,this._size=d,this._yAxis=new Jt(Ht([0,0,0,0,d,0]),new er({color:3407616})),this._zAxis=new Jt(Ht([0,0,0,0,0,d]),new er({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 Nr(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 Cr extends br{constructor(u=new r(0,0,1),d=new r(0,0,0),M=1,L=16776960,$,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 ur(new Float32Array([0,0,0,0,1,0]),3)),this.line=new oi(U,new er({color:L})),this.cone=new Ft(new Hr(.5,1,8).translate(0,-.5,0),new vi({color:L})),this.add(this.line),this.add(this.cone),this.setDirection(u).setLength(M,$,B)}setDirection(u){let d=Pe(u?.x,0),M=Pe(u?.y,0),L=Pe(u?.z,1),$=Math.hypot(d,M,L),B=$>1e-9?d/$:0,U=$>1e-9?M/$:1,j=$>1e-9?L/$: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))),$=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*$;return this.line.scale.set(1,Math.max(1e-4,L-$),1),this.line.updateMatrix?.(),this.cone.scale.set(B,$,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 Cr;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 Er extends Jt{constructor(u=new a,d=16776960){let M=u instanceof a?u:new a(u?.min,u?.max);super(M.isEmpty()?new n:fn(M.min.x,M.min.y,M.min.z,M.max.x,M.max.y,M.max.z),new er({color:d})),this.type="Box3Helper",this.isBox3Helper=!0,this.box=M}_bakeAuthorGeometry(){let u=this.box,d=!u||u.isEmpty()?new n:fn(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 Er(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 li extends Jt{constructor(u,d=16776960){super(new n,new er({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:fn(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 li(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[Mt,Pt,Ct,Xt,Ot,Yt,Qt,Zt,wi,Nr,Cr,Er,li])Object.freeze(T.prototype);let hr=["checkerboard","grid","wood","marble","brushedMetal","carbonFiber","concrete","brick","fabric","leather","rust"],mn=[[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]],oa=(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},vr=(T,u,d)=>oa(T,u,d)/4294967296,fr=(T,u)=>(T%u+u)%u,Lc=(T,u,d,M,L)=>{let $=Math.floor(T),B=Math.floor(u),U=T-$,j=u-B,K=fr($,d),ue=fr(B,M),le=(K+1)%d,oe=(ue+1)%M,fe=U*U*(3-2*U),ye=j*j*(3-2*j),ve=vr(K,ue,L),we=vr(le,ue,L),Te=vr(K,oe,L),Me=vr(le,oe,L);return ve+(we-ve)*fe+(Te-ve)*ye+(ve-we-Te+Me)*fe*ye},kr=(T,u,d,M,L,$)=>{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*Lc(T*le,u*oe,le,oe,$+ue>>>0),j+=U,U*=.5,K*=2}return B/j},io=T=>T-Math.floor(T),no=T=>Math.abs(io(T)*2-1),pn=(T,u,d)=>{let M=(d-T)/(u-T);return M<0?M=0:M>1&&(M=1),M*M*(3-2*M)},wr=(T,u,d)=>T+(u-T)*d,Fr=T=>T<=0?0:T>=1?255:Math.floor(T*255+.5),T0=(T,u,d,M,L,$,B,U,j,K,ue)=>{let le=Me=>[L[0]*Me,L[1]*Me,L[2]*Me],oe=(Me,be,Ce)=>[wr(Me[0],be[0],Ce),wr(Me[1],be[1],Ce),wr(Me[2],be[2],Ce)];if(T===0){let Me=fr(Math.floor(U*d)+Math.floor(j*d),2)===1?$:L;return[Me[0],Me[1],Me[2],.5,B,0]}if(T===1){let Me=io(U*d),be=io(j*d),Ce=Math.max(.035,d/u),Ie=1-pn(Ce*.5,Ce,Math.min(Me,1-Me,be,1-be));return[...oe(L,$,Ie),.3+.4*Ie,B,0]}if(T===2){let Me=kr(U,j,4,4,4,M),be=no(j*d+Me*1.5),Ce=kr(U,j,2,96,2,M+7>>>0),Ie=be*.7+Ce*.3;return[...le(wr(.55,1,Ie)),Ie,B+(1-Ie)*.15,0]}if(T===3){let Me=kr(U,j,3,3,5,M),be=no((U+j)*d+Me*2.5),Ce=be*be,Ie=Ce*Ce,ze=Ie*Ie,Ue=.92+.08*Me,He=oe(L,$,ze*.85);return[He[0]*Ue,He[1]*Ue,He[2]*Ue,.5-ze*.2,B+ze*.1,0]}if(T===4){let Me=kr(U,j,2,192*d,2,M),be=vr(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),ze=Ce-Math.floor(Ce),Ue=fr(Math.floor(be)+Math.floor(Ce),2)===0,He=Ue?ze*2-1:Ie*2-1,Ke=1-He*He,et=.08*no(Ue?ze*8:Ie*8),Qe=.6+.4*Ke;return[L[0]*Qe+et,L[1]*Qe+et,L[2]*Qe+et,Ke*.8,B+.1*(1-Ke),0]}if(T===6){let Me=kr(U,j,d,d,5,M),be=vr(K,ue,M+31>>>0),Ce=d*16,Ie=pn(.82,.9,Lc(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,ze=U*Me+(fr(Ce,2)===1?.5:0),Ue=Math.floor(ze),He=ze-Ue,Ke=Math.min(Math.min(He,1-He)*2,Math.min(Ie,1-Ie)),et=Math.max(.06,1.5*d/u),Qe=1-pn(et*.5,et,Ke),tt=vr(fr(Ue,Me),fr(Ce,d),M),Oe=kr(U,j,d,d,3,M+5>>>0),Xe=.8+.25*tt+.15*(Oe-.5),rt=.9+.1*Oe;return[wr(L[0]*Xe,$[0]*rt,Qe),wr(L[1]*Xe,$[1]*rt,Qe),wr(L[2]*Xe,$[2]*rt,Qe),(1-Qe)*(.75+.1*Oe)+Qe*.2,wr(B,.95,Qe),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,ze=fr(Math.floor(Me)+Math.floor(be),2)===0?1-Ce*Ce:1-Ie*Ie,Ue=kr(U,j,4,4,2,M);return[...le((.75+.25*ze)*(.95+.1*(Ue-.5))),ze,B,0]}if(T===9){let Me=U*d,be=j*d,Ce=Math.floor(Me),Ie=Math.floor(be),ze=1e9,Ue=1e9;for(let et=-1;et<=1;et++)for(let Qe=-1;Qe<=1;Qe++){let tt=Ce+Qe,Oe=Ie+et,Xe=fr(tt,d),rt=fr(Oe,d),yt=tt+vr(Xe,rt,M)-Me,pt=Oe+vr(Xe,rt,M+1>>>0)-be,ot=yt*yt+pt*pt;ot<ze?(Ue=ze,ze=ot):ot<Ue&&(Ue=ot)}let He=1-pn(0,.12,Math.sqrt(Ue)-Math.sqrt(ze)),Ke=kr(U,j,4,4,3,M+3>>>0);return[...le((.85+.2*(Ke-.5))*(1-.3*He)),.6-.4*He+.1*(Ke-.5),B+.15*He,0]}let fe=kr(U,j,d,d,5,M),ye=pn(.45,.6,fe),ve=kr(U,j,d*8,d*8,3,M+9>>>0),we=.9+.1*ve,Te=.7+.5*ve;return[wr($[0]*we,L[0]*Te,ye),wr($[1]*we,L[1]*Te,ye),wr($[2]*we,L[2]*Te,ye),.4+.4*ye*ve+.1*ye,wr(.35,B,ye),1-ye]},P0=(T,u,d,M,L,$,B,U)=>{let j=globalThis.__three_live_native_material_preset__;if(typeof j=="function"){let oe=j(T,u,d,M,...L,...$,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=T0(T,u,d,M,L,$,B,(ye+.5)/u,fe,ye,oe),we=(oe*u+ye)*4;K[we]=Fr(ve[0]),K[we+1]=Fr(ve[1]),K[we+2]=Fr(ve[2]),K[we+3]=255,ue[we]=255,ue[we+1]=Fr(ve[4]),ue[we+2]=Fr(ve[5]),ue[we+3]=255,le[oe*u+ye]=ve[3]}}return[K,Rc(le,u,U),ue]},Rc=(T,u,d)=>{let M=new Uint8Array(u*u*4),L=d*u*.0625;for(let $=0;$<u;$++){let B=($+u-1)%u,U=($+1)%u;for(let j=0;j<u;j++){let K=-(T[$*u+(j+1)%u]-T[$*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=($*u+j)*4;M[oe]=Fr(K*le*.5+.5),M[oe+1]=Fr(ue*le*.5+.5),M[oe+2]=Fr(le*.5+.5),M[oe+3]=255}}return M},Ic=(T,u)=>{let d=u;try{T!=null&&(d=new xr(T).getHex())}catch{}return[(d>>16&255)/255,(d>>8&255)/255,(d&255)/255]},la=new Map,ao=(T,u={})=>{let d=hr.indexOf(T);if(d<0)throw new TypeError(`THREE.ProceduralTexture: unknown preset '${T}' (use ${hr.join(", ")})`);let M=u&&typeof u=="object"?u:{},L=mn[d],$=Math.max(1,Math.min(256,Math.round(Pe(M.scale,L[0]))));(d===0||d===7||d===8)&&$%2===1&&$++;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=Ic(M.color,L[1]),K=Ic(M.color2,L[2]||L[1]),ue=at(Pe(M.roughness,L[3])),le=Math.max(0,Math.min(8,Pe(M.normalStrength,1))),oe=[d,B,$,U,...j,...K,ue,le].join(","),fe=la.get(oe);if(fe)return{...fe};let[ye,ve,we]=P0(d,B,$,U,j,K,ue,le),Te=(Ce,Ie)=>{let ze=new _e(B,B);ze._data.set(Ce),ze._ver++;let Ue=new W(ze);return Ue.flipY=!1,Ue.colorSpace=Ie,Ue.name=`${T}_${Ie==="srgb"?"albedo":Ce===ve?"normal":"orm"}`,Ue},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,la.size>=64&&la.clear(),la.set(oe,be),{...be}},so={presets:Object.freeze(hr.slice()),create:(T,u)=>ao(String(T),u)};for(let T of hr)so[T]=u=>ao(T,u);Object.freeze(so);let N0=500,C0=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>N0?null:u},E0=T=>{let u=typeof T=="number"?T:NaN;return Number.isFinite(u)?u<=384?256:u<=768?512:1024:512},$c=T=>T>512&&T%2===0?T/2:T,L0=(T,u)=>{let d=u/2,M=new Uint8Array(d*d*4);for(let L=0;L<d;L++)for(let $=0;$<d;$++){let B=(2*L*u+2*$)*4,U=B+u*4,j=(L*d+$)*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},R0=T=>{let u=typeof T=="number"?T:NaN,d=Number.isFinite(u)?Math.abs(u):1;return Math.floor(d+.5)%4294967296},I0=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},$0=(T,u,d)=>{let M=I0(`three-live-texture1${T}${u}${d}`),L=3421674724,$=2216829733;for(let B of M){$=($^B)>>>0;let U=$&65535,j=$>>>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+($<<8>>>0)>>>0,$=le>>>0}return L.toString(16).padStart(8,"0")+$.toString(16).padStart(8,"0")},Dc=T=>{let u=C0(T?.prompt);if(u===null)return null;let d=E0(T?.size),M=R0(T?.seed);return{prompt:u,size:d,seed:M,key:$0(u,d,M)}},oo=(T,u,d,M,L)=>{if($c(u)!==u)return oo(L0(T,u),u/2,d,M,L);let $=new Float64Array(u*u);for(let be=0;be<u*u;be++){let Ce=be*4;$[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 ze=0;ze<=2*B;ze++)Ie+=$[be*u+(Ce+u+ze-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 Ue=0;Ue<=2*B;Ue++)Ie+=U[(be+u+Ue-B)%u*u+Ce];let ze=j*$[be*u+Ce]-Ie;K[be*u+Ce]=ze,ze<ue&&(ue=ze),ze>le&&(le=ze)}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=Rc(fe,u,ye),we=Number.isFinite(M)?Math.max(0,Math.min(1,M)):0,Te=Fr(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]=Fr(we+.35*(.5-fe[be])),Me[Ce+2]=Te,Me[Ce+3]=255}return[ve,Me]},ua=new Map,kc=new WeakMap,D0=0,k0=(T,u)=>{let d=Dc(T);if(!d)return null;let{prompt:M,size:L,seed:$,key:B}=d,U=at(Pe(T.roughness,u>=0?mn[u][3]:.8)),j=at(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=kc.get(oe)??0,fe||kc.set(oe,fe=++D0));let ye=[fe,B,K,U,j].join(","),ve=fe?ua.get(ye):void 0;if(ve)return{...ve};let we=null;if(typeof le=="function"){let Ie=le(M,L,$,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,...oo(Ie.rgba,L,K,U,j)])}if(!we)return null;let Te=(Ie,ze,Ue,He)=>{let Ke=new W({data:new Uint8ClampedArray(Ie.buffer,Ie.byteOffset,ze*ze*4),width:ze,height:ze});return Ke.flipY=!1,Ke.colorSpace=Ue,Ke.name=`ai_${B}_${He}`,Ke._pngDim=ze,Ke},Me=$c(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&&(ua.size>=32&&ua.clear(),ua.set(ye,Ce)),{...Ce}},Fc=new Set,F0=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??""),$=hr.indexOf(L),B=!!M&&M.prompt!==void 0&&M.prompt!==null,U=B?k0(M,$):null;if(!M||$<0&&!U){!(B&&L==="")&&!Fc.has(L)&&(Fc.add(L),console.warn(`[three-live] userData.xr.material: unknown preset '${L}' (use ${hr.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 xr(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??ao(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},Bc={Box3:a,Sphere:o,CanvasTexture:W,ImprovedNoise:pe,SimplexNoise:je,SpriteMaterial:wt,Sprite:Gt,LineCurve:Pt,QuadraticBezierCurve:Ct,CubicBezierCurve:Xt,SplineCurve:Ot,EllipseCurve:Yt,ArcCurve:Qt,CurvePath:Zt,GridHelper:wi,AxesHelper:Nr,ArrowHelper:Cr,Box3Helper:Er,BoxHelper:li,ProceduralTexture:so};return t&&typeof t=="object"&&(t.authorNamespace||(t.authorNamespace={}),Object.assign(t.authorNamespace,Bc),t.createCanvas=D,t._procMaterialize=F0,t.canonicalTextureSpec=Dc,t.deriveTextureMaps=oo,t.encodeRgbaPngDataUri=(T,u,d)=>_(T,u,d,!1,!1,f).uri,t.materializeDeclarativeGeometry=T=>{t._cadMaterialize?.(T),t._lodMaterialize?.(T),t._procMaterialize?.(T)}),Bc}var _o={name:"procedural",onRegister(){Mn(ga);let e=We(),t=e.threeNamespace??(typeof globalThis<"u"?globalThis.THREE:void 0);t&&ga(t,e)}};function oh(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 I=Math.min(w,P-R);if(y+I>v.length)return null;v.set(h.subarray(R,R+I),y),y+=I,R+=I,w-=I,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 I=S[1]|S[2]<<8;if((I^(S[3]|S[4]<<8))!==65535)return null;w=I,I===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 I=R>=4?h[S+R-4]:0,F=w>0?h[E+R]:0,V=0;if(_===1)V=I;else if(_===2)V=F;else if(_===4){let J=R>=4&&w>0?h[E+R-4]:0,re=I+F-J,Q=Math.abs(re-I),ee=Math.abs(re-F),k=Math.abs(re-J);V=Q<=ee&&Q<=k?I: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,I)=>(R[I]|R[I+1]<<8|R[I+2]<<16|R[I+3]<<24)>>>0,g=(R,I,F)=>{R[I]=F&255,R[I+1]=F>>>8&255,R[I+2]=F>>>16&255,R[I+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)),I=p(h,12);if(p(h,16)!==1313821514||20+I>R)return Promise.resolve(h);x=JSON.parse(new TextDecoder().decode(h.subarray(20,20+I)));let F=20+I;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 I=A[R];if(!I||typeof I!="object")continue;let F=y[I.bufferView];if(typeof I.uri=="string"&&I.uri.indexOf(E)===0){let V=m(I.uri.slice(E.length));V&&(w.push(R),S.push(V))}else I.mimeType==="image/png"&&F&&(F.buffer||0)===0&&b.indexOf(I.bufferView)<0&&b.push(I.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,I)=>(y[R].byteOffset||0)-(y[I].byteOffset||0));let C=0;for(let R=0;R<N.length;R++){let I=y[N[R]],F=I.byteOffset||0;if(typeof I.byteLength!="number"||(I.buffer||0)!==0||F<C||F+I.byteLength>v.length)return Promise.resolve(h);C=F+I.byteLength}let _=R=>{let I=y[R].byteOffset||0;return v.subarray(I,I+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 I=[];for(let k=0;k<y.length;k++){let G=b.indexOf(k);I.push(G>=0?R[G]:_(k))}let F=0;for(let k=0;k<N.length;k++)F=(F+3&-4)+I[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(I[G],J),y[G].byteOffset=J,y[G].byteLength=I[G].length,J+=I[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 ap={5120:1,5121:1,5122:2,5123:2,5125:4,5126:4};function Fi(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=ap[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 sp(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 _i(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 lh=["neutral","reinhard","none","aces","agx"];function Bi(e){let t=String(e??"").trim().toLowerCase();return lh.includes(t)?t:"neutral"}function op(e){return lh.indexOf(Bi(e))}function lp(e){return new TextDecoder().decode(e)}var uh=We().decoders;function up(e,t){uh.set(e.toLowerCase(),t)}function ya(e){return uh.get(e.toLowerCase())}function ch(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=lp(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)&&!ya(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 Lt)h.onParseGLB?.(m);return m}function hh(e,t=An(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 cp(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 zi(e){if(cp(e))return e;if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return ch(e);throw new TypeError("Invalid 3D model input: expected GLBData ({ gltf, bin }) or binary GLB (ArrayBuffer / ArrayBufferView).")}var So=`#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
|
+
}`,hp=`#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 fh(e,t,r=1){t=Bi(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 fp=`#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);}`,mp=`#version 300 es
|
|
247
212
|
precision highp float;
|
|
248
213
|
uniform vec4 uColorId;
|
|
249
214
|
out vec4 fragColor;
|
|
250
|
-
void main(){fragColor=uColorId;}`;function Bi(e,t,r){let i={};for(let s of r)i[s]=e.getUniformLocation(t,s);return i}var ua=["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 ha(){let e=Se().xrDepthShader;return{fs:hl.replace("/*XRD_U*/",e?.uniformsGLSL||"").replace("/*XRD_O*/",e?.occlusionGLSL||""),uniforms:e?[...ua,...e.uniformNames]:ua}}function fl(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 zi(e,t,r,i,s,n,l,a){if(i===void 0||!t.accessors?.[i])return null;let o=Xt(t,r,t.accessors[i],n);if(!o)return null;a&&(o=o.slice(),nl(o,a));let u=e.createBuffer();return l.push(u),e.bindBuffer(34962,u),e.bufferData(34962,o,35044),e.enableVertexAttribArray(s),e.vertexAttribPointer(s,n,5126,!1,0,0),o}function $i(e){let t=Number(e);return Number.isFinite(t)?Math.max(0,t):1}function ca(e,t,r){let i=ha(),s=oa,n=i.fs,l=!1;for(let o of Fe)if(o.onResolveShader){let u=o.onResolveShader(t,r,s,n);u&&(s=u.vs,n=u.fs,l=!0)}let a=l?qt(e,s,n):null;return{program:a,uniforms:a?Bi(e,a,i.uniforms):null}}function pl(e,t,r){let i=t.instanceMatrices;if(!i||i.length<16||typeof e.vertexAttribDivisor!="function"||typeof e.drawElementsInstanced!="function")return!1;let s=i.length>>4,n=t.instanceColors,l=new Float32Array(s*20);for(let o=0;o<s;o++)l.set(i.subarray(o*16,o*16+16),o*20),l[o*20+16]=n?n[o*3]:1,l[o*20+17]=n?n[o*3+1]:1,l[o*20+18]=n?n[o*3+2]:1,l[o*20+19]=1;let a=e.createBuffer();r.push(a),e.bindBuffer(34962,a),e.bufferData(34962,l,35044);for(let o=0;o<5;o++)e.enableVertexAttribArray(8+o),e.vertexAttribPointer(8+o,4,5126,!1,80,o*16),e.vertexAttribDivisor(8+o,1);return!0}function dl(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 s of i){let n=s?.extensions?.KHR_texture_transform;if(n&&typeof n=="object")return n}return null}var gl=Object.freeze({maxMeshes:1e3,maxTextures:64,maxVertices:1e6,maxIndices:3e6}),ma=Object.freeze({maxMeshes:1/0,maxTextures:1/0,maxVertices:1/0,maxIndices:1/0});function _r(e,t){t.indices?e.drawElements(4,t.indexCount,t.indexType,0):e.drawArrays(4,0,t.indexCount)}function fa(e,t){let r=e?.pbrMetallicRoughness,i=r?.baseColorFactor,s=e?.extensions?.KHR_materials_clearcoat,n=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:s?s.clearcoatFactor??1:0,clearcoatRoughness:Math.max(.04,s?.clearcoatRoughnessFactor??.04),texture:n(r?.baseColorTexture),metallicRoughnessTexture:n(r?.metallicRoughnessTexture),normalTexture:n(e?.normalTexture),normalScale:e?.normalTexture?.scale??1,occlusionTexture:n(e?.occlusionTexture),occlusionStrength:e?.occlusionTexture?.strength??1,isTransmissive:(e?.extensions?.KHR_materials_transmission?.transmissionFactor??0)>0}}function pa(e,t,r){let i=new Set,s=n=>{n&&!i.has(n)&&(i.add(n),e.deleteTexture(n))};for(let n of t)for(let l of n.primitives){if(l.vao&&e.deleteVertexArray(l.vao),l.buffers)for(let o of l.buffers)e.deleteBuffer(o);s(l.texture),s(l.metallicRoughnessTexture),s(l.normalTexture),s(l.occlusionTexture);let a=new Set;l.customProgram&&a.add(l.customProgram);for(let o of l.programCache?.values()??[])o.program&&a.add(o.program);for(let o of a)e.deleteProgram(o)}if(r)for(let n of r)s(n)}function da(e,t,r=ma,i){let s={meshes:[],mesh:null,gpuTextures:[],vao:null,buffers:[]};try{return yl(e,t,r,i,s)}catch(n){let l=s.mesh&&!s.meshes.includes(s.mesh)?[...s.meshes,s.mesh]:s.meshes;pa(e,l,s.gpuTextures),s.vao&&e.deleteVertexArray(s.vao);for(let a of s.buffers)e.deleteBuffer(a);throw n}}function yl(e,t,r,i,s){if(!t||!t.gltf)throw new Error("Invalid GLBData passed to buildGpuScene: missing gltf object.");let{gltf:n}=t,l=Yt("meshopt");l?.decodeBufferViews&&l.decodeBufferViews(n,t);let a=t.bin,o=[];s.meshes=o;let u=[],h=n.extensions?.KHR_materials_variants;h&&Array.isArray(h.variants)&&h.variants.forEach((L,w)=>{u.push(typeof L?.name=="string"&&L.name?L.name:`Variant_${w}`)});let c=Rr(n),f=[];if(Array.isArray(n.nodes))for(let L=0;L<n.nodes.length;L++){let w=n.nodes[L];w.mesh!==void 0&&n.meshes&&n.meshes[w.mesh]&&f.push({node:w,nodeIdx:L,meshIdx:w.mesh})}let p=f.length>0?f:(n.meshes||[]).map((L,w)=>({node:L,nodeIdx:-1,meshIdx:w})),m=[],g=Array.isArray(t.lights)&&t.lights.length>0?t.lights:Array.isArray(n.asset?.extras?.lights)&&n.asset.extras.lights.length>0?n.asset.extras.lights:null;if(g)for(let L of g)m.push({...L,type:L.type||L.light_type||"point",innerConeAngle:L.innerConeAngle??L.inner_cone_angle,outerConeAngle:L.outerConeAngle??L.outer_cone_angle});else if(n.extensions?.KHR_lights_punctual?.lights){let L=n.extensions.KHR_lights_punctual.lights;for(let w of L){let ie=w.type==="directional"?"directional":w.type==="point"?"point":w.type==="spot"?"spot":"ambient";m.push({type:ie,color:w.color||[1,1,1],intensity:w.intensity!==void 0?w.intensity:1})}}if(m.length===0&&(m.push({type:"ambient",color:[1,1,1],intensity:.35}),m.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 x=[];if(s.gpuTextures=x,n.textures&&n.images){if(n.textures.length>r.maxTextures)throw new Error(`SecurityError: GLB scene exceeds host texture limit (${r.maxTextures}). Found: ${n.textures.length}`);for(let L=0;L<n.textures.length;L++){let w=n.textures[L],ie=n.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 k=J=>{e.bindTexture(3553,oe),e.texImage2D(3553,0,6408,6408,5121,J),e.generateMipmap(3553),i?.()};if(ie.bufferView!==void 0){let J=n.bufferViews[ie.bufferView],z=J.byteOffset||0,Y=new Blob([a.slice(z,z+J.byteLength)],{type:ie.mimeType||"image/png"});typeof createImageBitmap=="function"&&createImageBitmap(Y).then(k).catch(()=>{})}else if(ie.uri){let J=fl(ie.uri);if(J){let z=new Image;z.crossOrigin="anonymous",z.referrerPolicy="no-referrer",z.onload=()=>k(z),z.src=J}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],d=0,y=0;for(let L=0;L<p.length;L++){let w=p[L],ie=n.meshes[w.meshIdx],oe=w.nodeIdx>=0?c[w.nodeIdx]:Ee(),k=new Float32Array(9);Ye(k,oe);let J={name:w.node.name||ie.name||`Mesh_${w.meshIdx}`,nodeIndex:w.nodeIdx,transform:oe,normalMatrix:k,primitives:[],extras:w.node.extras||ie.extras,...w.node?.visible===!1||w.node?.extensions?.KHR_node_visibility?.visible===!1?{visible:!1}:{}};s.mesh=J;let z=w.node?.extensions?.EXT_mesh_gpu_instancing;if(z&&z.attributes&&typeof z.attributes=="object"){let Y=z.attributes,le=Y.TRANSLATION!==void 0?n.accessors?.[Y.TRANSLATION]:null,he=Y.ROTATION!==void 0?n.accessors?.[Y.ROTATION]:null,$=Y.SCALE!==void 0?n.accessors?.[Y.SCALE]:null,U=Y._COLOR_0!==void 0?n.accessors?.[Y._COLOR_0]:null,N=Number(le?.count??he?.count??$?.count??0);if(!Number.isFinite(N)||N<0||N>1e4)throw new Error(`SecurityError: EXT_mesh_gpu_instancing exceeds maximum instance limit (10000). Found: ${N}`);if(N>0){let G=(j,A)=>{if(!j||j.bufferView===void 0||!n.bufferViews?.[j.bufferView])return null;let S=j.componentType??5126,_=I=>(console.warn(`[three-live] EXT_mesh_gpu_instancing: skipping accessor (${I})`),null);if(S!==5120&&S!==5121&&S!==5122&&S!==5123&&S!==5126)return _(`componentType ${S}`);if(!(Number(j.count)>=N))return _(`count ${j.count} < ${N}`);let O=null;try{O=Xt(n,a,{...j,count:N},A)}catch{return _("out of bounds")}return!O||!O.every(Number.isFinite)?_("non-finite value"):O},D=G(le,3),F=G(he,4),E=G($,3),H=U?.type==="VEC4"?4:3,ee=G(U,H),ne=new Float32Array(N*16),ae=Ee();for(let j=0;j<N;j++){let A=D?[D[j*3],D[j*3+1],D[j*3+2]]:[0,0,0],S=F?[F[j*4],F[j*4+1],F[j*4+2],F[j*4+3]]:[0,0,0,1],_=E?[E[j*3],E[j*3+1],E[j*3+2]]:[1,1,1];or(ae,S,A,_),ne.set(ae,j*16)}if(J.instanceMatrices=ne,ee){let j=new Float32Array(N*3);for(let A=0;A<N;A++)j[A*3]=ee[A*H],j[A*3+1]=ee[A*H+1],j[A*3+2]=ee[A*H+2];J.instanceColors=j}}}for(let Y of ie.primitives||[]){if(Y.extensions?.KHR_draco_mesh_compression){let O=Yt("draco");O&&O.decodePrimitive(n,Y,a)}let le=[],he=e.createVertexArray();s.vao=he,s.buffers=le,e.bindVertexArray(he);let $=pl(e,J,le),U=n.accessors[Y.attributes.POSITION],N=Number(U?.count??0);if(!Number.isFinite(N)||N<0||d+N>r.maxVertices)throw new Error(`SecurityError: GLB scene exceeds host vertex limit (${r.maxVertices}).`);if(d+=N,U?.min&&U?.max){let O=I=>{for(let W=0;W<3;W++){let Q=I[12+W],K=I[12+W];for(let Z=0;Z<3;Z++){let X=I[Z*4+W]*U.min[Z],re=I[Z*4+W]*U.max[Z];Q+=X<re?X:re,K+=X>re?X:re}Q<b[W]&&(b[W]=Q),K>v[W]&&(v[W]=K)}};if(J.instanceMatrices&&J.instanceMatrices.length>=16){let I=J.instanceMatrices.length>>4,W=Ee();for(let Q=0;Q<I;Q++){let K=J.instanceMatrices.subarray(Q*16,Q*16+16);ke(W,oe,K),O(W)}}else O(oe)}let G=zi(e,n,a,Y.attributes.POSITION,0,3,le);zi(e,n,a,Y.attributes.NORMAL,1,3,le),zi(e,n,a,Y.attributes.TEXCOORD_0,2,2,le,dl(n,Y));let D=0,F=5123,E=null;if(Y.indices!==void 0){let O=n.accessors[Y.indices],I=(n.bufferViews[O.bufferView].byteOffset||0)+(O.byteOffset||0);if(D=Number(O.count??0),!Number.isFinite(D)||D<0||y+D>r.maxIndices)throw new Error(`SecurityError: GLB scene exceeds host index limit (${r.maxIndices}).`);y+=D,F=O.componentType===5125?5125:5123;let W=e.createBuffer();le.push(W),e.bindBuffer(34963,W),O.componentType===5125?E=new Uint32Array(a,I,O.count):O.componentType===5121?E=Uint16Array.from(new Uint8Array(a,I,O.count)):E=I%2===0?new Uint16Array(a,I,O.count):new Uint16Array(a.slice(I,I+O.count*2)),e.bufferData(34963,E,35044)}else D=U.count;let H={};for(let O of Fe)if(O.onBuildPrimitiveVAO){let I=O.onBuildPrimitiveVAO(e,he,Y,n,a);I&&(H[O.name]=I)}e.bindVertexArray(null);let ee=n.materials&&Y.material!==void 0?n.materials[Y.material]:null,{program:ne,uniforms:ae}=ca(e,Y,ee),j=fa(ee,x),A=!!(ee?.extensions?.KHR_materials_transmission||H.materials?.isTransmissive),S=Y.extensions?.KHR_materials_variants?.mappings,_=Array.isArray(S)?S.filter(O=>O&&typeof O.material=="number"&&Array.isArray(O.variants)).map(O=>({material:O.material|0,variants:O.variants.map(I=>Number(I)|0)})):void 0;J.primitives.push({vao:he,instanced:$,indexCount:D,indexType:F,...j,positions:G,indices:E,buffers:le,materialIndex:Y.material,defaultMaterialIndex:Y.material,variantMappings:_,primitiveDef:Y,programCache:new Map([[Y.material??-1,{program:ne,uniforms:ae}]]),pluginData:H,customProgram:ne,customUniforms:ae,isTransmissive:A})}o.push(J)}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],T=v[0]-b[0],V=v[1]-b[1],q=v[2]-b[2],P=Math.max(Math.hypot(T,V,q)/2,.5),R=[b[0],b[1],b[2]],C=[v[0],v[1],v[2]],B=t.animations;if(!B){for(let L of Fe)if(L.onParseGLB?.(t),t.animations){B=t.animations;break}}return B||(B=[]),{meshes:o,bounds:{center:M,radius:P,min:R,max:C},lights:m,animations:B,worldMatrices:c,gpuTextures:x,availableVariants:u}}function cr(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 Ze=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=Ee(),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=Ee(),this.viewMatrix=Ee(),this.activeViewMatrix=null,this.modelMatrix=Ee(),this.mvpMatrix=Ee(),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:Ee(),rawValueToMeters:.001,format:0},this.container=e;let i,s;if(t&&typeof t.getContext=="function"?(i=t,s=r):(s=t,i=s?.canvas),!i){let a=e.querySelector("canvas");a||(a=document.createElement("canvas"),a.style.width="100%",a.style.height="100%",a.style.display="block",a.style.touchAction="none",e.prepend(a)),i=a}this.canvas=i,this.opts=s||{},this.opts.clearColor&&(this.clearColor=this.opts.clearColor);let n=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches;this.opts.autoRotate!==void 0?this.autoRotate=this.opts.autoRotate&&!n:n&&(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=$i(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=Kt(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){ll(e,t)}static getDecoder(e){return Yt(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=ha();this.renderProg=qt(e,oa,t.fs),this.pickProg=qt(e,cl,ml),this.uRender=Bi(e,this.renderProg,t.uniforms),this.uPick=Bi(e,this.pickProg,["uMVP","uColorId"]),this.setupPickingFbo()}restoreContext(){let e=this.gl;this.contextLost=!1,this.initGlState();for(let t of Fe)t.onContextRestored?.(e,this);this.meshes=[],this.gpuTextures=[],this.environmentTexture=null,this.lastGlbData&&this.loadGLBData(this.lastGlbData,this.lastLimits),this.opts.environmentImage&&this.setEnvironmentImage(this.opts.environmentImage).catch(()=>{}),typeof requestAnimationFrame<"u"&&this.opts.autoStart!==!1&&this.start()}setupPickingFbo(){let e=this.gl;if(typeof e.createFramebuffer!="function")return;this.pickFbo=e.createFramebuffer(),this.pickTexture=e.createTexture(),this.pickDepth=e.createRenderbuffer();let t=Math.max(1,this.canvas.width),r=Math.max(1,this.canvas.height);this.pickFboWidth=t,this.pickFboHeight=r,e.bindTexture(3553,this.pickTexture),e.texImage2D(3553,0,6408,t,r,0,6408,5121,null),e.texParameteri(3553,10241,9728),e.texParameteri(3553,10240,9728),e.bindRenderbuffer(36161,this.pickDepth),e.renderbufferStorage(36161,33189,t,r),e.bindFramebuffer(36160,this.pickFbo),e.framebufferTexture2D(36160,36064,3553,this.pickTexture,0),e.framebufferRenderbuffer(36160,36096,36161,this.pickDepth),e.bindFramebuffer(36160,null)}resizePickingFbo(e,t){if(!this.pickFbo)return;let r=this.gl,i=Math.max(1,e),s=Math.max(1,t);this.pickFboWidth=i,this.pickFboHeight=s,r.bindTexture(3553,this.pickTexture),r.texImage2D(3553,0,6408,i,s,0,6408,5121,null),r.bindRenderbuffer(36161,this.pickDepth),r.renderbufferStorage(36161,33189,i,s)}loadGLBData(e,t){let{meshes:r,bounds:i,lights:s,animations:n,worldMatrices:l,gpuTextures:a,availableVariants:o}=da(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=s,this.animations=n||[],this.worldMatrices=l||[],this.gpuTextures=a||[],this.availableVariants=o||[],this.gltf=e.gltf,this.activeVariantName&&!this.applyVariantMaterial(this.activeVariantName)&&(this.activeVariantName=null),this.initialNodeTransforms=[],Array.isArray(e.gltf?.nodes))for(let c of e.gltf.nodes)this.initialNodeTransforms.push({t:c.translation?[c.translation[0],c.translation[1],c.translation[2]]:[0,0,0],r:c.rotation?[c.rotation[0],c.rotation[1],c.rotation[2],c.rotation[3]]:[0,0,0,1],s:c.scale?[c.scale[0],c.scale[1],c.scale[2]]:[1,1,1]});this.autoplay&&this.animations.length>0&&this.playAnimation(this.animationName||void 0);for(let c of Fe)c.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=$i(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(aa(e))}clearScene(){this.disposeMeshGpuResources(),this.lights=[],this.animations=[],this.currentClip=null,this.isPlayingAnimation=!1,this.animationTime=0,this.lastGlbData=null;for(let e of Fe)e.onClearScene?.(this);this.worldMatrices=[],this.gltf=null,this.initialNodeTransforms=[],this.turntableRotation=0,this.updateTurntableMatrix(),this.gl&&this.render()}loadModel(e){this.loadGLBData(Dt(e))}setBackdropGLB(e,t){if(this.disposeMeshListGpuResources(this.backdropMeshes),this.backdropMeshes=[],!e){this.update(0),this.render();return}let r=Dt(e),{meshes:i}=da(this.gl,r,ma,()=>this.render());if(t)for(let s of i)s.transform[12]+=t[0],s.transform[13]+=t[1],s.transform[14]+=t[2],Ye(s.normalMatrix,s.transform);this.backdropMeshes=i,this.update(0),this.render()}setClearColor(e,t,r,i=1){this.clearColor=[e,t,r,i]}updateMeshTransforms(e){for(let t=0;t<this.meshes.length;t++){let r=this.meshes[t],i;e instanceof Map?i=e.get(r.name)??e.get(t):Array.isArray(e)?i=e[t]:e&&typeof e=="object"&&(Object.prototype.hasOwnProperty.call(e,r.name)?i=e[r.name]:Object.prototype.hasOwnProperty.call(e,t)&&(i=e[t])),i&&i.length===16&&(r.transform.set(i),Ye(r.normalMatrix,r.transform))}}bindLights(e=this.uRender){let t=this.gl,r=[.28,.28,.28],i=[],s=[],n=[],l=[],a=[],o=[];for(let u of this.lights){let h=u.color||[1,1,1],c=u.intensity!==void 0?u.intensity:1;if(u.type==="ambient")r=[h[0]*c,h[1]*c,h[2]*c];else if(u.type==="directional"&&i.length<6){let f=u.direction||[.5,1,.8];i.push(f[0],f[1],f[2]),s.push(h[0]*c,h[1]*c,h[2]*c)}else if((u.type==="point"||u.type==="spot")&&n.length<6){let f=u.position||[0,0,0];if(n.push(f[0],f[1],f[2]),l.push(h[0]*c,h[1]*c,h[2]*c),u.type==="spot"){let p=u.direction||[0,-1,0],m=Math.max(.01,Math.min(Math.PI/2,u.outerConeAngle??Math.PI/3)),g=Math.max(0,Math.min(m-1e-4,u.innerConeAngle??0));a.push(p[0],p[1],p[2]),o.push(Math.cos(g),Math.cos(m))}else a.push(0,-1,0),o.push(-2,-3)}}i.length===0&&(i.push(.5,1,.8),s.push(1,1,1)),t.uniform3fv(e.uAmbientColor,r),t.uniform1i(e.uNumDirLights,i.length/3),i.length>0&&(t.uniform3fv(e.uDirLightDir,i),t.uniform3fv(e.uDirLightColor,s)),t.uniform1i(e.uNumPointLights,n.length/3),n.length>0&&(t.uniform3fv(e.uPointLightPos,n),t.uniform3fv(e.uPointLightColor,l),e.uPointLightSpotDir&&t.uniform3fv(e.uPointLightSpotDir,a),e.uPointLightSpotCone&&t.uniform2fv(e.uPointLightSpotCone,o)),t.uniform1f(e.uEnvIntensity,this.envIntensity)}setExposure(e){this.exposure=$i(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=Kt(e)}getToneMapping(){return this.toneMapping}async setEnvironmentImage(e){for(let t of Fe)if(t.setEnvironmentImage){await t.setEnvironmentImage(this,e);return}}async setSkyboxImage(e){for(let t of Fe)if(t.setSkyboxImage){await t.setSkyboxImage(this,e);return}}setInteractive(e){this.interactive=e}isInteractive(){return this.interactive}getCameraOrbit(){let e=this.currTheta,t=this.currPhi,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)),s=i[0],n=s?[...s.baseColor]:t.pbrMetallicRoughness?.baseColorFactor||[.8,.8,.8,1],l=s?s.metallic:t.pbrMetallicRoughness?.metallicFactor??.1,a=s?s.roughness:t.pbrMetallicRoughness?.roughnessFactor??.5,o={baseColorFactor:n,metallicFactor:l,roughnessFactor:a,setBaseColorFactor:u=>{let h=[u[0],u[1],u[2],u[3]??1];o.baseColorFactor=h,t.pbrMetallicRoughness&&(t.pbrMetallicRoughness.baseColorFactor=h);for(let c of i)c.baseColor=h;this.render()},setMetallicFactor:u=>{o.metallicFactor=u,t.pbrMetallicRoughness&&(t.pbrMetallicRoughness.metallicFactor=u);for(let h of i)h.metallic=u;this.render()},setRoughnessFactor:u=>{o.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:o}})}playAnimation(e){if(this.animations.length!==0){if(e){let t=this.animations.find(r=>r.name===e);t&&(this.currentClip=t)}else this.currentClip||(this.currentClip=this.animations[0]);this.isPlayingAnimation=!0}}pauseAnimation(){this.isPlayingAnimation=!1}getAvailableAnimations(){return this.animations.map(e=>e.name)}getAvailableVariants(){return[...this.availableVariants]}getVariantName(){return this.activeVariantName}selectVariant(e){let t=this.applyVariantMaterial(e);return t&&this.gl&&this.render(),t}applyVariantMaterial(e){let t=e===null||e==="",r=-1;if(t)this.activeVariantName=null;else{if(r=this.availableVariants.indexOf(e),r<0)return!1;this.activeVariantName=e}let i=this.gltf?.materials;if(!Array.isArray(i))return t;for(let s of this.meshes)for(let n of s.primitives){let l=n.defaultMaterialIndex;if(!t&&Array.isArray(n.variantMappings)){for(let o of n.variantMappings)if(Array.isArray(o.variants)&&o.variants.includes(r)){l=o.material;break}}let a=l!==void 0?i[l]:void 0;n.materialIndex=a?l:void 0,Object.assign(n,fa(a,this.gpuTextures)),this.applyPrimitiveProgram(n,n.materialIndex,a??null)}return!0}applyPrimitiveProgram(e,t,r){if(!this.gl||!e.primitiveDef)return;e.programCache??(e.programCache=new Map);let i=t??-1,s=e.programCache.get(i);s||(s=ca(this.gl,{...e.primitiveDef,material:t},r),e.programCache.set(i,s)),e.customProgram=s.program,e.customUniforms=s.uniforms,e.pluginData&&(e.pluginData.materials=e.isTransmissive?{isTransmissive:!0}:void 0)}setAutoplay(e){this.autoplay=e,e?this.playAnimation(this.animationName||void 0):this.pauseAnimation()}setAnimationName(e){this.animationName=e,(this.isPlayingAnimation||this.autoplay)&&this.playAnimation(e)}evaluateAnimation(e){for(let t of Fe)if(t.evaluateAnimation){t.evaluateAnimation(this,e);return}}setTarget(e,t,r){this.customTarget=[e,t,r],this.gl&&(this.meshes.length>0||this.backdropMeshes.length>0)&&(this.update(0),this.render())}getTarget(){return this.customTarget?[...this.customTarget]:null}setFieldOfView(e){let t=Math.max(10,Math.min(90,e));this.fov=t*Math.PI/180}getFieldOfView(){return this.fov*180/Math.PI}setDistanceMode(e){if(this.distanceMode=e,!this.customDistance){let t=this.clampDistance(this.distanceMode==="absolute"?3:this.bounds.radius*2.5);this.initialDistance=t,this.targetDistance=t,this.currDistance=t,this.gl&&(this.meshes.length>0||this.backdropMeshes.length>0)&&(this.update(0),this.render())}}getDistanceMode(){return this.distanceMode}setOrbitLimits(e){e.minTheta!==void 0&&(this.minTheta=e.minTheta*Math.PI/180),e.maxTheta!==void 0&&(this.maxTheta=e.maxTheta*Math.PI/180),e.minPhi!==void 0&&(this.minPhi=Math.max(-Math.PI*.48,e.minPhi*Math.PI/180)),e.maxPhi!==void 0&&(this.maxPhi=Math.min(Math.PI*.48,e.maxPhi*Math.PI/180)),e.minDistance!==void 0&&(this.minDistanceLimit=e.minDistance),e.maxDistance!==void 0&&(this.maxDistanceLimit=e.maxDistance),this.targetTheta=this.clampTheta(this.targetTheta),this.targetPhi=this.clampPhi(this.targetPhi),this.targetDistance=this.clampDistance(this.targetDistance)}getOrbitLimits(){return{minTheta:isFinite(this.minTheta)?this.minTheta*180/Math.PI:void 0,maxTheta:isFinite(this.maxTheta)?this.maxTheta*180/Math.PI:void 0,minPhi:this.minPhi*180/Math.PI,maxPhi:this.maxPhi*180/Math.PI,minDistance:this.minDistanceLimit!==null?this.minDistanceLimit:void 0,maxDistance:this.maxDistanceLimit!==null?this.maxDistanceLimit:void 0}}clampTheta(e){return Math.max(this.minTheta,Math.min(this.maxTheta,e))}clampPhi(e){return Math.max(this.minPhi,Math.min(this.maxPhi,e))}clampDistance(e){let t=this.minDistanceLimit!==null?this.minDistanceLimit:this.bounds?this.bounds.radius*.5:.1,r=this.maxDistanceLimit!==null?this.maxDistanceLimit:this.bounds?this.bounds.radius*8:100;return Math.max(t,Math.min(r,e))}setCamera(e,t,r,i){e!==void 0&&(this.targetTheta=this.clampTheta(e*Math.PI/180)),t!==void 0&&(this.targetPhi=this.clampPhi(t*Math.PI/180)),r!==void 0&&r>0&&(this.targetDistance=this.clampDistance(r)),i!==void 0&&i>0&&(this.targetDistance=this.clampDistance(this.bounds.radius*2.5/i))}setInitialCamera(e,t,r,i){if(e!==void 0&&(this.initialTheta=this.clampTheta(e*Math.PI/180),this.targetTheta=this.initialTheta,this.currTheta=this.initialTheta),t!==void 0&&(this.initialPhi=this.clampPhi(t*Math.PI/180),this.targetPhi=this.initialPhi,this.currPhi=this.initialPhi),r!==void 0&&r>0){let s=this.clampDistance(r);this.initialDistance=s,this.customDistance=!0,this.targetDistance=s,this.currDistance=s}else if(i!==void 0&&i>0){let s=this.clampDistance(this.bounds.radius*2.5/i);this.initialDistance=s,this.customDistance=!0,this.targetDistance=s,this.currDistance=s}else{this.customDistance=!1;let s=this.clampDistance(this.distanceMode==="absolute"?3:this.bounds.radius*2.5);this.initialDistance=s,this.targetDistance=s,this.currDistance=s}this.gl&&(this.meshes.length>0||this.backdropMeshes.length>0)&&(this.update(0),this.render())}resetCamera(){this.targetTheta=this.clampTheta(this.initialTheta),this.targetPhi=this.clampPhi(this.initialPhi),this.initialDistance!==null?this.targetDistance=this.clampDistance(this.initialDistance):this.targetDistance=this.clampDistance(this.bounds.radius*2.5),this.initialCustomTarget?this.customTarget=[...this.initialCustomTarget]:this.customTarget=null,this.turntableRotation=0,this.updateTurntableMatrix()}projectPointToScreen(e,t){let r=Ee();ke(r,this.projMatrix,this.viewMatrix);let[i,s,n]=e,l=t?t[0]:0,a=t?t[1]:0,o=t?t[2]:0,u=this.modelRootMatrix;u&&(i=u[0]*e[0]+u[4]*e[1]+u[8]*e[2]+u[12],s=u[1]*e[0]+u[5]*e[1]+u[9]*e[2]+u[13],n=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],a=u[1]*t[0]+u[5]*t[1]+u[9]*t[2],o=u[2]*t[0]+u[6]*t[1]+u[10]*t[2]));let h=r[0]*i+r[4]*s+r[8]*n+r[12],c=r[1]*i+r[5]*s+r[9]*n+r[13],f=r[2]*i+r[6]*s+r[10]*n+r[14],p=r[3]*i+r[7]*s+r[11]*n+r[15];if(p<=1e-4)return{x:0,y:0,z:1,visible:!1};let m=h/p,g=c/p,x=f/p,b=this.canvas.getBoundingClientRect(),v=b.width||this.canvas.clientWidth||this.canvas.width||300,d=b.height||this.canvas.clientHeight||this.canvas.height||150,y=(m*.5+.5)*v,M=(-g*.5+.5)*d,T=m>=-1.1&&m<=1.1&&g>=-1.1&&g<=1.1&&x>=-1&&x<=1;if(T&&t){let[V,q,P]=cr(this),R=[i-V,s-q,n-P];l*R[0]+a*R[1]+o*R[2]>.05&&(T=!1)}return{x:y,y:M,z:x,visible:T}}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},s=r.clientX-i.x,n=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(s,n),this.isPanning||r.button===2||r.shiftKey||this.activePointers.size===2){let l=[this.viewMatrix[0],this.viewMatrix[4],this.viewMatrix[8]],a=[this.viewMatrix[1],this.viewMatrix[5],this.viewMatrix[9]],o=this.customTarget?[...this.customTarget]:[...this.bounds.center],u=this.currDistance/Math.max(e.clientHeight||300,1)*1.5;o[0]+=(-s*l[0]+n*a[0])*u,o[1]+=(-s*l[1]+n*a[1])*u,o[2]+=(-s*l[2]+n*a[2])*u,this.customTarget=o}else this.targetTheta=this.clampTheta(this.targetTheta-s*.008),this.targetPhi=this.clampPhi(this.targetPhi+n*.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(),s=Math.floor((r.clientX-i.left)*(e.width/Math.max(i.width,1))),n=Math.floor((r.clientY-i.top)*(e.height/Math.max(i.height,1)));this.performMeshPick(s,n,!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,s)=>{this[s]&&(r.removeEventListener(i,this[s]),this[s]=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(),s=r.width||300,n=r.height||300,l=i.width>0?Math.floor((e-i.left)*(s/i.width)):Math.floor(e),a=i.height>0?Math.floor((t-i.top)*(n/i.height)):Math.floor(t);return this.performMeshPick(l,a,!1)}performMeshPick(e,t,r=!0){if(this.meshes.length===0)return null;let i=this.gl,s=Math.max(1,this.canvas.width||300),n=Math.max(1,this.canvas.height||300);e=this.mapStereoPickX(e,s);let l=Ee();ke(l,this.projMatrix,this.viewMatrix);let a=[],o=Math.max(0,Math.min(s-1,e)),u=Math.max(0,Math.min(n-1,n-1-t));if(this.pickFbo&&i&&!this.xrSessionActive){(this.pickFboWidth!==s||this.pickFboHeight!==n)&&this.resizePickingFbo(s,n),i.bindFramebuffer(36160,this.pickFbo),i.viewport(0,0,s,n),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 T=this.meshes[M];if(T.visible===!1||T.isPluginMesh)continue;let V=M+1,q=(V&255)/255,P=(V>>8&255)/255,R=(V>>16&255)/255;i.uniform4f(this.uPick.uColorId,q,P,R,1),ke(this.modelMatrix,this.modelRootMatrix,T.transform);let C=T.instanceMatrices;if(C&&C.length>=16){let B=C.length>>4,L=Ee();for(let w of T.primitives){i.bindVertexArray(w.vao);for(let ie=0;ie<B;ie++)ke(L,this.modelMatrix,C.subarray(ie*16,ie*16+16)),ke(this.mvpMatrix,l,L),i.uniformMatrix4fv(this.uPick.uMVP,!1,this.mvpMatrix),_r(i,w)}}else{ke(this.mvpMatrix,l,this.modelMatrix),i.uniformMatrix4fv(this.uPick.uMVP,!1,this.mvpMatrix);for(let B of T.primitives)i.bindVertexArray(B.vao),_r(i,B)}}let d=new Uint8Array(4);i.readPixels(o,u,1,1,6408,5121,d),i.bindFramebuffer(36160,null);let y=d[0]+(d[1]<<8)+(d[2]<<16);y>0&&y<=this.meshes.length&&(a=[this.meshes[y-1]])}a.length===0&&(a=this.meshes.filter(d=>d.visible!==!1));let h=null,c=1/0,f=[0,0,0],p=[0,1,0],[m,g,x]=cr(this),b=Ee();for(let d of a){ke(b,this.modelRootMatrix,d.transform);let y=d.instanceMatrices,M=y&&y.length>=16?y.length>>4:1;for(let T=0;T<M;T++){y&&y.length>=16?ke(this.modelMatrix,b,y.subarray(T*16,T*16+16)):this.modelMatrix.set(b),ke(this.mvpMatrix,l,this.modelMatrix);let V=Ee();if(!Ci(V,this.mvpMatrix))continue;let q=(o+.5)/s*2-1,P=(u+.5)/n*2-1,R=[0,0,0],C=[0,0,0];Kn(R,q,P,-1,V),Kn(C,q,P,1,V);let B=C[0]-R[0],L=C[1]-R[1],w=C[2]-R[2],ie=Math.hypot(B,L,w)||1,oe=B/ie,k=L/ie,J=w/ie,z={distance:1/0,point:[0,0,0],normal:[0,1,0]};if((Y=>{for(let le of d.primitives){if(!le.positions)continue;let he=le.positions,$=le.indices,U=Math.floor($?$.length/3:he.length/9);for(let N=0;N<U;N++){let G=$?$[N*3]:N*3,D=$?$[N*3+1]:N*3+1,F=$?$[N*3+2]:N*3+2;Wo(R[0],R[1],R[2],oe,k,J,he[G*3],he[G*3+1],he[G*3+2],he[D*3],he[D*3+1],he[D*3+2],he[F*3],he[F*3+1],he[F*3+2],z,Y)}}})(1e-4),isFinite(z.distance)){let Y=z.point[0],le=z.point[1],he=z.point[2],$=this.modelMatrix,U=$[0]*Y+$[4]*le+$[8]*he+$[12],N=$[1]*Y+$[5]*le+$[9]*he+$[13],G=$[2]*Y+$[6]*le+$[10]*he+$[14],D=U-m,F=N-g,E=G-x,H=Math.hypot(D,F,E);if(H<c){Ye(this.normalMatrix,this.modelMatrix);let ee=this.normalMatrix,ne=z.normal[0],ae=z.normal[1],j=z.normal[2],A=ee[0]*ne+ee[3]*ae+ee[6]*j,S=ee[1]*ne+ee[4]*ae+ee[7]*j,_=ee[2]*ne+ee[5]*ae+ee[8]*j,O=Math.hypot(A,S,_)||1;A/=O,S/=O,_/=O,A*D+S*F+_*E>0&&(A=-A,S=-S,_=-_),h=d,c=Math.round(H*1e3)/1e3,f=[Math.round(U*1e3)/1e3,Math.round(N*1e3)/1e3,Math.round(G*1e3)/1e3],p=[Math.round(A*1e3)/1e3,Math.round(S*1e3)/1e3,Math.round(_*1e3)/1e3]}}}}if(!h)return null;let v={meshIndex:this.meshes.indexOf(h),meshName:h.name,nodeIndex:h.nodeIndex,distance:c,hitPoint:f,normal:p,screenX:e,screenY:t};if(r){for(let d of Fe)d.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,s=i?e-r:e,n=i?Math.max(1,t-r):r,l=(s+.5)/n*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);Ri(this.projMatrix,this.fov,e,.1,t);let r=this.customTarget||this.bounds.center;Pr(this.viewMatrix,cr(this),r,[0,1,0]),ke(this.mvpMatrix,this.projMatrix,this.viewMatrix),Ye(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 Fe)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 Fe)t.onUpdate?.(this,e)}start(){if(this.animFrameId!==null)return;this.lastTime=typeof performance<"u"?performance.now():Date.now();let e=t=>{if(this.animFrameId===null)return;let r=Math.min(Math.max((t-this.lastTime)/1e3,0),.1);if(this.lastTime=t,this.isVisible&&!this.xrSessionActive)try{this.resize(),this.update(r),this.render()}catch(i){this.reportRenderError(i)}this.animFrameId!==null&&(this.animFrameId=requestAnimationFrame(e))};this.animFrameId=requestAnimationFrame(e)}stop(){this.animFrameId!==null&&(cancelAnimationFrame(this.animFrameId),this.animFrameId=null)}setAutoRotate(e){this.autoRotate=e}getAutoRotate(){return this.autoRotate}setAutoRotateSpeed(e){this.autoRotateSpeed=e}getAutoRotateSpeed(){return this.autoRotateSpeed}setAutoRotateDelay(e){this.autoRotateDelay=Math.max(0,Number(e)||0)}getAutoRotateDelay(){return this.autoRotateDelay}resetTurntableRotation(e=0){this.turntableRotation=Number(e)||0,this.updateTurntableMatrix(),this.render()}updateTurntableMatrix(){let e=Math.cos(this.turntableRotation),t=Math.sin(this.turntableRotation),r=this.bounds.center[0],i=this.bounds.center[2],s=this.modelRootMatrix;s[0]=e,s[1]=0,s[2]=-t,s[3]=0,s[4]=0,s[5]=1,s[6]=0,s[7]=0,s[8]=t,s[9]=0,s[10]=e,s[11]=0,s[12]=r-(e*r+t*i),s[13]=0,s[14]=i-(-t*r+e*i),s[15]=1}setVisible(e){this.isVisible=e}update(e){for(let n of Fe)n.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 n of Fe)n.onCameraChange?.(this,this.container)}this.currTheta+=(this.targetTheta-this.currTheta)*.12,this.currPhi+=(this.targetPhi-this.currPhi)*.12,this.currDistance+=(this.targetDistance-this.currDistance)*.12,this.syncCameraMatrices();let r=Math.round((this.currTheta*180/Math.PI%360+360)%360),i=Math.round(this.currPhi*180/Math.PI),s=Math.round(this.bounds.radius*2.5/this.currDistance*100)/100;if(Math.abs(r-this.lastReportedTheta)>=1||Math.abs(i-this.lastReportedPhi)>=1||Math.abs(s-this.lastReportedZoom)>=.02){this.lastReportedTheta=r,this.lastReportedPhi=i,this.lastReportedZoom=s;let n={theta:r,phi:i,zoom:s,distance:Math.round(this.currDistance*100)/100};this.opts.onCameraChange&&this.opts.onCameraChange(n),typeof CustomEvent<"u"&&typeof this.container.dispatchEvent=="function"&&this.container.dispatchEvent(new CustomEvent("cameraChange",{bubbles:!0,detail:n}))}}renderXRView(e,t,r,i,s=!0,n=0){this.onBeforeRenderXRView&&this.onBeforeRenderXRView(e);let l=e?.transform?.inverse?.matrix||this.viewMatrix,a=e?.projectionMatrix||this.projMatrix,o=e?.transform?.position,u=o?[o.x,o.y,o.z]:[0,1.6,0];t?this.modelRootMatrix.set(t):r&&t&&this.modelRootMatrix.set(t),this.render({viewMatrix:l,projMatrix:a,eyePos:u,viewport:i,eye:e?.eye||"none",clear:n>0?!1:e?.eye!=="right",isAR:s})}render(e){if(this.contextLost)return;if(!e&&this.stereoSBS){let v=Math.max(2,this.canvas.width||2),d=Math.max(1,this.canvas.height||1),y=Math.max(1,Math.floor(v*.5)),M=Math.max(1,v-y),T=this.backdropMeshes.length>0?Math.max(this.bounds.radius*20,120):Math.max(this.bounds.radius*20,10),V=this.customTarget||this.bounds.center,[q,P,R]=cr(this),C=Math.cos(this.currTheta),B=-Math.sin(this.currTheta),L=.032,w=Ee(),ie=Ee(),oe=[q-C*L,P,R-B*L],k=[V[0]-C*L*.25,V[1],V[2]-B*L*.25];Ri(w,this.fov,y/d,.1,T),Pr(ie,oe,k,[0,1,0]);let J=Ee(),z=Ee(),Y=[q+C*L,P,R+B*L],le=[V[0]+C*L*.25,V[1],V[2]+B*L*.25];Ri(J,this.fov,M/d,.1,T),Pr(z,Y,le,[0,1,0]),this.render({viewMatrix:ie,projMatrix:w,eyePos:oe,viewport:[0,0,y,d],eye:"left",clear:!0,isAR:!1}),this.render({viewMatrix:z,projMatrix:J,eyePos:Y,viewport:[y,0,M,d],eye:"right",clear:!1,isAR:!1}),this.gl.viewport(0,0,v,d);return}let t=this.gl,r=0,i=0,s=this.canvas.width,n=this.canvas.height;e?.viewport?(r=e.viewport[0],i=e.viewport[1],s=e.viewport[2],n=e.viewport[3],t.viewport(r,i,s,n)):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=Ee(),a=e?.viewMatrix??this.viewMatrix;this.activeViewMatrix=a,ke(l,e?.projMatrix??this.projMatrix,a);let o=Se().xrDepthShader,u=al(this.toneMapping),[h,c,f]=e?e.eyePos:cr(this);for(let v of Fe)v.onBeforeDrawScene?.(this,t,l,[h,c,f],u);let p=e?.isAR?0:this.backdropMeshes.length;if(this.meshes.length===0&&p===0)return;let m=e?.eye||"none",g=!1,x=p>0?[...this.backdropMeshes,...this.meshes]:this.meshes,b=v=>{for(let d=0;d<x.length;d++){let y=x[d];if(y.visible===!1)continue;let M=this.selectedMeshName!==""&&y.name===this.selectedMeshName;d<p||y.worldSpace===!0||y.name==="__xr_reticle__"?this.modelMatrix.set(y.transform):ke(this.modelMatrix,this.modelRootMatrix,y.transform),ke(this.mvpMatrix,l,this.modelMatrix),Ye(y.normalMatrix,this.modelMatrix);let T=y.extras?.xr?.stereo||y.userData?.xr?.stereo,V=0,q=0,P=1,R=1;T==="sbs"?(P=.5,V=m==="right"?.5:0):T==="ou"&&(R=.5,q=m==="right"?.5:0);for(let C of y.primitives){let B=!!C.isTransmissive;if(!v&&B){g=!0;continue}if(v&&!B)continue;let L=C.customProgram||this.renderProg,w=C.customUniforms||this.uRender;t.useProgram(L),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,c,f),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,V,q,P,R),w.uViewportSize&&t.uniform2f(w.uViewportSize,Math.max(1,s),Math.max(1,n)),o?.bind(t,w,this.xrDepthState,a,[r,i,Math.max(1,s),Math.max(1,n)]),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 Fe)oe.onBeforeDrawPrimitive?.(t,L,C,y,this.worldMatrices||[],this.gltf);t.uniform4fv(w.uBaseColor,C.baseColor),t.uniform1f(w.uMetallic,C.metallic),t.uniform1f(w.uRoughness,C.roughness),w.uClearcoat&&t.uniform2f(w.uClearcoat,C.clearcoat??0,C.clearcoatRoughness??.04),C.texture?(t.activeTexture(33984),t.bindTexture(3553,C.texture),t.uniform1i(w.uBaseColorTexture,0),t.uniform1i(w.uHasTexture,1)):t.uniform1i(w.uHasTexture,0),C.metallicRoughnessTexture?(t.activeTexture(33985),t.bindTexture(3553,C.metallicRoughnessTexture),t.uniform1i(w.uMetallicRoughnessTexture,1),t.uniform1i(w.uHasMetallicRoughnessTexture,1)):t.uniform1i(w.uHasMetallicRoughnessTexture,0),C.normalTexture?(t.activeTexture(33986),t.bindTexture(3553,C.normalTexture),t.uniform1i(w.uNormalTexture,2),t.uniform1i(w.uHasNormalTexture,1),t.uniform1f(w.uNormalScale,C.normalScale)):t.uniform1i(w.uHasNormalTexture,0),C.occlusionTexture?(t.activeTexture(33987),t.bindTexture(3553,C.occlusionTexture),t.uniform1i(w.uOcclusionTexture,3),t.uniform1i(w.uHasOcclusionTexture,1),t.uniform1f(w.uOcclusionStrength,C.occlusionStrength)):t.uniform1i(w.uHasOcclusionTexture,0),t.bindVertexArray(C.vao);let ie=y.instanceMatrices;if(C.instanceCount!==void 0)t.drawElementsInstanced(4,C.indexCount,C.indexType,0,C.instanceCount);else if(ie&&ie.length>=16&&C.instanced&&w.uInstanced&&w.uViewProj){let oe=ie.length>>4;t.uniform1i(w.uInstanced,1),t.uniformMatrix4fv(w.uViewProj,!1,l),C.indices?t.drawElementsInstanced(4,C.indexCount,C.indexType,0,oe):t.drawArraysInstanced(4,0,C.indexCount,oe),t.uniform1i(w.uInstanced,0)}else if(ie&&ie.length>=16){let oe=ie.length>>4,k=y.instanceColors,J=Ee(),z=new Float32Array(9),Y=[C.baseColor[0],C.baseColor[1],C.baseColor[2],C.baseColor[3]];for(let le=0;le<oe;le++)ke(J,this.modelMatrix,ie.subarray(le*16,le*16+16)),ke(this.mvpMatrix,l,J),Ye(z,J),t.uniformMatrix4fv(w.uMVP,!1,this.mvpMatrix),t.uniformMatrix4fv(w.uModel,!1,J),t.uniformMatrix3fv(w.uNormalMatrix,!1,z),k&&(Y[0]=C.baseColor[0]*k[le*3],Y[1]=C.baseColor[1]*k[le*3+1],Y[2]=C.baseColor[2]*k[le*3+2],Y[3]=C.baseColor[3],t.uniform4fv(w.uBaseColor,Y)),_r(t,C)}else _r(t,C)}}};if(b(!1),g){for(let v of Fe)v.onBeforeTransmissivePass?.(t,this);b(!0)}for(let v of Fe)v.onAfterRender?.(t,this,l,e?.eye??"none",[r,i,s,n],e?.projMatrix??this.projMatrix)}disposeMeshListGpuResources(e,t){pa(this.gl,e,t)}disposeMeshGpuResources(){this.disposeMeshListGpuResources(this.meshes,this.gpuTextures),this.meshes=[],this.gpuTextures=[],this.availableVariants=[]}disposeGpuResources(){let e=this.gl;this.disposeMeshGpuResources(),this.disposeMeshListGpuResources(this.backdropMeshes),this.backdropMeshes=[];for(let t of Fe)t.onDestroy?.(e,this);this.environmentTexture&&(e.deleteTexture(this.environmentTexture),this.environmentTexture=null),this.renderProg&&e.deleteProgram(this.renderProg),this.pickProg&&e.deleteProgram(this.pickProg),this.pickFbo&&e.deleteFramebuffer(this.pickFbo),this.pickTexture&&e.deleteTexture(this.pickTexture),this.pickDepth&&e.deleteRenderbuffer(this.pickDepth),this.pickFbo=null,this.pickTexture=null,this.pickDepth=null}dispose(){this.stop(),this.teardownEvents(),this.disposeGpuResources()}destroy(){this.dispose()}};Ze.registerPlugin=He,Ze.getRegisteredPlugins=Hn;function bl(e){return e+3&-4}var ve=(e,t)=>typeof e=="number"&&Number.isFinite(e)?e:t;function ga(e,t){let r=t,i=1;for(;e.has(r);)r=`${t}_${i++}`;return e.add(r),r}function ya(e,t=0){let[r,i,s,,n,l,a,,o,u,h,,c,f,p]=Array.from({length:15},(z,Y)=>ve(e[t+Y],Y%5===0?1:0)),m=Math.hypot(r,i,s),g=Math.hypot(n,l,a),x=Math.hypot(o,u,h);r*(l*h-u*a)-n*(i*h-u*s)+o*(i*a-l*s)<0&&(m=-m);let b=Math.abs(m)>1e-8?1/m:0,v=Math.abs(g)>1e-8?1/g:0,d=Math.abs(x)>1e-8?1/x:0,y=r*b,M=i*b,T=s*b,V=n*v,q=l*v,P=a*v,R=o*d,C=u*d,B=h*d,L=y+q+B,w=0,ie=0,oe=0,k=1;if(L>0){let z=.5/Math.sqrt(L+1);k=.25/z,w=(P-C)*z,ie=(R-T)*z,oe=(M-V)*z}else if(y>q&&y>B){let z=2*Math.sqrt(Math.max(0,1+y-q-B));z>1e-8&&(k=(P-C)/z,w=.25*z,ie=(V+M)/z,oe=(R+T)/z)}else if(q>B){let z=2*Math.sqrt(Math.max(0,1+q-y-B));z>1e-8&&(k=(R-T)/z,w=(V+M)/z,ie=.25*z,oe=(P+C)/z)}else{let z=2*Math.sqrt(Math.max(0,1+B-y-q));z>1e-8&&(k=(M-V)/z,w=(R+T)/z,ie=(P+C)/z,oe=.25*z)}let J=Math.hypot(w,ie,oe,k);return J>1e-8&&Number.isFinite(J)?(w/=J,ie/=J,oe/=J,k/=J):(w=0,ie=0,oe=0,k=1),{t:[c,f,p],r:[w,ie,oe,k],s:[m,g,x]}}function xl(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 Pt=(e,t,r,i)=>typeof e=="number"&&Number.isFinite(e)?Math.max(t,Math.min(r,e)):i;function ba(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,s=typeof r.preset=="string"?r.preset:void 0;return!i&&!s?null:{ae:r,src:i,preset:s,volume:Pt(r.volume,0,2,.6),loop:typeof r.loop=="boolean"?r.loop:!0,isGlobal:r.type==="global"||r.positional===!1}}function Zt(e,t){return xa(e,t)[0]}function xa(e,t){e.updateMatrixWorld(!0);let r=[],i=0,s=[],n=[],l=[],a=[],o=new Set,u=[],h=[],c=new Map,f=[],p=[],m=[],g=new Map,x=[],b=[];function v(k){let J=c.get(k);if(J!==void 0)return J;J=h.length,c.set(k,J);let z=k,Y=z.color?.r??.8,le=z.color?.g??.8,he=z.color?.b??.8,$=z.opacity??1,U={baseColorFactor:[Y,le,he,$],metallicFactor:z.metalness??0,roughnessFactor:z.roughness??.5},N={};if(z.map){let F="";typeof z.map=="string"?F=z.map:typeof z.map.source=="string"?F=z.map.source:typeof z.map.image=="string"&&(F=z.map.image);let E=F.trim(),H=E&&!/[\x00-\x1f\x7f\\]|\.\./.test(E)&&(/^data:image\/(png|jpeg|jpg|webp|ktx2|avif)(;|,)/i.test(E)||!E.startsWith("//")&&!/^[a-z][a-z0-9+.-]*:/i.test(E))?E:null;if(H){let ne=g.get(H);if(ne===void 0){let ae=f.length;f.push({uri:H}),p.length===0&&p.push({magFilter:9729,minFilter:9987,wrapS:10497,wrapT:10497}),ne=m.length,m.push({sampler:0,source:ae}),g.set(H,ne)}U.baseColorTexture={index:ne}}let ee=z.map.avgColor;Array.isArray(ee)&&ee.length>=3&&(N.avgColor=[ee[0],ee[1],ee[2]])}let G={name:z.name||"",pbrMetallicRoughness:U,doubleSided:z.side===2||!!z.doubleSided,...Object.keys(N).length>0?{extras:N}:{}};if(z.emissive&&(z.emissive.r>0||z.emissive.g>0||z.emissive.b>0)){let F=z.emissiveIntensity??1;G.emissiveFactor=[z.emissive.r*F,z.emissive.g*F,z.emissive.b*F]}let D={};return z.clearcoat&&z.clearcoat>0&&(D.KHR_materials_clearcoat={clearcoatFactor:z.clearcoat,clearcoatRoughnessFactor:z.clearcoatRoughness||0}),z.sheen&&z.sheen>0&&(D.KHR_materials_sheen={sheenColorFactor:z.sheenColor?[z.sheenColor.r,z.sheenColor.g,z.sheenColor.b]:[1,1,1],sheenRoughnessFactor:z.sheenRoughness||0}),z.transmission&&z.transmission>0&&(D.KHR_materials_transmission={transmissionFactor:z.transmission}),z.thickness&&z.thickness>0&&(D.KHR_materials_volume={thicknessFactor:z.thickness,attenuationDistance:z.attenuationDistance??1/0,attenuationColor:z.attenuationColor?[z.attenuationColor.r,z.attenuationColor.g,z.attenuationColor.b]:[1,1,1]}),z.ior!==void 0&&z.ior!==1.5&&(D.KHR_materials_ior={ior:z.ior}),z.dispersion&&z.dispersion>0&&(D.KHR_materials_dispersion={dispersion:z.dispersion}),z.iridescence&&z.iridescence>0&&(D.KHR_materials_iridescence={iridescenceFactor:z.iridescence,iridescenceIor:z.iridescenceIOR??1.3}),Object.keys(D).length>0&&(G.extensions=D),h.push(G),J}function d(k,J){let z=new Uint8Array(k.buffer,k.byteOffset,k.byteLength),Y=bl(z.byteLength),le=new Uint8Array(Y);le.set(z),r.push(le);let he=s.length;return s.push({buffer:0,byteOffset:i,byteLength:z.byteLength,target:J}),i+=Y,he}function y(k,J,z,Y,le,he,$){let U=d(k,z),N=n.length,G={bufferView:U,byteOffset:0,componentType:Y,count:le,type:J};return he&&(G.min=he),$&&(G.max=$),n.push(G),N}e.traverse(k=>{if(k.isLight||k.color&&k.intensity!==void 0){let J=k.matrixWorld?.elements,z=ve(J?J[12]:k.position?.x,0),Y=ve(J?J[13]:k.position?.y,0),le=ve(J?J[14]:k.position?.z,0),he=k.target,$=he?.parent?he?.matrixWorld?.elements:void 0,U=ve($?$[12]:he?.position?.x,0),N=ve($?$[13]:he?.position?.y,0),G=ve($?$[14]:he?.position?.z,0),D=U-z,F=N-Y,E=G-le,H=Math.hypot(D,F,E),ee=Math.max(.01,Math.min(Math.PI/2,ve(k.angle,Math.PI/3))),ne=Math.max(0,Math.min(1,ve(k.penumbra,0)));b.push({type:k.type,color:[k.color.r,k.color.g,k.color.b],intensity:k.intensity,position:[z,Y,le],...k.type==="spot"?{direction:H>1e-6?[D/H,F/H,E/H]:[0,-1,0],outerConeAngle:ee,innerConeAngle:Math.max(0,ee*(1-ne)),range:Math.max(0,ve(k.distance,0))}:k.type==="point"?{range:Math.max(0,ve(k.distance,0))}:{}})}});let M=[],T=new Set([e]),V=[];if(Array.isArray(e.children))for(let k=e.children.length-1;k>=0;k--)V.push({obj:e.children[k],parentKids:M});for(;V.length>0;){let{obj:k,parentKids:J}=V.pop();if(!k||typeof k!="object"||T.has(k))continue;T.add(k),k._bakeAuthorGeometry?.(),Se().materializeDeclarativeGeometry?.(k);let z=!!(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)),Y={name:k.name||(z?`Node_${a.length}`:"")},le=ve(k.position?.x,0),he=ve(k.position?.y,0),$=ve(k.position?.z,0),U=ve(k.quaternion?.x,0),N=ve(k.quaternion?.y,0),G=ve(k.quaternion?.z,0),D=ve(k.quaternion?.w,1),F=ve(k.scale?.x,1),E=ve(k.scale?.y,1),H=ve(k.scale?.z,1);if((le||he||$)&&(Y.translation=[le,he,$]),(U||N||G||D!==1)&&(Y.rotation=[U,N,G,D]),(F!==1||E!==1||H!==1)&&(Y.scale=[F,E,H]),k.visible===!1&&(Y.extensions={...Y.extensions||{},KHR_node_visibility:{visible:!1}},o.add("KHR_node_visibility")),k.userData&&Object.keys(k.userData).length>0&&(Y.extras=JSON.parse(JSON.stringify(k.userData,(ae,j)=>{if(!(ae==="__proto__"||ae==="prototype"||ae==="constructor"))return typeof j=="function"?void 0:j})),k.userData.xr)){let ae=xl(k.userData.xr);Y.extensions={...Y.extensions||{},MOZ_hubs_components:ae,ANDROID_xr_scenecore:ae},Se().xrTraitSerializer?.gltfNode(Y,k.userData.xr),o.add("MOZ_hubs_components").add("ANDROID_xr_scenecore")}if(k.geometry){let ae=k.geometry,j=ae.attributes.position;if(j&&j.count>0){let A=[1/0,1/0,1/0],S=[-1/0,-1/0,-1/0];for(let K=0;K<j.count;K++){let Z=j.getX(K),X=j.getY(K),re=j.getZ(K);Z<A[0]&&(A[0]=Z),Z>S[0]&&(S[0]=Z),X<A[1]&&(A[1]=X),X>S[1]&&(S[1]=X),re<A[2]&&(A[2]=re),re>S[2]&&(S[2]=re)}let _={attributes:{POSITION:y(j.array,"VEC3",34962,5126,j.count,A,S)}};if(ae.attributes.normal&&(_.attributes.NORMAL=y(ae.attributes.normal.array,"VEC3",34962,5126,ae.attributes.normal.count)),ae.attributes.uv&&(_.attributes.TEXCOORD_0=y(ae.attributes.uv.array,"VEC2",34962,5126,ae.attributes.uv.count)),ae.index){let K=ae.index.array instanceof Uint32Array;_.indices=y(ae.index.array,"SCALAR",34963,K?5125:5123,ae.index.count)}let O=Array.isArray(k.material)?k.material[0]:k.material;O&&(_.material=v(O));let I=k.userData?.variants;if(I&&typeof I=="object"){let K=new Map;for(let Z of Object.keys(I)){if(!Z||Z==="__proto__"||Z==="constructor"||Z==="prototype")continue;let X=I[Z];if(!X||typeof X!="object")continue;let re=x.indexOf(Z);if(re===-1&&x.length<256&&(re=x.length,x.push(Z)),re===-1)continue;let se=v(X),te=K.get(se);te||(te=[],K.set(se,te)),te.push(re)}if(K.size>0){let Z=[];for(let[X,re]of K.entries())Z.push({material:X,variants:re});_.extensions={..._.extensions||{},KHR_materials_variants:{mappings:Z}},o.add("KHR_materials_variants")}}let W=k;if(W.isInstancedMesh&&typeof W.count=="number"&&W.count>0&&W.instanceMatrix?.array){let K=Math.min(1e4,Math.floor(W.count)),Z=W.instanceMatrix.array,X=new Float32Array(K*3),re=new Float32Array(K*4),se=new Float32Array(K*3);for(let ue=0;ue<K;ue++){let{t:ce,r:fe,s:me}=ya(Z,ue*16);X[ue*3]=ce[0],X[ue*3+1]=ce[1],X[ue*3+2]=ce[2],re[ue*4]=fe[0],re[ue*4+1]=fe[1],re[ue*4+2]=fe[2],re[ue*4+3]=fe[3],se[ue*3]=me[0],se[ue*3+1]=me[1],se[ue*3+2]=me[2]}let te={TRANSLATION:y(X,"VEC3",0,5126,K),ROTATION:y(re,"VEC4",0,5126,K),SCALE:y(se,"VEC3",0,5126,K)};if(W.instanceColor?.array&&W.instanceColor.array.length>=K*3){let ue=new Float32Array(W.instanceColor.array.subarray(0,K*3));te._COLOR_0=y(ue,"VEC3",0,5126,K)}Y.extensions={...Y.extensions||{},EXT_mesh_gpu_instancing:{attributes:te}},o.add("EXT_mesh_gpu_instancing")}let Q=l.length;l.push({primitives:[_],name:k.name,...Y.extras?{extras:Y.extras}:{}}),Y.mesh=Q}}let ee=a.length;a.push(Y),u.push(k),J.push(ee);let ne=k.children;if(Array.isArray(ne)&&ne.length>0){let ae=[];Y.children=ae;for(let j=ne.length-1;j>=0;j--)V.push({obj:ne[j],parentKids:ae})}}for(let k=0;k<a.length;k++){let J=a[k];J.children&&J.children.length===0?delete J.children:J.children&&J.children.length>0&&(J.extras?.xr?.lod||J.extensions?.ANDROID_xr_scenecore?.lod||u[k]?.isLOD)&&(J.extensions={...J.extensions||{},MSFT_lod:{ids:[...J.children]}},o.add("MSFT_lod"))}let q=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),P=[];if(typeof q=="function"&&u.length>0){let k=t?.duration??4,J=t?.fps??15,z=Math.max(2,Math.round(k*J)+1),Y=new Float32Array(z),le=u.map(E=>[ve(E.position?.x,0),ve(E.position?.y,0),ve(E.position?.z,0),ve(E.quaternion?.x,0),ve(E.quaternion?.y,0),ve(E.quaternion?.z,0),ve(E.quaternion?.w,1),ve(E.scale?.x,1),ve(E.scale?.y,1),ve(E.scale?.z,1)]),he=u.map(()=>new Float32Array(z*3)),$=u.map(()=>new Float32Array(z*4)),U=u.map(()=>new Float32Array(z*3));for(let E=0;E<z;E++){let H=E/(z-1)*k;Y[E]=H;try{q(H)}catch{}for(let ee=0;ee<u.length;ee++){let ne=u[ee];he[ee][E*3]=ve(ne.position?.x,0),he[ee][E*3+1]=ve(ne.position?.y,0),he[ee][E*3+2]=ve(ne.position?.z,0);let ae=ve(ne.quaternion?.x,0),j=ve(ne.quaternion?.y,0),A=ve(ne.quaternion?.z,0),S=ve(ne.quaternion?.w,1),_=Math.hypot(ae,j,A,S)||1;if(ae/=_,j/=_,A/=_,S/=_,E>0){let O=(E-1)*4,I=$[ee];I[O]*ae+I[O+1]*j+I[O+2]*A+I[O+3]*S<0&&(ae=-ae,j=-j,A=-A,S=-S)}$[ee][E*4]=ae,$[ee][E*4+1]=j,$[ee][E*4+2]=A,$[ee][E*4+3]=S,U[ee][E*3]=ve(ne.scale?.x,1),U[ee][E*3+1]=ve(ne.scale?.y,1),U[ee][E*3+2]=ve(ne.scale?.z,1)}}for(let E=0;E<u.length;E++){let H=u[E],ee=le[E];H.position?.set(ee[0],ee[1],ee[2]),H.quaternion?.set(ee[3],ee[4],ee[5],ee[6]),H.scale?.set(ee[7],ee[8],ee[9])}e.updateMatrixWorld(!0);let N=null,G=()=>(N===null&&(N=y(Y,"SCALAR",0,5126,z,[0],[k])),N),D=[],F=[];for(let E=0;E<u.length;E++){let H=le[E],ee=(ae,j,A)=>ae.some((S,_)=>Math.abs(S-H[A+_%j])>1e-4),ne=(ae,j,A,S)=>{ae&&F.push({sampler:D.push({input:G(),interpolation:"LINEAR",output:y(j,A,0,5126,z)})-1,target:{node:E,path:S}})};ne(ee(he[E],3,0),he[E],"VEC3","translation"),ne(ee($[E],4,3),$[E],"VEC4","rotation"),ne(ee(U[E],3,7),U[E],"VEC3","scale")}F.length>0&&P.push({name:"ProceduralLoop",samplers:D,channels:F})}let R=jo(a,l,e.userData),C=[],B=[],L=[];for(let k=0;k<a.length;k++){let J=a[k],z=ba(J.extras?.xr);if(!z)continue;let{ae:Y,src:le,preset:he,volume:$,loop:U,isGlobal:N}=z,G=J.name||`Node_${k}`,D=B.length;B.push({name:`${G}_source`,gain:$,loop:U,autoPlay:typeof Y.autoplay=="boolean"?Y.autoplay:!0,...le!==void 0?{audio:C.push({uri:le})-1}:{},...he?{extras:{preset:he,pitch:Pt(Y.pitch,.25,4,1)}}:{}});let F=L.length,E=Pt(Y.refDistance,.05,100,1),H=Pt(Y.coneInnerAngle,0,360,360),ee=Pt(Y.coneOuterAngle,H,360,360);L.push({name:`${G}_emitter`,type:N?"global":"positional",gain:$,sources:[D],...N?{}:{positional:{distanceModel:Y.distanceModel==="linear"||Y.distanceModel==="exponential"?Y.distanceModel:"inverse",refDistance:E,maxDistance:Pt(Y.maxDistance,E,500,Math.max(E,25)),rolloffFactor:Pt(Y.rolloffFactor,0,10,1),coneInnerAngle:+(H*Math.PI/180).toFixed(6),coneOuterAngle:+(ee*Math.PI/180).toFixed(6),coneOuterGain:Pt(Y.coneOuterGain,0,1,0)}}}),J.extensions={...J.extensions||{},KHR_audio_emitter:{emitter:F}},o.add("KHR_audio_emitter")}let w={asset:{version:"2.0",generator:"ThreeLiveConvert",extras:{environmentIntensity:e.environmentIntensity}},scenes:[{nodes:M}],scene:0,nodes:a,meshes:l,materials:h,...f.length>0?{images:f}:{},...p.length>0?{samplers:p}:{},...m.length>0?{textures:m}:{},accessors:n,bufferViews:s,buffers:[{byteLength:i}],...P.length>0?{animations:P}:{},...R||o.size>0?{extensionsUsed:[...R?["KHR_interactivity"]:[],...o]}:{},...R||x.length>0||L.length>0?{extensions:{...R?{KHR_interactivity:R}:{},...x.length>0?{KHR_materials_variants:{variants:x.map(k=>({name:k}))}}:{},...L.length>0?{KHR_audio_emitter:{...C.length>0?{audio:C}:{},sources:B,emitters:L}}:{}}}:{}},ie=new Uint8Array(i),oe=0;for(let k of r)ie.set(k,oe),oe+=k.byteLength;return[{gltf:w,bin:ie.buffer,lights:b,environmentIntensity:e.environmentIntensity},u]}function Gi(e){return new TextEncoder().encode(e)}function mr(e,t){let{gltf:r,bin:i}=Zt(e,t),s=JSON.stringify(r),n=Gi(s),l=(4-n.byteLength%4)%4,a=n.byteLength+l,o=20+a+8+i.byteLength,u=new Uint8Array(o),h=new DataView(u.buffer);h.setUint32(0,1179937895,!0),h.setUint32(4,2,!0),h.setUint32(8,o,!0),h.setUint32(12,a,!0),h.setUint32(16,1313821514,!0),u.set(n,20);for(let f=0;f<l;f++)u[20+n.byteLength+f]=32;let c=20+a;return h.setUint32(c,i.byteLength,!0),h.setUint32(c+4,5130562,!0),u.set(new Uint8Array(i),c+8),u}function vl(e,t){let[r,i]=xa(e,t);return Hi(r,i)}function Hi(e,t){let r=[],i=e.gltf,s=Se().decoders.get("meshopt");s&&typeof s.decodeBufferViews=="function"&&s.decodeBufferViews(i,e);let n=e.bin,l=n instanceof ArrayBuffer?n:n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength),a=i.accessors||[],o=i.bufferViews||[],u=i.materials||[],h=i.meshes||[],c=i.nodes||[],f=new Set,p=u.map((x,b)=>ga(f,Dr(x?.name,`Material_${b}`)));function m(x){let b=a[x];if(!b)throw new Error(`Accessor ${x} not found`);let v=o[b.bufferView||0],d=(v.byteOffset||0)+(b.byteOffset||0),y=v.byteLength||0;return{acc:b,buffer:l.slice(d,d+y)}}function g(x,b,v,d){let y=[],M=h[x];if(!M)return y;let T=M.primitives||[];for(let V=0;V<T.length;V++){let q=T[V],P=q.attributes?.POSITION;if(P===void 0)continue;let{acc:R,buffer:C}=m(P),B=new Float32Array(C,0,R.count*3),L,w=q.attributes?.NORMAL;if(w!==void 0){let{acc:D,buffer:F}=m(w),E=new Float32Array(F,0,D.count*3);L=new Float32Array(E.length);for(let H=0;H<D.count;H++){let ee=E[H*3],ne=E[H*3+1],ae=E[H*3+2],j=Math.hypot(ee,ne,ae)||1;L[H*3]=ee/j,L[H*3+1]=ne/j,L[H*3+2]=ae/j}}let ie,oe=q.attributes?.TEXCOORD_0;if(oe!==void 0){let{acc:D,buffer:F}=m(oe);ie=new Float32Array(F,0,D.count*2)}let k;if(q.indices!==void 0){let{acc:D,buffer:F}=m(q.indices);k=D.componentType===5125?new Uint32Array(F,0,D.count):new Uint16Array(F,0,D.count);let E=R.count;for(let H of k)if(H>=E)throw new Error(`SecurityError: Index buffer value (${H}) out of vertex bounds [0, ${E}).`)}else{let D=R.count;k=D>65535?new Uint32Array(D):new Uint16Array(D);for(let F=0;F<D;F++)k[F]=F}let J="DefaultMaterial",z=[.8,.8,.8],Y=.5,le=0,he=0,$=0,U=1.5,N=1,G=[0,0,0];if(q.material!==void 0&&u[q.material]){let D=u[q.material];J=p[q.material]||`Material_${q.material}`;let F=D.pbrMetallicRoughness||{},E=(ae,j)=>Array.isArray(ae)&&ae.length>=3?[ae[0],ae[1],ae[2]]:j;z=E(F.baseColorFactor,[1,1,1]);let H=D.extras?.avgColor;Array.isArray(H)&&H.length>=3&&(z=[z[0]*H[0],z[1]*H[1],z[2]*H[2]]);let ee=Array.isArray(F.baseColorFactor)&&typeof F.baseColorFactor[3]=="number"?F.baseColorFactor[3]:1;typeof F.roughnessFactor=="number"&&(Y=F.roughnessFactor),typeof F.metallicFactor=="number"&&(le=F.metallicFactor),G=E(D.emissiveFactor,[0,0,0]);let ne=D.extensions||{};ne.KHR_materials_clearcoat&&(he=ne.KHR_materials_clearcoat.clearcoatFactor??0,$=ne.KHR_materials_clearcoat.clearcoatRoughnessFactor??0),typeof ne.KHR_materials_ior?.ior=="number"&&(U=ne.KHR_materials_ior.ior),N=ee*(1-(ne.KHR_materials_transmission?.transmissionFactor??0))}y.push({name:T.length>1?`${b}_p${V}`:b,positions:B,indices:k,normals:L,uvs:ie,materialName:J,color:z,roughness:Y,metallic:le,clearcoat:he,clearcoatRoughness:$,ior:U,opacity:N,emissiveColor:G,xrTraits:v||M.extras?.xr,...d?{invisible:!0}:{}})}return y}if(c.length>0){let x=new Float32Array(0),b=new Uint16Array(0),v=(B,L)=>{if(B===void 0)return null;let{acc:w,buffer:ie}=m(B);return new Float32Array(ie,0,w.count*L)},d=(B,L)=>Array.isArray(B)&&B.length>=3?[ve(B[0],L),ve(B[1],L),ve(B[2],L)]:[L,L,L],y=(B,L,w)=>B&&B.length>=(L+1)*3?[B[L*3],B[L*3+1],B[L*3+2]]:w,M=(B,L,w)=>B&&B.length>=(L+1)*4?[B[L*4],B[L*4+1],B[L*4+2],B[L*4+3]]:w,T=new Map,V=i.animations?.[0];if(V&&Array.isArray(V.channels)&&Array.isArray(V.samplers))for(let B of V.channels){let L=V.samplers[B?.sampler],w=B?.target?.node,ie=B?.target?.path;if(!L||typeof w!="number"||L.input===void 0)continue;let oe=T.get(w);oe||(oe={input:L.input},T.set(w,oe)),ie==="translation"?oe.t=L.output:ie==="rotation"?oe.r=L.output:ie==="scale"&&(oe.s=L.output)}let q=i.scenes?.[i.scene??0]?.nodes??[];if(!Array.isArray(q)||q.length===0){let B=new Set;for(let L of c)if(Array.isArray(L?.children))for(let w of L.children)B.add(w);q=[];for(let L=0;L<c.length;L++)B.has(L)||q.push(L);q.length===0&&(q=[0])}let P=new Set,R=[],C=(B,L)=>{if(Array.isArray(B))for(let w=B.length-1;w>=0;w--)R.push({idx:B[w],out:L})};for(C(q,r);R.length>0;){let{idx:B,out:L}=R.pop();if(typeof B!="number"||B<0||B>=c.length||P.has(B))continue;P.add(B);let w=c[B];if(!w)continue;let ie=[0,0,0],oe=[0,0,0,1],k=[1,1,1];if(Array.isArray(w.matrix)&&w.matrix.length===16){let N=ya(w.matrix);ie=N.t,oe=N.r,k=N.s}else ie=d(w.translation,0),Array.isArray(w.rotation)&&w.rotation.length>=4&&(oe=[ve(w.rotation[0],0),ve(w.rotation[1],0),ve(w.rotation[2],0),ve(w.rotation[3],1)]),k=d(w.scale,1);let J,z=T.get(B);if(z){let N=v(z.input,1);if(N&&N.length>0){let G=v(z.t,3),D=v(z.r,4),F=v(z.s,3),E=Array.from(N),H=[],ee=[],ne=[];for(let ae=0;ae<N.length;ae++)H.push(y(G,ae,ie)),ee.push(M(D,ae,oe)),ne.push(y(F,ae,k));J={times:E,translations:H,rotations:ee,scales:ne}}}let Y=Array.isArray(w.children)?w.children:[],le=typeof w.mesh=="number"&&w.mesh>=0&&w.mesh<h.length,he=t?.[B]?.userData?.xr??w.extras?.xr;if(!le&&Y.length===0&&(w.camera!==void 0||w.extensions?.KHR_lights_punctual||!w.name&&!w.extras&&!he&&!J))continue;let $=(N,G,D)=>({name:N,positions:x,indices:b,isXform:!0,xrTraits:he,timeSamples:J,translation:ie,rotation:oe,scale:k,children:G,...D?{invisible:!0}:{}}),U=w.visible===!1||w.extensions?.KHR_node_visibility?.visible===!1||t?.[B]?.visible===!1;if(le){let N=w.name||h[w.mesh]?.name||`Mesh_${B}`,G=g(w.mesh,N,he,U),D=w.extensions?.EXT_mesh_gpu_instancing?.attributes;if(D&&typeof D=="object"&&G.length>0){let F=v(D.TRANSLATION,3),E=v(D.ROTATION,4),H=v(D.SCALE,3),ee=v(D._COLOR_0,3),ne=Math.min(1e3,F?F.length/3:E?E.length/4:H?H.length/3:0);if(ne>0){let ae=[];for(let j=0;j<ne;j++){let A=y(F,j,[0,0,0]),S=M(E,j,[0,0,0,1]),_=y(H,j,[1,1,1]);for(let O of G){let I=O.color||[.8,.8,.8],W=ee&&ee.length>=(j+1)*3;ae.push({...O,name:`${O.name}_${j}`,materialName:W?`${O.materialName}_inst_${j}`:O.materialName,color:W?[I[0]*ee[j*3],I[1]*ee[j*3+1],I[2]*ee[j*3+2]]:O.color,translation:A,rotation:S,scale:_})}}C(Y,ae),L.push($(N,ae,U));continue}}if(G.length===1)G[0].translation=ie,G[0].rotation=oe,G[0].scale=k,G[0].timeSamples=J,Y.length>0&&(G[0].children=[],C(Y,G[0].children)),L.push(G[0]);else{let F=[...G];C(Y,F),L.push($(N,F,U))}}else{let N=[];C(Y,N),L.push($(w.name||`Group_${B}`,N,U))}}}else for(let x=0;x<h.length;x++){let b=h[x].name||`Mesh_${x}`;r.push(...g(x,b,h[x].extras?.xr))}return r}function Dr(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 ji(e){return String(e??"").replace(/[\x00-\x1f\x7f]/g,"").replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function Be(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 ft=(e,t,r)=>`(${Be(e)}, ${Be(t)}, ${Be(r)})`,va=(e,t,r,i)=>`(${Be(e)}, ${Be(t)}, ${Be(r)}, ${Be(i)})`;function Ma(e){let t=e.length/3,r=new Array(t);for(let i=0;i<t;i++)r[i]=ft(e[i*3],e[i*3+1],e[i*3+2]);return r.join(", ")}function Ml(e,t){let r=new Array(t);for(let i=0;i<t;i++)r[i]=`(${Be(e[i*2])}, ${Be(1-e[i*2+1])})`;return r.join(", ")}function wl(e){return Array.from(e).join(", ")}function Wi(e){let t=new Map,r=0,i=null,s=[...e];for(;s.length>0;){let m=s.pop();if(!m.isXform&&m.positions&&m.positions.length>0){let g=Dr(m.materialName,"DefaultMaterial");t.has(g)||t.set(g,{color:m.color||[.8,.8,.8],roughness:m.roughness??.5,metallic:m.metallic??0,clearcoat:m.clearcoat??0,clearcoatRoughness:m.clearcoatRoughness??0,ior:m.ior??1.5,opacity:m.opacity??1,emissiveColor:m.emissiveColor||[0,0,0]})}if(m.timeSamples&&m.timeSamples.times.length>0){let g=m.timeSamples.times[m.timeSamples.times.length-1];g>r&&(r=g)}if(m.xrTraits?.anchor&&!i&&(i=m.xrTraits.anchor==="vertical"||m.xrTraits.anchor==="wall"?"vertical":"horizontal"),m.children)for(let g=m.children.length-1;g>=0;g--)s.push(m.children[g])}let n="";r>0&&(n=`startTimeCode = 0
|
|
251
|
-
endTimeCode = ${
|
|
215
|
+
void main(){fragColor=uColorId;}`;function ba(e,t,r){let i={};for(let n of r)i[n]=e.getUniformLocation(t,n);return i}var pp="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 Ao(){let e=We(),t=e.xrDepthShader,r=e.shadowMapShader;return{fs:hp.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:[...pp,...t?.uniformNames||[],...r?.uniformNames||[]]}}function dp(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 To(e,t,r,i,n,a,s,o){if(i===void 0||!t.accessors?.[i])return null;let l=Fi(t,r,t.accessors[i],a);if(!l)return null;o&&(l=l.slice(),sp(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 Po(e){let t=Number(e);return Number.isFinite(t)?Math.max(0,t):1}function mh(e,t,r){let i=Ao(),n=So,a=i.fs,s=!1;for(let l of Lt)if(l.onResolveShader){let c=l.onResolveShader(t,r,n,a);c&&(n=c.vs,a=c.fs,s=!0)}let o=s?_i(e,n,a):null;return{program:o,uniforms:o?ba(e,o,i.uniforms):null}}function gp(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 yp(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 bp=Object.freeze({maxMeshes:1e3,maxTextures:64,maxVertices:1e6,maxIndices:3e6}),ph=Object.freeze({maxMeshes:1/0,maxTextures:1/0,maxVertices:1/0,maxIndices:1/0});function xa(e,t){t.indices?e.drawElements(4,t.indexCount,t.indexType,0):e.drawArrays(4,0,t.indexCount)}function dh(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 gh(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 yh(e,t,r=ph,i){let n={meshes:[],mesh:null,gpuTextures:[],vao:null,buffers:[]};try{return xp(e,t,r,i,n)}catch(a){let s=n.mesh&&!n.meshes.includes(n.mesh)?[...n.meshes,n.mesh]:n.meshes;gh(e,s,n.gpuTextures),n.vao&&e.deleteVertexArray(n.vao);for(let o of n.buffers)e.deleteBuffer(o);throw a}}function xp(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=ya("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=An(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(...hh(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],I=a.images[R.source];if(I){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(I.bufferView!==void 0){let Y=a.bufferViews[I.bufferView],J=Y.byteOffset||0,re=new Blob([o.slice(J,J+Y.byteLength)],{type:I.mimeType||"image/png"});typeof createImageBitmap=="function"&&createImageBitmap(re).then(V).catch(()=>{})}else if(I.uri){let Y=dp(I.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:",I.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],I=a.meshes[R.meshIdx],F=R.nodeIdx>=0?m[R.nodeIdx]:lt(),V=new Float32Array(9);rr(V,F);let Y=R.node?.extras?.shadow,J={name:R.node.name||I.name||`Mesh_${R.meshIdx}`,nodeIndex:R.nodeIdx,transform:F,normalMatrix:V,primitives:[],extras:R.node.extras||I.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=Fi(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),ke=lt();for(let _e=0;_e<H;_e++){let Le=_e*3,ne=_e*4;Sn(ke,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(ke,_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 I.primitives||[]){if(Q.extensions?.KHR_draco_mesh_compression){let z=ya("draco");z&&z.decodePrimitive(a,Q,o)}let ee=[],k=e.createVertexArray();n.vao=k,n.buffers=ee,e.bindVertexArray(k);let G=gp(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=lt();for(let se=0;se<O;se++)ft(X,F,J.instanceMatrices.subarray(se*16,se*16+16)),z(X)}else z(F)}let te=To(e,a,o,Q.attributes.POSITION,0,3,ee),Z=To(e,a,o,Q.attributes.NORMAL,1,3,ee),ae=To(e,a,o,Q.attributes.TEXCOORD_0,2,2,ee,yp(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 Lt)if(z.onBuildPrimitiveVAO){let O=z.onBuildPrimitiveVAO(e,k,Q,a,o);O&&(Se[z.name]=O)}e.bindVertexArray(null);let ke=a.materials&&Q.material!==void 0?a.materials[Q.material]:null,{program:_e,uniforms:Le}=mh(e,Q,ke),ne=dh(ke,v),Re=!!(ke?.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 Lt)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 va(){return typeof performance<"u"?performance.now():Date.now()}function Cn(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 ir=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=lt(),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=lt(),this.viewMatrix=lt(),this.activeViewMatrix=null,this.modelMatrix=lt(),this.mvpMatrix=lt(),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:lt(),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=Po(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=Bi(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){up(e,t)}static getDecoder(e){return ya(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=Ao();this.renderProg=_i(e,So,t.fs),this.pickProg=_i(e,fp,mp),this.uRender=ba(e,this.renderProg,t.uniforms),this.uPick=ba(e,this.pickProg,["uMVP","uColorId"]),this.setupPickingFbo()}recompileRenderProgram(){if(this.contextLost)return;let e=this.gl,t=Ao();this.renderProg&&e.deleteProgram(this.renderProg),this.renderProg=_i(e,So,t.fs),this.uRender=ba(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 Lt)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}=yh(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 Lt)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=Po(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(ch(e))}clearScene(){this.disposeMeshGpuResources(),this.lights=[],this.animations=[],this.currentClip=null,this.isPlayingAnimation=!1,this.animationTime=0,this.lastGlbData=null;for(let e of Lt)e.onClearScene?.(this);this.worldMatrices=[],this.gltf=null,this.initialNodeTransforms=[],this.turntableRotation=0,this.updateTurntableMatrix(),this.gl&&this.render()}loadModel(e){this.loadGLBData(zi(e))}setBackdropGLB(e,t){if(this.disposeMeshListGpuResources(this.backdropMeshes),this.backdropMeshes=[],!e){this.update(0),this.render();return}let r=zi(e),{meshes:i}=yh(this.gl,r,ph,()=>this.render());if(t)for(let n of i)n.transform[12]+=t[0],n.transform[13]+=t[1],n.transform[14]+=t[2],rr(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),rr(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=Po(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=Bi(e)}getToneMapping(){return this.toneMapping}async setEnvironmentImage(e){this.environmentSource=e&&typeof e=="object"?e:null;for(let t of Lt)if(t.setEnvironmentImage){await t.setEnvironmentImage(this,e),this.render();return}this.render()}async setSkyboxImage(e){for(let t of Lt)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,dh(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=mh(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 Lt)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=lt();ft(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]=Cn(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=va;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=lt();ft(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),ft(this.modelMatrix,this.modelRootMatrix,E.transform);let R=E.instanceMatrices;if(R&&R.length>=16){let I=R.length>>4,F=lt();for(let V of E.primitives){i.bindVertexArray(V.vao);for(let Y=0;Y<I;Y++)ft(F,this.modelMatrix,R.subarray(Y*16,Y*16+16)),ft(this.mvpMatrix,s,F),i.uniformMatrix4fv(this.uPick.uMVP,!1,this.mvpMatrix),xa(i,V)}}else{ft(this.mvpMatrix,s,this.modelMatrix),i.uniformMatrix4fv(this.uPick.uMVP,!1,this.mvpMatrix);for(let I of E.primitives)i.bindVertexArray(I.vao),xa(i,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]=Cn(this),y=lt();for(let b of o){ft(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?ft(this.modelMatrix,y,w.subarray(E*16,E*16+16)):this.modelMatrix.set(y),ft(this.mvpMatrix,s,this.modelMatrix);let N=lt();if(!co(N,this.mvpMatrix))continue;let C=(l+.5)/n*2-1,_=(c+.5)/a*2-1,P=[0,0,0],R=[0,0,0];Zc(P,C,_,-1,N),Zc(R,C,_,1,N);let I=R[0]-P[0],F=R[1]-P[1],V=R[2]-P[2],Y=Math.hypot(I,F,V)||1,J=I/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;W0(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){rr(this.normalMatrix,this.modelMatrix);let ke=this.normalMatrix,_e=ee.normal[0],Le=ee.normal[1],ne=ee.normal[2],Re=ke[0]*_e+ke[3]*Le+ke[6]*ne,W=ke[1]*_e+ke[4]*Le+ke[7]*ne,D=ke[2]*_e+ke[5]*Le+ke[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 Lt)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);uo(this.projMatrix,this.fov,e,.1,t);let r=this.customTarget||this.bounds.center;_n(this.viewMatrix,Cn(this),r,[0,1,0]),ft(this.mvpMatrix,this.projMatrix,this.viewMatrix),rr(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 Lt)r.onXRSessionEnd?.(this);if(this.lastTime=va(),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 Lt)t.onUpdate?.(this,e)}start(){if(this.animFrameId!==null)return;this.lastTime=va();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 Lt)a.onUpdate?.(this,e);let t=va();if(!this.isPointerDown&&this.autoRotate&&t-this.lastInteractionTime>=this.autoRotateDelay){this.turntableRotation+=this.autoRotateSpeed*e,this.updateTurntableMatrix();for(let a of Lt)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,[I,F,V]=Cn(this),Y=Math.cos(this.currTheta),J=-Math.sin(this.currTheta),re=.032;for(let Q of[-1,1]){let ee=lt(),k=lt(),G=Q<0?C:_,q=[I+Q*Y*re,F,V+Q*J*re];uo(ee,this.fov,G/N,.1,P),_n(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=lt(),o=e?.viewMatrix??this.viewMatrix;this.activeViewMatrix=o;let l=e?.projMatrix??this.projMatrix;ft(s,l,o);let c=We(),f=c.xrDepthShader,m=op(this.toneMapping),[h,p,g]=e?e.eyePos:Cn(this);for(let E of Lt)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 Lt)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{ft(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])}}ft(this.mvpMatrix,s,this.modelMatrix),rr(C.normalMatrix,this.modelMatrix);let P=C.extras?.xr?.stereo||C.userData?.xr?.stereo,R=0,I=0,F=1,V=1;P==="sbs"?(F=.5,R=v==="right"?.5:0):P==="ou"&&(V=.5,I=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,I,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 Lt)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=lt(),H=new Float32Array(9);for(let te=0;te<k;te++){if(ft(q,this.modelMatrix,ee.subarray(te*16,te*16+16)),ft(this.mvpMatrix,s,q),rr(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]])}xa(t,Y)}}else xa(t,Y)}}};if(S(!1),A){for(let E of Lt)E.onBeforeTransmissivePass?.(t,this);S(!0)}for(let E of Lt)E.onAfterRender?.(t,this,s,v,[r,i,n,a],l)}disposeMeshListGpuResources(e,t){gh(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 Lt)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()}};ir.registerPlugin=Rt,ir.getRegisteredPlugins=Wc;function vp(e){return e+3&-4}var Ye=(e,t)=>typeof e=="number"&&Number.isFinite(e)?e:t;function No(e,t){let r=t,i=1;for(;e.has(r);)r=`${t}_${i++}`;return e.add(r),r}function bh(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 xh(e,t=0){let[r,i,n,,a,s,o,,l,c,f,,m,h,p]=Array.from({length:15},(ee,k)=>Ye(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,I=f*b,F=w+C+I,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>I){let ee=2*Math.sqrt(Math.max(0,1+w-C-I));ee>1e-8&&(re=(_-R)/ee,V=.25*ee,Y=(N+S)/ee,J=(P+E)/ee)}else if(C>I){let ee=2*Math.sqrt(Math.max(0,1+C-w-I));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+I-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 wp(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 Lr=(e,t,r,i)=>typeof e=="number"&&Number.isFinite(e)?Math.max(t,Math.min(r,e)):i;function vh(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:Lr(r.volume,0,2,.6),loop:typeof r.loop=="boolean"?r.loop:!0,isGlobal:r.type==="global"||r.positional===!1}}function Mp(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 Vi(e,t){return wh(e,t)[0]}function wh(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?.(),ke=me(q.map);ke&&(ie.baseColorTexture=ke);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,Ye(Re,1)):Re?Math.max(0,(Ye(Re.x,1)+Ye(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,Ye(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,Ye(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=vp(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?.(),We().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=Ye(k.position?.x,0),Z=Ye(k.position?.y,0),ae=Ye(k.position?.z,0),ie=Ye(k.quaternion?.x,0),de=Ye(k.quaternion?.y,0),me=Ye(k.quaternion?.z,0),Se=Ye(k.quaternion?.w,1),ke=Ye(k.scale?.x,1),_e=Ye(k.scale?.y,1),Le=Ye(k.scale?.z,1);if((te||Z||ae)&&(H.translation=[te,Z,ae]),(ie||de||me||Se!==1)&&(H.rotation=[ie,de,me,Se]),(ke!==1||_e!==1||Le!==1)&&(H.scale=[ke,_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=wp(k.userData.xr);H.extensions={...H.extensions||{},MOZ_hubs_components:z,ANDROID_xr_scenecore:z},We().xrTraitSerializer?.gltfNode(H,k.userData.xr);let O=Mp(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=Ye(z?z[12]:k.position?.x,0),X=Ye(z?z[13]:k.position?.y,0),se=Ye(z?z[14]:k.position?.z,0),ce=ne.target,pe=ce?.parent?ce?.matrixWorld?.elements:void 0,xe=Ye(pe?pe[12]:ce?.position?.x,0),he=Ye(pe?pe[13]:ce?.position?.y,0),Ne=Ye(pe?pe[14]:ce?.position?.z,0),ge=xe-O,Ae=he-X,Ee=Ne-se,$e=Math.hypot(ge,Ae,Ee),De=Math.max(.01,Math.min(Math.PI/2,Ye(ne.angle,Math.PI/3))),Be=Math.max(0,Math.min(1,Ye(ne.penumbra,0))),Fe=Math.max(0,De*(1-Be)),Ve=Math.max(0,Ye(ne.distance,0)),qe=k.type==="directional"||k.type==="spot"||k.type==="point",je;if(k.castShadow&&qe){let Je=ne.shadow,Dt=Math.max(256,Math.min(2048,Math.round(Ye(Je?.mapSize?.x??Je?.mapSize?.width,1024))));je={cast:!0,mapSize:Dt<=384?256:Dt<=768?512:Dt<=1536?1024:2048,bias:Lr(Je?.bias,-.05,.05,-5e-4),normalBias:Lr(Je?.normalBias,0,.2,.015),radius:Lr(Je?.radius,0,8,1.5)},b=!0}let ut=O-xe,it=X-he,nt=se-Ne,ct=Math.hypot(ut,it,nt);y.push({type:k.type,color:[k.color.r,k.color.g,k.color.b],intensity:k.intensity,position:k.type==="directional"?[ut,it,nt]:[O,X,se],...k.type==="directional"?{direction:ct>1e-6?[ut/ct,it/ct,nt/ct]:[0,1,0]}:k.type==="spot"?{direction:$e>1e-6?[ge/$e,Ae/$e,Ee/$e]:[0,-1,0],outerConeAngle:De,innerConeAngle:Fe,range:Ve}:k.type==="point"?{range:Ve}:k.type==="hemisphere"&&ne.groundColor?{groundColor:[ne.groundColor.r,ne.groundColor.g,ne.groundColor.b]}:{},...je?{shadow:je}:{}}),qe&&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:$e,outerAngle:De,innerAngle:Fe,range:Ve,shadowSpec:je})}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),$e=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),$e<X[2]&&(X[2]=$e),$e>se[2]&&(se[2]=$e)}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 $e=v.indexOf(Ae);if($e===-1&&v.length<256&&($e=v.length,v.push(Ae)),$e===-1)continue;let De=w(Ee),Be=ge.get(De);Be||(Be=[],ge.set(De,Be)),Be.push($e)}if(ge.size>0){let Ae=[];for(let[Ee,$e]of ge.entries())Ae.push({material:Ee,variants:$e});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),$e=new Float32Array(ge*4),De=new Float32Array(ge*3);for(let Fe=0;Fe<ge;Fe++){let{t:Ve,r:qe,s:je}=xh(Ae,Fe*16);Ee[Fe*3]=Ve[0],Ee[Fe*3+1]=Ve[1],Ee[Fe*3+2]=Ve[2],$e[Fe*4]=qe[0],$e[Fe*4+1]=qe[1],$e[Fe*4+2]=qe[2],$e[Fe*4+3]=qe[3],De[Fe*3]=je[0],De[Fe*3+1]=je[1],De[Fe*3+2]=je[2]}let Be={TRANSLATION:E(Ee,"VEC3",0,5126,ge),ROTATION:E($e,"VEC4",0,5126,ge),SCALE:E(De,"VEC3",0,5126,ge)};if(he.instanceColor?.array&&he.instanceColor.array.length>=ge*3){let Fe=new Float32Array(he.instanceColor.array.subarray(0,ge*3));Be._COLOR_0=E(Fe,"VEC3",0,5126,ge)}H.extensions={...H.extensions||{},EXT_mesh_gpu_instancing:{attributes:Be}},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=bh(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),I=[];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=>[Ye(_e.position?.x,0),Ye(_e.position?.y,0),Ye(_e.position?.z,0),Ye(_e.quaternion?.x,0),Ye(_e.quaternion?.y,0),Ye(_e.quaternion?.z,0),Ye(_e.quaternion?.w,1),Ye(_e.scale?.x,1),Ye(_e.scale?.y,1),Ye(_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]=Ye(Re.position?.x,0),Z[ne][_e*3+1]=Ye(Re.position?.y,0),Z[ne][_e*3+2]=Ye(Re.position?.z,0);let W=Ye(Re.quaternion?.x,0),D=Ye(Re.quaternion?.y,0),z=Ye(Re.quaternion?.z,0),O=Ye(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]=Ye(Re.scale?.x,1),ie[ne][_e*3+1]=Ye(Re.scale?.y,1),ie[ne][_e*3+2]=Ye(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=[],ke=[];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&&ke.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")}ke.length>0&&I.push({name:"ProceduralLoop",samplers:Se,channels:ke})}let F=H0(o,s,e.userData),V=[],Y=[],J=[];for(let k=0;k<o.length;k++){let G=o[k],q=vh(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:Lr(H.pitch,.25,4,1)}}:{}});let ke=J.length,_e=Lr(H.refDistance,.05,100,1),Le=Lr(H.coneInnerAngle,0,360,360),ne=Lr(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:Lr(H.maxDistance,_e,500,Math.max(_e,25)),rolloffFactor:Lr(H.rolloffFactor,0,10,1),coneInnerAngle:+(Le*Math.PI/180).toFixed(6),coneOuterAngle:+(ne*Math.PI/180).toFixed(6),coneOuterGain:Lr(H.coneOuterGain,0,1,0)}}}),G.extensions={...G.extensions||{},KHR_audio_emitter:{emitter:ke}},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}],...I.length>0?{animations:I}:{},...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 Co(e){return new TextEncoder().encode(e)}function En(e,t){let{gltf:r,bin:i}=Vi(e,t),n=JSON.stringify(r),a=Co(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 _p(e,t){let[r,i]=wh(e,t);return Mh(r,i)}function Mh(e,t){let r=[],i=e.gltf,n=We().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,_)=>No(x,Ln(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,I=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);I[V++]=J>>16&255,V<I.length&&(I[V++]=J>>8&255),V<I.length&&(I[V++]=J&255)}return I}function b(C,_,P){let R=C?.index;if(typeof R!="number")return;let I=h[R],F=I?.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 I.sampler=="number"?g[I.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),I=P.byteLength||0;return{acc:_,buffer:s.slice(R,R+I)}}function S(C,_,P,R){let I=[],F=f[C];if(!F)return I;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,ke=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=(Fe,Ve)=>Array.isArray(Fe)&&Fe.length>=3?[Fe[0],Fe[1],Fe[2]]:Ve;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,$e=b(D.normalTexture,[2*Ee,2*Ee,2,1],[-Ee,-Ee,-1,0]),De=typeof D.occlusionTexture?.strength=="number"?D.occlusionTexture.strength:1,Be=De!==1?b(D.occlusionTexture,[De,De,De,1],[1-De,1-De,1-De,0]):b(D.occlusionTexture);(ce||Ne||$e||Ae||Be)&&(Re=[ce,Ne,$e,Ae,Be]),W=D.extensions||{},W.KHR_materials_clearcoat&&(Se=W.KHR_materials_clearcoat.clearcoatFactor??0,ke=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))}I.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:ke,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 I}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?[Ye(k[0],G),Ye(k[1],G),Ye(k[2],G)]:[G,G,G],I=(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=xh(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=[Ye(q.rotation[0],0),Ye(q.rotation[1],0),Ye(q.rotation[2],0),Ye(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(I(ne,se,H)),O.push(F(Re,se,te)),X.push(I(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 ke=(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=I(O,he,[0,0,0]),ge=F(X,he,[0,0,0,1]),Ae=I(se,he,[1,1,1]);for(let Ee of ne){let $e=Ee.color||[.8,.8,.8],De=ce&&ce.length>=(he+1)*3;xe.push({...Ee,name:`${Ee.name}_${he}`,materialName:De?`${Ee.materialName}_inst_${he}`:Ee.materialName,color:De?[$e[0]*ce[he*3],$e[1]*ce[he*3+1],$e[2]*ce[he*3+2]]:Ee.color,translation:Ne,rotation:ge,scale:Ae})}}ee(de,xe),G.push(ke(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(ke(Le,O,_e))}}else{let Le=[];ee(de,Le),G.push(ke(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)??hh(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 Ln(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 wa(e){return String(e??"").replace(/[\x00-\x1f\x7f]/g,"").replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function It(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 Rr=(e,t,r)=>`(${It(e)}, ${It(t)}, ${It(r)})`,Rn=(e,t,r,i)=>`(${It(e)}, ${It(t)}, ${It(r)}, ${It(i)})`;function _h(e){let t=e.length/3,r=new Array(t);for(let i=0;i<t;i++)r[i]=Rr(e[i*3],e[i*3+1],e[i*3+2]);return r.join(", ")}function Sp(e,t){let r=new Array(t);for(let i=0;i<t;i++)r[i]=`(${It(e[i*2])}, ${It(1-e[i*2+1])})`;return r.join(", ")}function Ap(e){return Array.from(e).join(", ")}function Tp(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=Ln(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 = ${It(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,118 +230,228 @@ kind = "component"
|
|
|
265
230
|
{
|
|
266
231
|
${l}def Scope "Materials"
|
|
267
232
|
{
|
|
268
|
-
`;for(let[
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
`),
|
|
273
|
-
`),
|
|
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,I,F]=y.textures||[],V=(G,q)=>`.connect = <${C}/${G}.outputs:${q}>`,Y=_?`color3f inputs:diffuseColor${V("DiffuseTexture","rgb")}`:`color3f inputs:diffuseColor = ${Rr(A,b,w)}`,J=P?`float inputs:metallic${V("MetallicRoughnessTexture","b")}
|
|
234
|
+
float inputs:roughness${V("MetallicRoughnessTexture","g")}`:`float inputs:metallic = ${It(y.metallic)}
|
|
235
|
+
float inputs:roughness = ${It(y.roughness)}`,re="";y.clearcoat>0&&(re+=`float inputs:clearcoat = ${It(y.clearcoat)}
|
|
236
|
+
`,re+=`float inputs:clearcoatRoughness = ${It(y.clearcoatRoughness)}
|
|
237
|
+
`),y.ior!==1.5&&(re+=`float inputs:ior = ${It(y.ior)}
|
|
238
|
+
`),y.opacity<1&&(re+=`float inputs:opacity = ${It(y.opacity)}
|
|
239
|
+
`),I?re+=`color3f inputs:emissiveColor${V("EmissiveTexture","rgb")}
|
|
240
|
+
`:(S>0||E>0||N>0)&&(re+=`color3f inputs:emissiveColor = ${Rr(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||I||F){Q+=`def Shader "PrimvarReader"
|
|
244
|
+
{
|
|
245
|
+
uniform token info:id = "UsdPrimvarReader_float2"
|
|
246
|
+
string inputs:varname = "st"
|
|
247
|
+
float2 outputs:result
|
|
248
|
+
}
|
|
249
|
+
`;let G=(q,H,te,Z)=>{if(!H)return;let ae=H.scale?`float4 inputs:scale = ${Rn(H.scale[0],H.scale[1],H.scale[2],H.scale[3])}
|
|
250
|
+
`:"",ie=H.bias?`float4 inputs:bias = ${Rn(H.bias[0],H.bias[1],H.bias[2],H.bias[3])}
|
|
251
|
+
`:"";Q+=`def Shader "${q}"
|
|
252
|
+
{
|
|
253
|
+
uniform token info:id = "UsdUVTexture"
|
|
254
|
+
asset inputs:file = @${wa(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
|
|
262
|
+
float outputs:b
|
|
263
|
+
`),G("NormalTexture",R,"raw",`float3 outputs:rgb
|
|
264
|
+
`),G("EmissiveTexture",I,"sRGB",`float3 outputs:rgb
|
|
265
|
+
`),G("OcclusionTexture",F,"raw",`float outputs:r
|
|
266
|
+
`)}let ee=`${Y}
|
|
267
|
+
${J}
|
|
268
|
+
${re}`,k=y.tslGraph&&We().tslUsdzSerializer?.(y.tslGraph,v,ee);k&&(ee=k.surfaceInputsUsda||ee,Q+=k.nodeGraphUsda),c+=`def Material "${v}"
|
|
274
269
|
{
|
|
275
270
|
def Shader "PBRShader"
|
|
276
271
|
{
|
|
277
272
|
uniform token info:id = "UsdPreviewSurface"
|
|
278
|
-
|
|
279
|
-
float inputs:metallic = ${Be(g.metallic)}
|
|
280
|
-
float inputs:roughness = ${Be(g.roughness)}
|
|
281
|
-
${T}token outputs:surface
|
|
273
|
+
${ee}token outputs:surface
|
|
282
274
|
}
|
|
283
|
-
token outputs:surface
|
|
284
|
-
}
|
|
285
|
-
`}
|
|
275
|
+
token outputs:surface${V("PBRShader","surface")}
|
|
276
|
+
${Q}}
|
|
277
|
+
`}c+=`}
|
|
286
278
|
def Scope "Meshes"
|
|
287
279
|
{
|
|
288
|
-
`;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=We().xrTraitSerializer;if(v){let I=N?.usdLines(v,wa)??[];if(!I.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&&I.push(`string ${F} = "${wa(V)}"`)}I.length>0&&E.push(`customData = {
|
|
289
281
|
dictionary xr = {
|
|
290
|
-
${
|
|
282
|
+
${I.join(`
|
|
291
283
|
`)}
|
|
292
284
|
}
|
|
293
|
-
}`)}let
|
|
294
|
-
${
|
|
285
|
+
}`)}let C=E.length>0?` (
|
|
286
|
+
${E.join(`
|
|
295
287
|
`)}
|
|
296
|
-
)`:"",
|
|
297
|
-
`:"";if(
|
|
298
|
-
bool physics:kinematicEnabled = ${
|
|
288
|
+
)`:"",_=A?`uniform token visibility = "invisible"
|
|
289
|
+
`:"";if(S){let I=v?.rigidBody??v?.physics,F=I?.body??I?.mode??I;_+=`bool physics:rigidBodyEnabled = true
|
|
290
|
+
bool physics:kinematicEnabled = ${F==="static"||F==="kinematic"}
|
|
299
291
|
bool physics:collisionEnabled = true
|
|
300
|
-
`,
|
|
301
|
-
`)}let
|
|
292
|
+
`,I?.mass>0&&Number.isFinite(I.mass)&&(_+=`float physics:mass = ${It(I.mass)}
|
|
293
|
+
`)}let P=vh(v),R=(P?`def SpatialAudio "AudioEmitter"
|
|
302
294
|
{
|
|
303
|
-
${
|
|
304
|
-
`:""}uniform token inputs:auralMode = "${
|
|
305
|
-
uniform token inputs:playbackMode = "${
|
|
306
|
-
double gain = ${
|
|
307
|
-
}
|
|
308
|
-
`:"";return{header:
|
|
309
|
-
quatf xformOp:orient.timeSamples = { ${
|
|
310
|
-
double3 xformOp:scale.timeSamples = { ${
|
|
295
|
+
${P.src?`asset inputs:file = @${wa(P.src)}@
|
|
296
|
+
`:""}uniform token inputs:auralMode = "${P.isGlobal?"nonSpatial":"spatial"}"
|
|
297
|
+
uniform token inputs:playbackMode = "${P.loop?"loopFromStart":"onceFromStart"}"
|
|
298
|
+
double gain = ${It(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,I,F)=>E.times.map((V,Y)=>`${It(V)}: ${F(R?.[Y]||I)}`).join(", "),C=N(E.translations,[0,0,0],R=>Rr(R[0],R[1],R[2])),_=N(E.rotations,[0,0,0,1],R=>{let I=Math.hypot(R[0],R[1],R[2],R[3])||1;return Rn(R[3]/I,R[0]/I,R[1]/I,R[2]/I)}),P=N(E.scales,[1,1,1],R=>Rr(R[0],R[1],R[2]));return`double3 xformOp:translate.timeSamples = { ${C} }
|
|
301
|
+
quatf xformOp:orient.timeSamples = { ${_} }
|
|
302
|
+
double3 xformOp:scale.timeSamples = { ${P} }
|
|
311
303
|
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:orient", "xformOp:scale"]
|
|
312
|
-
`}let
|
|
313
|
-
`,
|
|
314
|
-
`,
|
|
315
|
-
`,
|
|
316
|
-
`),
|
|
317
|
-
int[] faceVertexCounts = [${
|
|
318
|
-
int[] faceVertexIndices = [${
|
|
319
|
-
point3f[] points = [${
|
|
320
|
-
`;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 = ${Rr(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 = ${Rn(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 = ${Rr(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 I=0;I<y;I++){let F=v.positions[I*3],V=v.positions[I*3+1],Y=v.positions[I*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),_=Ln(v.materialName,"DefaultMaterial"),P=C>0?C===1?"3":"3, ".repeat(C-1)+"3":"",R=`float3[] extent = [${Rr(A,b,w)}, ${Rr(S,E,N)}]
|
|
309
|
+
int[] faceVertexCounts = [${P}]
|
|
310
|
+
int[] faceVertexIndices = [${Ap(v.indices)}]
|
|
311
|
+
point3f[] points = [${_h(v.positions)}]
|
|
312
|
+
`;return v.normals&&v.normals.length===v.positions.length&&(R+=`normal3f[] normals = [${_h(v.normals)}] (
|
|
321
313
|
interpolation = "vertex"
|
|
322
314
|
)
|
|
323
|
-
`),
|
|
315
|
+
`),v.uvs&&v.uvs.length===y*2&&(R+=`texCoord2f[] primvars:st = [${Sp(v.uvs,y)}] (
|
|
324
316
|
interpolation = "vertex"
|
|
325
317
|
)
|
|
326
|
-
`),
|
|
327
|
-
`,
|
|
328
|
-
|
|
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=No(A,Ln(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}
|
|
329
322
|
{
|
|
330
|
-
${
|
|
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}
|
|
331
324
|
{
|
|
332
|
-
${
|
|
325
|
+
${E.body}${m(y)}${E.tail}`,c+=`def Mesh "${N}" (
|
|
333
326
|
prepend apiSchemas = ["MaterialBindingAPI"]
|
|
334
327
|
)
|
|
335
328
|
{
|
|
336
|
-
${h(
|
|
337
|
-
`,
|
|
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=No(v,Ln(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],I=-_,F=-P,V=-R;A.direction&&A.direction.length>=3&&(A.type==="directional"?(I=-A.direction[0],F=-A.direction[1],V=-A.direction[2]):(I=A.direction[0],F=A.direction[1],V=A.direction[2]));let[Y,J,re,Q]=bh(I,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 = ${Rr(_,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 = ${Rn(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 = ${It(q)}
|
|
340
|
+
float inputs:shaping:cone:softness = ${It(te)}
|
|
341
|
+
`}c+=`def ${w} "${b}" (
|
|
342
|
+
prepend apiSchemas = ${S}
|
|
343
|
+
)
|
|
344
|
+
{
|
|
345
|
+
color3f inputs:color = ${Rr(E,N,C)}
|
|
346
|
+
float inputs:intensity = ${It(A.intensity??1)}
|
|
347
|
+
bool inputs:shadow:enable = 1
|
|
348
|
+
${G}${ee}}
|
|
349
|
+
`}c+=`}
|
|
350
|
+
`}return c+=`}
|
|
351
|
+
`,c}var Ma=null;function Eo(e){if(!Ma){Ma=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;Ma[r]=i}}let t=4294967295;for(let r=0;r<e.length;r++)t=Ma[(t^e[r])&255]^t>>>8;return(t^4294967295)>>>0}function Pp(e){let t=[],r=0,i=[];for(let f of e){let m=Co(f.filename),h=Eo(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 Sh(e){let t=[{filename:"model.usda",data:Co(Tp(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 Pp(t)}function In(e){return Sh(_p(e))}function _a(e){return Sh(Mh(zi(e)))}function Sa(e){return e&&typeof e.toUSDZ=="function"?e.toUSDZ():_a(e)}function Aa(e){let t=Sa(e);return new Blob([t],{type:"model/vnd.usdz+zip"})}function Ta(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),I=s(P._type);if(I>R)P=P.swizzle("xyzw".slice(0,R));else{let F=[P];for(let V=I;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 I=[_];for(let F=R;F<P;F++)I.push(new p("const","float",[],[F===3?1:0]));return new p("construct",C,I)};class p{constructor(C,_,P,R,I,F){this.isTSLNode=!0,this._op=C,this._type=_,this._args=P,R!==void 0&&(this._val=R),I!==void 0&&(this._name=I),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,I]=m(this,C),F=f(_);return F._type!=="float"&&F._type!==I&&(F=h(F,I)),new p("mix",I,[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,I=f(C);return(R._type!=="float"||I._type!=="float")&&(R=h(R,P._type),I=h(I,P._type)),new p("smoothstep",P._type,[R,I,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 I=this.sub(C).div(f(_).sub(C)).clamp(0,1);return f(P).mix(R,I)}}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,I=[],F=0;for(let Y of P)if(F+=s(Y._type),Y._op==="const"&&Y._val)for(let J of Y._val)I.push(J);else R=!1;if(R&&I.length>=_)return new p("const",N,[],I.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={},I=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=I.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),I.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 Ui="GOOGLE_material_tsl",Ah=128,Th=16,Ph=3600,Np={positionLocal:"vec3",positionWorld:"vec3",normalLocal:"vec3",normalWorld:"vec3",viewDirection:"vec3",uv:"vec2",vertexColor:"vec4",instanceIndex:"float",time:"float"},Cp={color:"vec3",opacity:"float",emissive:"vec3",roughness:"float",metalness:"float",normalScale:"float",bump:"vec3",position:"vec3"},Ep=new Set(["neg","abs","sign","floor","ceil","fract","sqrt","exp","log","sin","cos","normalize"]),Lp=new Set(["add","sub","mul","div","mod","pow","atan2","min","max"]),Nh={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"]},Rp=/^[A-Za-z_][A-Za-z0-9_]{0,63}$/,Ip=new Set(["__proto__","constructor","prototype"]);function Lo(e,t){let r=Math.abs(t)<1e-6?t<0?-1e-6:1e-6:t;return e-r*Math.floor(e/r)}function nr(e){return e==="vec4"?4:e==="vec3"?3:e==="vec2"?2:1}function Ro(e){return e===1?"float":e===2?"vec2":e===3?"vec3":e===4?"vec4":null}function Io(e){return e==="float"||e==="vec2"||e==="vec3"||e==="vec4"}function ht(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 Si(e,t){for(let r=0;r<t.length;r++)e=Math.imul((e^t.charCodeAt(r))>>>0,16777619)>>>0;return e}var Ch=new Float32Array(1),$p=new Uint32Array(Ch.buffer);function Dp(e,t){return Ch[0]=t,Math.imul((e^$p[0])>>>0,16777619)>>>0}function Pa(e,t){let r=nr(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 Oi(e,t="Material"){if(!e||typeof e!="object"||Array.isArray(e))return ht("TL501",`Invalid GOOGLE_material_tsl on '${t}'.`);let r=e;if(r.version!==1)return ht("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 ht("TL501",`Invalid TSL uniforms on '${t}'.`);let y=a,A=Object.keys(y).sort();if(A.length>16)return ht("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=Io(E)?Pa(E,S.value):null;if(Ip.has(w)||!Rp.test(w)||!Io(E)||!N)return ht("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 ht("TL501",`Empty TSL nodes on '${t}'.`);if(s.length>128)return ht("TL502",`TSL '${t}' exceeds MAX_TSL_NODES (128).`);let o=[],l=2166136261;for(let y of i)l=Si(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 ht("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 ht("TL504",`Unsupported loop/call op '${w}' at node ${y} on '${t}'.`);if(typeof w!="string"||!Io(S))return ht("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 ht("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 ht("TL501",`Cyclic or out-of-order arg at node ${y} on '${t}'.`);C.push(P)}}l=Si(l,`N${y}:${E}:${S}:`);for(let P of C)l=Si(l,`${P},`);let _=C.map(P=>o[P].type);if(E==="const"){let P=nr(S),R=b.value;if(C.length!==0||!Array.isArray(R)||R.length!==P)return ht("TL501",`Invalid const node ${y} on '${t}'.`);let I=[];for(let F=0;F<P;F++){let V=Number(R[F]);if(!Number.isFinite(V))return ht("TL501",`Non-finite const at node ${y}.`);let Y=Math.fround(V);I.push(Y),l=Dp(l,Y)}o.push({op:E,type:S,args:[],value:I})}else if(E==="builtin"){let P=b.name;if(C.length!==0||typeof P!="string"||Np[P]!==S)return ht("TL501",`Invalid builtin at node ${y}.`);l=Si(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 ht("TL501",`Invalid uniform ref at node ${y}.`);l=Si(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)||Ro(P.length)!==S)return ht("TL501",`Invalid swizzle at node ${y}.`);let R=nr(_[0]);for(let I=0;I<P.length;I++)if("xyzw".indexOf(P[I])>=R)return ht("TL501",`Swizzle '.${P}' out of bounds at node ${y}.`);l=Si(l,P),o.push({op:E,type:S,args:C,mask:P})}else if(E==="construct"){let P=nr(S),R=_.reduce((I,F)=>I+nr(F),0);if(C.length===0||!(C.length===1&&_[0]==="float")&&R!==P)return ht("TL501",`Invalid construct at node ${y}.`);o.push({op:E,type:S,args:C})}else if(Ep.has(E)){if(C.length!==1||_[0]!==S)return ht("TL501",`Type mismatch on '${E}' at node ${y}.`);o.push({op:E,type:S,args:C})}else if(Lp.has(E)){if((C.length===2?_[0]===_[1]?_[0]:_[0]==="float"?_[1]:_[1]==="float"?_[0]:null:null)!==S)return ht("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 ht("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 ht("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 ht("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 ht("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 ht("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 ht("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 ht("TL501",`Invalid 'reflect' at node ${y}.`);o.push({op:E,type:S,args:C})}else if(E in Nh){let[P,R]=Nh[E];if(C.length!==P.length||S!==R||P.some((I,F)=>_[F]!==I))return ht("TL501",`Invalid '${E}' at node ${y}.`);o.push({op:E,type:S,args:C})}else return ht("TL501",`Unknown TSL op '${String(E)}' at node ${y}.`)}let c=r.outputs;if(!c||typeof c!="object"||Array.isArray(c))return ht("TL501",`Missing TSL outputs on '${t}'.`);let f=c,m={},h=0;for(let y of Object.keys(f).sort()){let A=Cp[y];if(!A)return ht("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 ht("TL501",`Invalid TSL output '${y}' on '${t}'.`);m[y]=b,h++,l=Si(l,`O:${y}=${b};`)}}if(h===0)return ht("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 ht("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 Xr(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 Na(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 kp=["x","y","z","w"],Eh=[[2,"vec2"],[3,"vec3"],[4,"vec4"]];function ji(e,t){return Eh.map(([r,i])=>{let n=kp.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 Lh(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);}",...ji("_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);}",...ji("_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));}",...ji("_tslPow",2)),e.clamp&&r.push("float _tslClamp(float a,float b,float c){return clamp(a,min(b,c),max(b,c));}",...ji("_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);}",...ji("_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);}",...ji("_tslAtan2",2)),e.norm&&r.push("float _tslNorm(float v){return abs(v)>1e-6?sign(v):0.0;}",...Eh.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 Fp={positionLocal:"_tslPL",positionWorld:"_tslPW",normalLocal:"_tslNL",normalWorld:"_tslNW",viewDirection:"_tslVD",uv:"_tslUV",vertexColor:"_tslVC",instanceIndex:"_tslII"};function Rh(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(Xr);g=o==="float"?x[0]:`${o}(${x.join(",")})`;break}case"builtin":g=s.builtin==="time"?`_tslMod(uTslTime,${Xr(3600)})`:Fp[s.builtin]??"0.0";break;case"uniform":{let x=`uTslParams[${s.uniformSlot??0}]`,v=nr(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 $o(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=Lh(Na(e.nodes,e.vertexReachable,e.usesTime),!1),c=Rh(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=Lh(Na(e.nodes,e.fragmentReachable,e.usesTime),!0),c=Rh(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 Bp={float:"float",vec2:"float2",vec3:"float3",vec4:"float4"},zp={float:"float",vec2:"vector2",vec3:"vector3",vec4:"vector4"};function gr(e){return Bp[e]||"float"}function ui(e){return zp[e]||"float"}function $n(e,t){if(t===1)return Xr(e[0]??0);let r=[];for(let i=0;i<t;i++)r.push(Xr(e[i]??0));return`(${r.join(", ")})`}function Do(e,t,r=""){let i;if(e&&typeof e=="object"&&"fragmentReachable"in e)i=e;else{let w=Oi(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=gr(w.type),E=nr(w.type);s.push(`${S} inputs:u_${w.slot} = ${$n(w.defaultVec4,E)}`)}let l=(w,S,E,N)=>(a.push(`def Shader "${w}"
|
|
378
|
+
{
|
|
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=nr(w),N=`C_${o++}`;return l(N,`ND_constant_${ui(w)}`,gr(w),[`${gr(w)} inputs:value = ${$n(S,E)}`])},f=(w,S)=>{if(S==="float")return w;let E=nr(S),N=`B_${o++}`,C=[];for(let _=1;_<=E;_++)C.push(`float inputs:in${_}.connect = <${w}>`);return l(N,`ND_combine${E}_${ui(S)}`,gr(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_${ui(S)}`,"float",[`${gr(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 = ${Xr(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=gr(E),C=ui(E),_=nr(E),P=S.args[0]!==void 0?x[S.args[0]]:"",R=S.args[1]!==void 0?x[S.args[1]]:"",I=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 = ${$n(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=nr(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 = ${$n([-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 = ${$n([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(I,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(I,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 = <${I}>`,`${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_${ui(F)}`,"float",[`${gr(F)} inputs:in1.connect = <${P}>`,`${gr(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_${ui(F)}`,"float",[`${gr(F)} inputs:in.connect = <${P}>`]);break;case"distance":{let re=l(`D_${o++}`,`ND_subtract_${ui(F)}`,gr(F),[`${gr(F)} inputs:in1.connect = <${P}>`,`${gr(F)} inputs:in2.connect = <${R}>`]);x[w]=F==="float"?l(J,"ND_absval_float","float",[`float inputs:in.connect = <${re}>`]):l(J,`ND_magnitude_${ui(F)}`,"float",[`${gr(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"
|
|
338
388
|
{
|
|
339
|
-
${
|
|
340
|
-
`}
|
|
389
|
+
${[...s,...v,...a].join(`
|
|
390
|
+
`)}
|
|
341
391
|
}
|
|
342
|
-
`,a}function Sl(e,t){if(e&&typeof e.traverse=="function"){let s=vl(e,t);return Wi(s)}let r=Dt(e),i=Hi(r);return Wi(i)}var Ir=null;function Xi(e){if(!Ir){Ir=new Uint32Array(256);for(let r=0;r<256;r++){let i=r;for(let s=0;s<8;s++)i=i&1?3988292384^i>>>1:i>>>1;Ir[r]=i}}let t=4294967295;for(let r=0;r<e.length;r++)t=Ir[(t^e[r])&255]^t>>>8;return(t^4294967295)>>>0}function Al(e){let t=[],r=0,i=[];for(let h of e){let c=Gi(h.filename),f=Xi(h.data),p=h.data.length,m=30+c.length,g=(r+m)%64,x=g!==0?64-g:0,b=new Uint8Array(m+x),v=new DataView(b.buffer);v.setUint32(0,67324752,!0),v.setUint16(4,20,!0),v.setUint32(14,f,!0),v.setUint32(18,p,!0),v.setUint32(22,p,!0),v.setUint16(26,c.length,!0),v.setUint16(28,x,!0),b.set(c,30),t.push({offset:r,size:p,crc:f,filenameBytes:c,entry:h}),i.push(b,h.data),r+=b.length+h.data.length}let s=r;for(let h of t){let c=new Uint8Array(46+h.filenameBytes.length),f=new DataView(c.buffer);f.setUint32(0,33639248,!0),f.setUint16(4,20,!0),f.setUint16(6,20,!0),f.setUint32(16,h.crc,!0),f.setUint32(20,h.size,!0),f.setUint32(24,h.size,!0),f.setUint16(28,h.filenameBytes.length,!0),f.setUint32(42,h.offset,!0),c.set(h.filenameBytes,46),i.push(c),r+=c.length}let n=r-s,l=new Uint8Array(22),a=new DataView(l.buffer);a.setUint32(0,101010256,!0),a.setUint16(8,t.length,!0),a.setUint16(10,t.length,!0),a.setUint32(12,n,!0),a.setUint32(16,s,!0),i.push(l),r+=22;let o=new Uint8Array(r),u=0;for(let h of i)o.set(h,u),u+=h.length;return o}var wa=e=>Al([{filename:"model.usda",data:Gi(e)}]);function fr(e){return wa(Sl(e))}function kr(e){return wa(Wi(Hi(Dt(e))))}function Fr(e){return e&&typeof e.toUSDZ=="function"?e.toUSDZ():kr(e)}function Vr(e){let t=Fr(e);return new Blob([t],{type:"model/vnd.usdz+zip"})}function Rt(e,t,r,i){let s=typeof e=="number"&&Number.isFinite(e)?e:i;return Math.max(t,Math.min(r,s))}function Tl(e){return Array.isArray(e)&&e.length>=3&&Number.isFinite(e[0])&&Number.isFinite(e[1])&&Number.isFinite(e[2])}function qi(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Pl(e,t=256){return typeof e=="string"&&e.length>0?e.slice(0,t):void 0}function Rl(e){let t=qi(e);if(!t)return null;let r=t.target;return{target:Tl(r)?[r[0],r[1],r[2]]:typeof r=="string"&&r.length>0&&r.length<=256?r:[0,0,0],radius:Rt(t.radius,.01,50,.5),speed:Rt(t.speed,-20,20,.5),height:Rt(t.height,-10,10,0),phase:Rt(t.phase,-1e6,1e6,0),faceCenter:t.faceCenter===!0}}var Cl=["hum","reactor","wind","beacon","geiger","chimeLoop","machinery","water"],El=["confirm","error","alarm","warning","pickup","jump","beam","impact","burst","powerup","step","pass","fail"],Lu=new Set(Cl),Nu=new Set(El);function Sa(e,t){let r=Pl(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 Aa(e){if(!e||typeof e=="number"&&!(e>0&&Number.isFinite(e)))return null;let t=e===!0?{}:typeof e=="number"?{strength:e}:qi(e);if(!t||t.enabled===!1)return null;let r=Rt(t.strength??t.intensity,0,5,.35);return r>0?{enabled:!0,strength:r,threshold:Rt(t.threshold,0,4,.8),radius:Rt(t.radius,0,2,.5)}:null}function Ki(e){if(!e)return null;let t=e===!0?{}:typeof e=="string"?{color:e}:qi(e);if(!t||t.enabled===!1)return null;let r=t.thickness??t.width;return{enabled:!0,color:Sa(t.color,"#38bdf8"),thickness:Rt(typeof r=="number"&&r>0&&r<.25?Math.max(1.5,r*140):r,.5,20,3),pulse:t.pulse===!0}}var it=class _o{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 _o(this.x,this.y)}copy(t){return this.x=t.x,this.y=t.y,this}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)}},be=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.x=t.x,this.y=t.y,this.z=t.z,this}add(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this}addVectors(t,r){return this.x=t.x+r.x,this.y=t.y+r.y,this.z=t.z+r.z,this}sub(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this}subVectors(t,r){return this.x=t.x-r.x,this.y=t.y-r.y,this.z=t.z-r.z,this}multiplyScalar(t){return this.x*=t,this.y*=t,this.z*=t,this}divideScalar(t){return this.multiplyScalar(t?1/t:0)}setScalar(t){return this.set(t,t,t)}addScaledVector(t,r){return this.x+=t.x*r,this.y+=t.y*r,this.z+=t.z*r,this}length(){return Math.hypot(this.x,this.y,this.z)}normalize(){let t=this.length();return t>1e-5&&(this.x/=t,this.y/=t,this.z/=t),this}cross(t){let r=this.y*t.z-this.z*t.y,i=this.z*t.x-this.x*t.z,s=this.x*t.y-this.y*t.x;return this.x=r,this.y=i,this.z=s,this}crossVectors(t,r){let i=t.x,s=t.y,n=t.z,l=r.x,a=r.y,o=r.z;return this.x=s*o-n*a,this.y=n*l-i*o,this.z=i*a-s*l,this}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,s=this.z,n=t.elements,l=1/(n[3]*r+n[7]*i+n[11]*s+n[15]);return this.x=(n[0]*r+n[4]*i+n[8]*s+n[12])*l,this.y=(n[1]*r+n[5]*i+n[9]*s+n[13])*l,this.z=(n[2]*r+n[6]*i+n[10]*s+n[14])*l,this}},Yi=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}},Or=class Io{constructor(t=0,r=0,i=0,s="XYZ"){this._onChangeCallback=null,this._x=Number(t),this._y=Number(r),this._z=Number(i),this.order=s}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,s=this.order){return this._x=Number(t),this._y=Number(r),this._z=Number(i),this.order=s,this._onChangeCallback?.(),this}copy(t){return this._x=t.x,this._y=t.y,this._z=t.z,this.order=t.order,this._onChangeCallback?.(),this}clone(){return new Io(this._x,this._y,this._z,this.order)}_onChange(t){return this._onChangeCallback=t,this}},Ur=class ko{constructor(t=0,r=0,i=0,s=1){this._onChangeCallback=null,this._x=Number(t),this._y=Number(r),this._z=Number(i),this._w=Number(s)}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,s){return this._x=Number(t),this._y=Number(r),this._z=Number(i),this._w=Number(s),this._onChangeCallback?.(),this}copy(t){return this._x=t.x,this._y=t.y,this._z=t.z,this._w=t.w,this._onChangeCallback?.(),this}clone(){return new ko(this._x,this._y,this._z,this._w)}setFromEuler(t,r=!0){let i=t.x,s=t.y,n=t.z,l=Math.cos(i/2),a=Math.cos(s/2),o=Math.cos(n/2),u=Math.sin(i/2),h=Math.sin(s/2),c=Math.sin(n/2);return this._x=u*a*o+l*h*c,this._y=l*h*o-u*a*c,this._z=l*a*c+u*h*o,this._w=l*a*o-u*h*c,r&&this._onChangeCallback?.(),this}setFromAxisAngle(t,r){let i=r/2,s=Math.sin(i);return this.set(t.x*s,t.y*s,t.z*s,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,s=t.y,n=t.z,l=t.w,a=r.x,o=r.y,u=r.z,h=r.w;return this._x=i*h+l*a+s*u-n*o,this._y=s*h+l*o+n*a-i*u,this._z=n*h+l*u+i*o-s*a,this._w=l*h-i*a-s*o-n*u,this._onChangeCallback?.(),this}_onChange(t){return this._onChangeCallback=t,this}},It=class Fo{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 Fo;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 ke(this.elements,t.elements,r.elements),this}lookAt(t,r,i){return Pr(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 be(0,0,0),i=new be(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}},Zi=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 Ye(this.elements,e.elements),this}},Qe=e=>e<=.04045?e/12.92:((e+.055)/1.055)**2.4,Br=e=>e<=.0031308?e*12.92:1.055*e**(1/2.4)-.055,Ta={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},ot=class Vo{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 s=parseInt(i,16);i.length===6&&!Number.isNaN(s)&&this.setHex(s)}else if(r in Ta)this.setHex(Ta[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 s=n=>Qe(Math.max(0,Math.min(1,(parseFloat(n)||0)/(n.endsWith("%")?100:255))));this.setRGB(s(i[0]),s(i[1]),s(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 a=Qe(i);return this.setRGB(a,a,a)}let s=i<=.5?i*(1+r):i+r-i*r,n=2*i-s,l=a=>(a<0&&(a+=1),a>1&&(a-=1),a<1/6?n+(s-n)*6*a:a<1/2?s:a<2/3?n+(s-n)*6*(2/3-a):n);return this.setRGB(Qe(l(t+1/3)),Qe(l(t)),Qe(l(t-1/3)))}lerp(t,r){let i=Number(r)||0;return this.r+=(t.r-this.r)*i,this.g+=(t.g-this.g)*i,this.b+=(t.b-this.b)*i,this}lerpColors(t,r,i){let s=Number(i)||0;return this.r=t.r+(r.r-t.r)*s,this.g=t.g+(r.g-t.g)*s,this.b=t.b+(r.b-t.b)*s,this}multiplyScalar(t){let r=Number(t)||0;return this.r*=r,this.g*=r,this.b*=r,this}setScalar(t){let r=Number(t)||0;return this.setRGB(r,r,r)}setHex(t){let r=Math.floor(t);return this.r=Qe((r>>16&255)/255),this.g=Qe((r>>8&255)/255),this.b=Qe((r&255)/255),this}setRGB(t,r,i){return this.r=Number(t),this.g=Number(r),this.b=Number(i),this}convertSRGBToLinear(){return this.r=Qe(this.r),this.g=Qe(this.g),this.b=Qe(this.b),this}convertLinearToSRGB(){return this.r=Br(this.r),this.g=Br(this.g),this.b=Br(this.b),this}getHex(){let t=r=>Math.round(Br(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.r=t.r,this.g=t.g,this.b=t.b,this}equals(t){return t.r===this.r&&t.g===this.g&&t.b===this.b}clone(){return new Vo(this.r,this.g,this.b)}},Qi={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 Oo{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,s){let n=t*this.itemSize;return this.array[n]=r,this.array[n+1]=i,this.array[n+2]=s,this.needsUpdate=!0,this}setUsage(t){return this}clone(){let t=this.array?.constructor||Float32Array;return new Oo(new t(this.array),this.itemSize)}},Ji=class extends $e{constructor(e,t){super(e instanceof Float32Array?e:new Float32Array(e),t)}},es=class extends $e{constructor(e,t){super(e instanceof Uint16Array?e:new Uint16Array(e),t)}},ts=class extends $e{constructor(e,t){super(e instanceof Uint32Array?e:new Uint32Array(e),t)}},Ve=class Uo{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=t.count,i=new Float32Array(r*3),s=new be,n=new be,l=new be,a=new be,o=new be,u=this.index?.array,h=u?u.length:r;for(let c=0;c<h;c+=3){let f=u?u[c]:c,p=u?u[c+1]:c+1,m=u?u[c+2]:c+2;s.set(t.getX(f),t.getY(f),t.getZ(f)),n.set(t.getX(p),t.getY(p),t.getZ(p)),l.set(t.getX(m),t.getY(m),t.getZ(m)),a.subVectors(l,n),o.subVectors(s,n),a.cross(o).normalize();for(let g of[f,p,m])i[g*3]+=a.x,i[g*3+1]+=a.y,i[g*3+2]+=a.z}for(let c=0;c<r;c++){let f=i[c*3],p=i[c*3+1],m=i[c*3+2],g=Math.hypot(f,p,m)||1;i[c*3]=f/g,i[c*3+1]=p/g,i[c*3+2]=m/g}return this.setAttribute("normal",new $e(i,3)),this}setFromBuffers(t,r,i,s){this.setAttribute("position",new $e(t,3)),this.setAttribute("normal",new $e(r,3)),this.setAttribute("uv",new $e(i,2)),this.setIndex(s)}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 be(1/0,1/0,1/0),i=new be(-1/0,-1/0,-1/0);if(t&&t.count>0)for(let s=0;s<t.count;s++){let n=t.getX(s),l=t.getY(s),a=t.getZ(s);n<r.x&&(r.x=n),l<r.y&&(r.y=l),a<r.z&&(r.z=a),n>i.x&&(i.x=n),l>i.y&&(i.y=l),a>i.z&&(i.z=a)}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 s=i.array;for(let n=0;n<s.length;n+=3)t(s,n);i.needsUpdate=!0,r&&this.computeVertexNormals(),this.computeBoundingBox()}return this}translate(t=0,r=0,i=0){return this._xform((s,n)=>{s[n]+=t,s[n+1]+=r,s[n+2]+=i})}scale(t=1,r=1,i=1){return this._xform((s,n)=>{s[n]*=t,s[n+1]*=r,s[n+2]*=i},!0)}_rot(t,r,i){let s=Math.cos(i),n=Math.sin(i);for(let l of[this.attributes.position,this.attributes.normal]){if(!l)continue;let a=l.array;for(let o=0;o<a.length;o+=3){let u=a[o+t],h=a[o+r];a[o+t]=u*s-h*n,a[o+r]=u*n+h*s}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 be;for(let s=0;s<r.count;s++)i.set(r.getX(s),r.getY(s),r.getZ(s)).applyMatrix4(t),r.setXYZ(s,i.x,i.y,i.z);this.computeVertexNormals()}return this}clone(){let t=new Uo;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(){}},zr=class extends Ve{constructor(e=1,t=1,r=1){super();let i=e/2,s=t/2,n=r/2,l=[-i,-s,n,i,-s,n,i,s,n,-i,s,n,i,-s,-n,-i,-s,-n,-i,s,-n,i,s,-n,-i,s,n,i,s,n,i,s,-n,-i,s,-n,-i,-s,-n,i,-s,-n,i,-s,n,-i,-s,n,i,-s,n,i,-s,-n,i,s,-n,i,s,n,-i,-s,-n,-i,-s,n,-i,s,n,-i,s,-n],a=[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],o=[],u=[];for(let h=0;h<6;h++){let c=h*4;o.push(0,0,1,0,1,1,0,1),u.push(c,c+1,c+2,c,c+2,c+3)}this.setFromBuffers(l,a,o,u)}},rs=class extends Ve{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 s=[],n=[],l=[],a=[];for(let o=0;o<=i;o++){let u=o/i;for(let h=0;h<=r;h++){let c=h/r;if(s.push((c-.5)*e,(.5-u)*t,0),n.push(0,0,1),l.push(c,1-u),o>0&&h>0){let f=(r+1)*o+h-1,p=f-(r+1);a.push(p,f,p+1,f,f+1,p+1)}}}this.setFromBuffers(s,n,l,a)}},is=class extends Ve{constructor(e=1,t=16,r=12){super(),t=Math.max(3,Math.floor(t)),r=Math.max(2,Math.floor(r));let i=[],s=[],n=[],l=[];for(let a=0;a<=r;a++){let o=a/r;for(let u=0;u<=t;u++){let h=u/t,c=h*Math.PI*2,f=o*Math.PI,p=-Math.cos(c)*Math.sin(f),m=Math.cos(f),g=Math.sin(c)*Math.sin(f);if(i.push(e*p,e*m,e*g),s.push(p,m,g),n.push(h,1-o),a>0&&u>0){let x=(t+1)*a+u,b=x-(t+1),v=b-1,d=x-1;a!==1&&l.push(b,v,x),a!==r&&l.push(v,d,x)}}}this.setFromBuffers(i,s,n,l)}},$r=class extends Ve{constructor(e=1,t=1,r=1,i=16){super(),i=Math.max(3,Math.floor(i));let s=[],n=[],l=[],a=[],o=r/2;for(let h=0;h<=1;h++){let c=h,f=h===0?e:t,p=h===0?o:-o;for(let m=0;m<=i;m++){let g=m/i,x=g*Math.PI*2,b=Math.sin(x),v=Math.cos(x);s.push(f*b,p,f*v),n.push(b,0,v),l.push(g,1-c)}}for(let h=0;h<i;h++){let c=h,f=h+i+1,p=h+i+2,m=h+1;a.push(c,f,m,f,p,m)}let u=(h,c)=>{if(h<=0)return;let f=c*o,p=s.length/3;s.push(0,f,0),n.push(0,c,0),l.push(.5,.5);let m=s.length/3;for(let g=0;g<=i;g++){let x=g/i*Math.PI*2,b=Math.sin(x),v=Math.cos(x);s.push(h*b,f,h*v),n.push(0,c,0),l.push(v*.5+.5,.5+c*b*.5)}for(let g=0;g<i;g++)a.push(p,m+g+(c>0?0:1),m+g+(c>0?1:0))};u(e,1),u(t,-1),this.setFromBuffers(s,n,l,a)}},ss=class extends $r{constructor(e=1,t=1,r=16){super(0,e,t,r)}},ns=class extends Ve{constructor(e=1,t=.4,r=12,i=48,s=Math.PI*2){super(),r=Math.max(3,Math.floor(r)),i=Math.max(3,Math.floor(i));let n=[],l=[],a=[],o=[];for(let u=0;u<=r;u++){let h=u/r*Math.PI*2,c=Math.cos(h),f=Math.sin(h);for(let p=0;p<=i;p++){let m=p/i*s,g=Math.cos(m),x=Math.sin(m);if(n.push((e+t*c)*g,(e+t*c)*x,t*f),l.push(c*g,c*x,f),a.push(p/i,u/r),u>0&&p>0){let b=(i+1)*u+p-1,v=b-(i+1);o.push(b,v,b+1,v,v+1,b+1)}}}this.setFromBuffers(n,l,a,o)}};function Pa(e,t,r,i,s){let n=Math.max(2,Math.min(256,Math.floor(Number(t)||64))),l=Math.max(3,Math.min(64,Math.floor(Number(r)||8))),a=Number(i)||.1,o=[],u=[],h=[],c=[],f=new be,p=new be,m=new be,g=new be,x=new be;for(let v=0;v<=n;v++){let d=v/n;s(Math.max(0,d-.001),f),s(Math.min(1,d+.001),p),m.subVectors(p,f).normalize(),v===0&&g.set(Math.abs(m.y)>.9?1:0,Math.abs(m.y)>.9?0:1,0),x.crossVectors(m,g).normalize(),g.crossVectors(x,m).normalize(),s(d,f);for(let y=0;y<=l;y++){let M=y/l*Math.PI*2,T=-a*Math.cos(M),V=a*Math.sin(M),q=T*g.x+V*x.x,P=T*g.y+V*x.y,R=T*g.z+V*x.z;o.push(f.x+q,f.y+P,f.z+R);let C=Math.hypot(q,P,R)||1;u.push(q/C,P/C,R/C),h.push(d,y/l)}}let b=l+1;for(let v=1;v<=n;v++){let d=b*(v-1),y=d+b;for(let M=1;M<=l;M++){let T=d+M-1,V=y+M-1;c.push(T,V,d+M,V,y+M,d+M)}}e.setFromBuffers(o,u,h,c)}var as=class extends Ve{constructor(e=1,t=.4,r=64,i=8,s=2,n=3){super(),r=Math.floor(r),i=Math.floor(i),Pa(this,r,i,t,(l,a)=>{let o=l*s*Math.PI*2,u=n/s*o,h=e*(2+Math.cos(u))*.5;a.set(h*Math.cos(o),h*Math.sin(o),e*Math.sin(u)*.5)})}},Ct=class{getPoint(e,t=new be){return t}getPointAt(e,t=new be){return this.getPoint(e,t)}getTangent(e,t=new be){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)}},os=class extends Ct{constructor(e=new be,t=new be){super(),this.v1=e,this.v2=t}getPoint(e,t=new be){return t.lerpVectors(this.v1,this.v2,e)}},ls=class extends Ct{constructor(e=new be,t=new be,r=new be){super(),this.v0=e,this.v1=t,this.v2=r}getPoint(e,t=new be){return t.lerpVectors(this.v0,this.v1,e).lerp(new be().lerpVectors(this.v1,this.v2,e),e)}},us=class extends Ct{constructor(e=new be,t=new be,r=new be,i=new be){super(),this.v0=e,this.v1=t,this.v2=r,this.v3=i}getPoint(e,t=new be){let r=new be().lerpVectors(this.v0,this.v1,e),i=new be().lerpVectors(this.v1,this.v2,e),s=new be().lerpVectors(this.v2,this.v3,e);return t.lerpVectors(r.lerp(i,e),i.lerp(s,e),e)}},hs=class extends Ct{constructor(e=[],t=!1){super(),this.points=Array.isArray(e)?e:[],this.closed=!!t}getPoint(e,t=new be){let r=this.points,i=r.length;if(!i)return t.set(0,0,0);if(i===1)return t.copy(r[0]);let s=(this.closed?i:i-1)*Math.max(0,Math.min(1,Number(e)||0)),n=Math.floor(s),l=s-n;!this.closed&&n>=i-1&&(n=i-2,l=1);let a=g=>r[this.closed?(g%i+i)%i:Math.max(0,Math.min(i-1,g))],o=a(n-1),u=a(n),h=a(n+1),c=a(n+2),f=l*l,p=f*l,m=(g,x,b,v)=>.5*(2*x+(b-g)*l+(2*g-5*x+4*b-v)*f+(3*x-g-3*b+v)*p);return t.set(m(o.x,u.x,h.x,c.x),m(o.y,u.y,h.y,c.y),m(o.z,u.z,h.z,c.z))}},Gr=class extends Ve{constructor(e=[new it(0,-.5),new it(.5,0),new it(0,.5)],t=12,r=0,i=Math.PI*2){super();let s=Array.isArray(e)&&e.length>=2?e:[new it(.2,0),new it(.2,.5)],n=Math.max(3,Math.min(128,Math.floor(Number(t)||12))),l=[],a=[],o=[],u=[],h=s.length;for(let c=0;c<=n;c++){let f=c/n,p=r+f*i,m=Math.sin(p),g=Math.cos(p);for(let x=0;x<h;x++){let b=s[x],v=Number(b?.x)||0,d=Number(b?.y)||0;l.push(v*m,d,v*g);let y=s[Math.max(0,x-1)],M=s[Math.min(h-1,x+1)],T=(Number(M?.x)||0)-(Number(y?.x)||0),V=(Number(M?.y)||0)-(Number(y?.y)||0),q=Math.hypot(V,T)||1;a.push(V/q*m,-T/q,V/q*g),o.push(f,x/(h-1))}}for(let c=0;c<n;c++){let f=c*h;for(let p=0;p<h-1;p++){let m=f+p,g=f+h+p;u.push(m,g,m+1,g,g+1,m+1)}}this.setFromBuffers(l,a,o,u)}},cs=class extends Ve{constructor(e,t=64,r=1,i=8,s=!1){super(),Pa(this,t,i,r,(n,l)=>{let a=e?.getPointAt??e?.getPoint;if(typeof a=="function"){let o=a.call(e,n,l);o&&o!==l&&l.copy(o)}else l.set(0,n,0)})}},Hr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",pr=class{constructor(e=""){this.isTexture=!0,this.wrapS=10497,this.wrapT=10497,this.repeat=new it(1,1),this.offset=new it(0,0),this.image=null,this.width=0,this.height=0,this.source=e,e&&typeof e=="object"&&(this.image=e)}dispose(){}},ms=class extends pr{constructor(e=null,t=1,r=1,i=1023,s=1009,n,l=1001,a=1001,o=1003,u=1003,h=1,c=""){super(""),this.isDataTexture=!0,this.avgColor=[1,1,1,1],this.flipY=!1,this.generateMipmaps=!1,this.unpackAlignment=1;let f=Number(t),p=Number(r),m=e&&typeof e.length=="number"?e:null;this.width=f,this.height=p,this.image={data:m,width:f,height:p},this.format=Number(i)||1023,this.type=Number(s)||1009,this.wrapS=Number(l)||1001,this.wrapT=Number(a)||1001,this.magFilter=Number(o)||1003,this.minFilter=Number(u)||1003,this.colorSpace=c||"",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 s=Math.max(1,r|0),n=Math.max(1,i|0),l=s*n,a=this.format,o=a===1021||a===1024||a===1028||t.length===l?1:a===1025||a===1030||t.length===l*2?2:a===1022||t.length===l*3?3:4,u=this.type===1015||this.type===1016||t instanceof Float32Array||t instanceof Float64Array,h=Math.min(s,96),c=Math.min(n,96),f=c*(1+h*4),p=new Uint8Array(68+f),m=new DataView(p.buffer);m.setUint32(0,2303741511),m.setUint32(4,218765834),m.setUint32(8,13),m.setUint32(12,1229472850),m.setUint32(16,h),m.setUint32(20,c),p[24]=8,p[25]=6,m.setUint32(29,Xi(p.subarray(12,29))),m.setUint32(33,f+11),m.setUint32(37,1229209940),p[41]=120,p[42]=1,p[43]=1,m.setUint16(44,f,!0),m.setUint16(46,~f&65535,!0);let g=48,x=1,b=0,v=0,d=0,y=0,M=0,T=R=>{if(!Number.isFinite(R))return 0;let C=u&&R<=1?R*255:R;return C>0?C<255?C+.5|0:255:0};for(let R=0;R<c;R++){let C=R*n/c|0,B=this.flipY?n-1-C:C;p[g++]=0,b+=x;for(let L=0;L<h;L++){let w=(B*s+(L*s/h|0))*o,ie=a===1021?255:T(t[w]??0),oe=o>=3||a===1030?T(t[w+1]??0):ie,k=o>=3?T(t[w+2]??0):a===1030?0:ie,J=o===4?T(t[w+3]??255):a===1021?T(t[w]??255):a===1025?T(t[w+1]??255):255;p[g++]=ie,x+=ie,b+=x,p[g++]=oe,x+=oe,b+=x,p[g++]=k,x+=k,b+=x,p[g++]=J,x+=J,b+=x,v+=ie,d+=oe,y+=k,M+=J}x%=65521,b%=65521}m.setUint32(g,(b<<16|x)>>>0),m.setUint32(g+4,Xi(p.subarray(37,g+4))),m.setUint32(g+12,1229278788),m.setUint32(g+16,2923585666);let V=h*c*255,q=this.colorSpace==="srgb-linear";this.avgColor=[q?v/V:Qe(v/V),q?d/V:Qe(d/V),q?y/V:Qe(y/V),M/V];let P=["data:image/png;base64,"];for(let R=0;R<p.length;R+=3){let C=p[R]<<16|(p[R+1]??0)<<8|(p[R+2]??0);P.push(Hr[C>>18&63]+Hr[C>>12&63]+(R+1<p.length?Hr[C>>6&63]:"=")+(R+2<p.length?Hr[C&63]:"="))}this.source=P.join("")}},fs=class{load(e,t){let r=new pr(e);return t?.(r),r}};function We(e,t){return e!==void 0?Number(e):t}function ps(e,t){return e!==void 0?!!e:t}var et=class{constructor(e={}){this.name=e.name||"",this.color=new ot(e.color!==void 0?e.color:16777215),this.emissive=new ot(e.emissive!==void 0?e.emissive:0),this.emissiveIntensity=We(e.emissiveIntensity,1),this.roughness=We(e.roughness,.5),this.metalness=We(e.metalness,0),this.opacity=We(e.opacity,1),this.transparent=ps(e.transparent,!1),this.wireframe=ps(e.wireframe,!1),this.side=We(e.side,2),this.doubleSided=ps(e.doubleSided,!0),this.map=e.map||null,this.clearcoat=We(e.clearcoat,0),this.clearcoatRoughness=We(e.clearcoatRoughness,0),this.sheen=We(e.sheen,0),this.sheenColor=new ot(e.sheenColor!==void 0?e.sheenColor:0),this.sheenRoughness=We(e.sheenRoughness,0),this.transmission=We(e.transmission,0),this.thickness=We(e.thickness,0),this.attenuationColor=new ot(e.attenuationColor!==void 0?e.attenuationColor:16777215),this.attenuationDistance=We(e.attenuationDistance,1/0),this.ior=We(e.ior,1.5),this.dispersion=We(e.dispersion,0),this.iridescence=We(e.iridescence,0),this.iridescenceIOR=We(e.iridescenceIOR,1.3)}dispose(){}},Qt=class extends et{},ds=class extends et{},gs=class extends et{},ys=class extends et{},bs=class extends et{},lt=class Bo{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 be,this.rotation=new Or,this.quaternion=new Ur,this.scale=new be(1,1,1),this.matrix=new It,this.matrixWorld=new It,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)))),s=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,s)})}add(...t){for(let r of t)r&&r instanceof Bo&&(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 s=i.pop();if(!s||typeof s!="object"||r.has(s))continue;r.add(s),t(s);let n=s.children;if(Array.isArray(n))for(let l=n.length-1;l>=0;l--)i.push(n[l])}}updateMatrix(){this.matrix.compose(this.position,this.quaternion,this.scale)}updateMatrixWorld(t=!1){this.traverse(r=>{Ra(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 s=typeof t=="object"?t:new be(t,r,i);this.target instanceof be?this.target.copy(s):this.target?.position instanceof be&&this.target.position.copy(s),this.updateMatrixWorld(!0);let n=new It;n.lookAt(this.position,s,new be(0,1,0));let l=n.elements,a=l[0],o=l[4],u=l[8],h=l[1],c=l[5],f=l[9],p=l[2],m=l[6],g=l[10],x=a+c+g;if(x>0){let b=.5/Math.sqrt(x+1);this.quaternion.set((m-f)*b,(u-p)*b,(h-o)*b,.25/b)}}translateOnAxis(t,r){let i=t.clone().applyMatrix4(new It().makeRotationFromQuaternion(this.quaternion)).multiplyScalar(r);return this.position.add(i),this}translateX(t){return this.translateOnAxis(new be(1,0,0),t)}translateY(t){return this.translateOnAxis(new be(0,1,0),t)}translateZ(t){return this.translateOnAxis(new be(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}clone(t=!0){let r=this instanceof Ft?new this.constructor(this._sourceGeo||this.geometry,this.material):this instanceof pt?new pt(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}},xs=class extends lt{},pt=class extends lt{constructor(e,t){super(),this.isMesh=!0;let r=Array.isArray(t)?t[0]:t;this.geometry=e instanceof Ve?e:e?(Lt("unsupported geometry","BoxGeometry"),new zr(.5,.5,.5)):new Ve,this.material=r instanceof et?r:r?(Lt("unsupported material","MeshStandardMaterial"),new Qt({color:13421772})):new Qt}};function Ra(e){typeof e?._bakeAuthorGeometry=="function"&&e._bakeAuthorGeometry();let t=Se().materializeDeclarativeGeometry;typeof t=="function"&&t(e)}var Jt=1e4,jr=class extends pt{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>Jt)throw new RangeError(`SecurityError: InstancedMesh count (${String(r)}) exceeds MAX_INSTANCES_PER_MESH (${Jt})`);this.count=Math.floor(i);let s=new Float32Array(this.count*16);for(let n=0;n<this.count;n++){let l=n*16;s[l]=1,s[l+5]=1,s[l+10]=1,s[l+15]=1}this.instanceMatrix=new $e(s,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,s=r*16;if(!(s+16>i.length))for(let n=0;n<16;n++){let l=Number(t.elements[n]);i[s+n]=Number.isFinite(l)?l:n%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,s=r*16;if(!(s+16>i.length))for(let n=0;n<16;n++)t.elements[n]=i[s+n]}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 n=new Float32Array(this.count*3);n.fill(1),this.instanceColor=new $e(n,3)}let i=this.instanceColor.array,s=r*3;i[s]=Number.isFinite(t.r)?t.r:1,i[s+1]=Number.isFinite(t.g)?t.g:1,i[s+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,s=r*3;t.setRGB(i[s],i[s+1],i[s+2])}dispose(){}},er=class extends lt{constructor(e=16777215,t=1){super(),this.color=new ot(e),this.intensity=Number(t),this.type="directional"}},Wr=class extends er{constructor(e,t){super(e,t),this.type="ambient"}},vs=class extends er{constructor(e,t){super(e,t),this.target=new lt,this.type="directional"}},Xr=class extends er{constructor(e,t,r=0,i=2){super(e,t),this.type="point",this.distance=r,this.decay=i}},qr=class extends lt{},Ms=class extends qr{constructor(e=45,t=1,r=.1,i=1e3){super(),this.target=new be(0,0,0),this.fov=Number(e),this.aspect=Number(t),this.near=Number(r),this.far=Number(i)}},Kr=class extends lt{constructor(){super(...arguments),this.background=null,this.environmentIntensity=1}toCanvas3D(){return dt.validate(this),Zt(this)}toGLB(){return dt.validate(this),mr(this)}toUSDZ(){return dt.validate(this),fr(this)}getMeshTransforms(){this.updateMatrixWorld(!0);let e=new Map,t=0;return this.traverse(r=>{if(r instanceof pt){let i=new Float32Array(r.matrixWorld.elements);e.set(t,i),r.name&&e.set(r.name,i),t++}}),e}},Yr=Zt,Zr=mr,ws=fr,dt=class{static validate(e){let t=0,r=0,i=0,s=new Set,n=(a,o,u)=>{throw new Error(`SecurityError: Scene exceeds SECURITY_3D_MAX_${a} (${o}). Found: ${u}`)},l=(a,o)=>{if(!Number.isFinite(o))throw new Error(`SecurityError: Scene reports a non-finite ${a} count (${String(o)}), which cannot be bounds-checked.`);return o};e.traverse(a=>{if(Ra(a),a instanceof pt||a.geometry?.attributes?.position?.count){if(i++,i>1e3&&n("MESHES",1e3,i),a instanceof jr){let u=l("instance",a.count);(u<0||u>Jt)&&n("INSTANCES",Jt,u)}let o=a.geometry;if(o){let u=0;if(o.attributes.position&&(u=l("vertex",o.attributes.position.count),t+=u,t>1e5&&n("VERTICES",1e5,t)),o.index){let h=l("index",o.index.count);r+=h,r>3e5&&n("INDICES",3e5,r);let c=o.index.array;if(c&&u>0){let f=Math.min(h,c.length);for(let p=0;p<f;p++){let m=c[p];if(!Number.isFinite(m)||m<0||m>=u)throw new Error(`SecurityError: Index buffer value (${String(m)}) out of vertex bounds [0, ${u}).`)}}}}if(a.material){let u=a.material;u.map&&s.add(u.map),u.normalMap&&s.add(u.normalMap),u.roughnessMap&&s.add(u.roughnessMap)}}}),s.size>16&&n("TEXTURES",16,s.size);for(let a of s){let o=a,u=o.image,h=Number(u?.width??o.width??0)||0,c=Number(u?.height??o.height??0)||0;(!Number.isFinite(h)||!Number.isFinite(c)||h>2048||c>2048)&&n("TEXTURE_DIMENSION",2048,Math.max(h,c))}}},Ss=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 ot(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){dt.validate(e);let i=(s,n)=>{typeof self<"u"&&typeof self.postMessage=="function"&&(n&&n.length?self.postMessage(s,n):self.postMessage(s))};if(this.hasInitialModelRendered){let s=e.getMeshTransforms(),n={};for(let[l,a]of s.entries())n[l]=Array.from(a);i({type:"3D_UPDATE_TRANSFORMS",containerId:this.containerId,transforms:n})}else{this.hasInitialModelRendered=!0;let s=Yr(e),n=Zr(e),l=(s.lights||[]).map(a=>({type:a.type,color:a.color,intensity:a.intensity,position:a.position}));i({type:"3D_MODEL_READY",containerId:this.containerId,glbBuffer:n.buffer,dynamicLights:l,camera:t?{fov:t.fov||60,position:[t.position.x,t.position.y,t.position.z]}:void 0},[n.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 Ca(){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 As=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=Ca(),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=Ca();e=(t-this.oldTime)/1e3,this.oldTime=t,this.elapsedTime+=e}return e}};function Ll(){}var tr=new Proxy(Ll,{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:tr},getPrototypeOf:()=>null,setPrototypeOf:()=>!1,apply:()=>tr,construct:()=>tr}),Ea=(()=>{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 Qr(){return typeof document<"u"&&document.baseURI?document.baseURI:typeof location<"u"&&location.href?location.href:"https://localhost/"}function kt(e,t){if(!e||typeof e!="string")return!1;let r=e.trim();if(!r)return!1;try{let i=new URL(r,Qr());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 La,dr;function Ts(e){if(!kt(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(dr===void 0||La!==t){La=t;try{dr=t.createPolicy("three-live#worker",{createScriptURL:r=>{if(!kt(r))throw new TypeError(`SecurityError: Disallowed Three-Live worker script URL "${r}".`);return r}})}catch{dr=null}}return dr?dr.createScriptURL(e):e}function Na(e){Se().sandboxEngineSrc=e}function Jr(){let e=Se().sandboxEngineSrc;if(e)return e;if(Ea)return Ea;try{if(typeof document>"u")return null;let t=Qr(),r=Array.from(document.querySelectorAll("script[src]"));for(let i of r){let s=i.src;if(!s)continue;let n=new URL(s,t).pathname;if(/(?:^|\/)(?:three|xr)-live[^/]*\.js$/.test(n)&&kt(s,{requireSameOrigin:!0}))return s}}catch{}return null}function Ps(e,t){if(!kt(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,Qr()).href}function Nl(){let e=Jr();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 Ps(e,"sandbox engine")}function _a(e){Se().sandboxIframeSrc=e}function Rs(){let e=Se().sandboxIframeSrc;if(e)return e;let t=Jr();if(!t||!kt(t))return null;let r=new URL(t,Qr());return r.protocol==="blob:"?null:new URL("three-live-sandbox.html",r).href}function _l(){let e=Rs();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 Ps(e,"sandbox iframe")}function Da(e){Se().allowClientScripts=e}function Cs(){return!!Se().allowClientScripts}function Dl(e){return Ps(e,"procedural scene script")}var Il=["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 kl(e,t){let r=self,i=e.nonce,s=e.engineSrc,n=e.allowedScriptUrl,l=e.allowClientScripts,a=e.revoked,o=r.postMessage.bind(r);function u(d){o({type:"ERROR",nonce:i,message:String(d)})}let h=typeof r.importScripts=="function"?r.importScripts.bind(r):null,c=n,f=null;try{let d=s;if(typeof r.trustedTypes<"u"&&r.trustedTypes&&typeof r.trustedTypes.createPolicy=="function")try{let y={createScriptURL:function(T){if(T!==s&&(!n||T!==n))throw new TypeError("Disallowed worker importScripts URL");return T}};l&&(y.createScript=function(T){return String(T)});let M=r.trustedTypes.createPolicy("three-live#worker-boot",y);d=M.createScriptURL(s),n&&(c=M.createScriptURL(n)),l&&typeof M.createScript=="function"&&(f=M.createScript.bind(M))}catch{}h(d)}catch(d){u('Sandbox failed to load the Three-Live engine from "'+s+'". It must be a same-origin (or CORS-enabled) IIFE bundle such as three-live.min.js. Underlying error: '+(d&&d.message||d));return}let p=r.THREE;if(!p||typeof p.Scene!="function"){u('Sandbox loaded "'+s+'" 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 d=r.__THREE_LIVE_REGISTRY__;for(let y=0;y<t.length;y++)if(typeof t[y]=="function")try{t[y](p,d)}catch{}}function m(d,y,M){let T=r;for(;T&&T!==Object.prototype;){if(!M&&T!==r)try{delete T[d]}catch{}if(!M||T===r||Object.prototype.hasOwnProperty.call(T,d))try{Object.defineProperty(T,d,M?{value:y,writable:!1,configurable:!1}:{value:y,writable:!1,configurable:!1,enumerable:!1})}catch{}try{T=Object.getPrototypeOf(T)}catch{break}}}for(let d=0;d<a.length;d++)m(a[d],void 0);m("performance",Object.freeze({now:function(){return Date.now()}}));let g=["3D_MODEL_READY","3D_UPDATE_TRANSFORMS"],x=!1;function b(d,y){if(d.type==="3D_MODEL_READY"){if(x)return;x=!0}d.nonce=i,y&&y.length?o(d,y):o(d)}m("postMessage",function(d,y){if(!d||g.indexOf(d.type)===-1)throw new Error("Sandboxed scripts may only post Three-Live scene messages ("+g.join(", ")+").");b(d,y)},!0);let v=!1;r.onmessage=function(d){let y=d&&d.data;if(!(!y||y.nonce!==i)&&!(y.type!=="EXECUTE"&&y.type!=="EXECUTE_URL")&&!v){v=!0;try{let M=new p.Scene,T=new p.PerspectiveCamera(60,1,.1,1e3),V=new p.WebGLRenderer({isSandboxed:!0});if(y.type==="EXECUTE_URL"){if(!n||y.scriptUrl!==n||typeof h!="function"){u("SecurityError: Refusing to execute unapproved script URL inside sandbox worker.");return}let q=c||n,P=h;if(h=null,c=null,r.THREE=p,r.scene=M,r.camera=T,r.renderer=V,P(q),typeof r.__THREE_LIVE_SCENE__=="function"){let R=r.__THREE_LIVE_SCENE__(p,M,T,V);R&&typeof R.toGLB=="function"&&(M=R)}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 q=f?(0,eval)(f(`(function (THREE, scene, camera, renderer) {
|
|
392
|
+
`,surfaceConnections:y,surfaceInputsUsda:b,usesTime:i.usesTime}}function ci(e,t,r,i){let n=typeof e=="number"&&Number.isFinite(e)?e:i;return Math.max(t,Math.min(r,n))}function Vp(e){return Array.isArray(e)&&e.length>=3&&Number.isFinite(e[0])&&Number.isFinite(e[1])&&Number.isFinite(e[2])}function ko(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Up(e,t=256){return typeof e=="string"&&e.length>0?e.slice(0,t):void 0}function Op(e){let t=ko(e);if(!t)return null;let r=t.target;return{target:Vp(r)?[r[0],r[1],r[2]]:typeof r=="string"&&r.length>0&&r.length<=256?r:[0,0,0],radius:ci(t.radius,.01,50,.5),speed:ci(t.speed,-20,20,.5),height:ci(t.height,-10,10,0),phase:ci(t.phase,-1e6,1e6,0),faceCenter:t.faceCenter===!0}}var jp=["hum","reactor","wind","beacon","geiger","chimeLoop","machinery","water"],Gp=["confirm","error","alarm","warning","pickup","jump","beam","impact","burst","powerup","step","pass","fail"],Lg=new Set(jp),Rg=new Set(Gp);function Ih(e,t){let r=Up(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 $h(e){if(!e||typeof e=="number"&&!(e>0&&Number.isFinite(e)))return null;let t=e===!0?{}:typeof e=="number"?{strength:e}:ko(e);if(!t||t.enabled===!1)return null;let r=ci(t.strength??t.intensity,0,5,.35);return r>0?{enabled:!0,strength:r,threshold:ci(t.threshold,0,4,.8),radius:ci(t.radius,0,2,.5)}:null}function Fo(e){if(!e)return null;let t=e===!0?{}:typeof e=="string"?{color:e}:ko(e);if(!t||t.enabled===!1)return null;let r=t.thickness??t.width;return{enabled:!0,color:Ih(t.color,"#38bdf8"),thickness:ci(typeof r=="number"&&r>0&&r<.25?Math.max(1.5,r*140):r,.5,20,3),pulse:t.pulse===!0}}var ar=class g0{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 g0(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 y0{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 y0(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}},Bo=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}},Ca=class b0{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 b0(this._x,this._y,this._z,this.order)}_onChange(t){return this._onChangeCallback=t,this}},Dn=class x0{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 x0(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}},Ai=class v0{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 v0;return t.copy(this),t}compose(t,r,i){return Sn(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 ft(this.elements,t.elements,r.elements),this}lookAt(t,r,i){return _n(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}},zo=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 rr(this.elements,e.elements),this}},sr=e=>e<=.04045?e/12.92:((e+.055)/1.055)**2.4,Ea=e=>e<=.0031308?e*12.92:1.055*e**(1/2.4)-.055,Dh={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},Br=class w0{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 Dh)this.setHex(Dh[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=>sr(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=sr(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(sr(s(t+1/3)),sr(s(t)),sr(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(sr((r>>16&255)/255),sr((r>>8&255)/255),sr((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(sr(this.r),sr(this.g),sr(this.b))}convertLinearToSRGB(){return this.setRGB(Ea(this.r),Ea(this.g),Ea(this.b))}getHex(){let t=r=>Math.round(Ea(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 w0(this.r,this.g,this.b)}},Vo=1234567,Uo={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&&(Vo=Number.isFinite(e)?e|0:0);let t=Vo=Vo+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}},zt=class M0{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 M0(new t(this.array),this.itemSize)}},Oo=class extends zt{constructor(e,t){super(e instanceof Float32Array||Array.isArray(e)?e:new Float32Array(e),t)}},jo=class extends zt{constructor(e,t){super(e instanceof Uint16Array?e:new Uint16Array(e),t)}},Go=class extends zt{constructor(e,t){super(e instanceof Uint32Array?e:new Uint32Array(e),t)}},$t=class _0{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 zt)this.index=t;else if(Array.isArray(t)){let r=0;for(let i of t)i>r&&(r=i);this.index=new zt(new(r>65535?Uint32Array:Uint16Array)(t),1)}else t&&t.buffer&&(this.index=new zt(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 zt(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 zt(a,3)),this}setFromBuffers(t,r,i,n){this.setAttribute("position",new zt(t,3)),this.setAttribute("normal",new zt(r,3)),this.setAttribute("uv",new zt(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 zt(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 _0;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(){}},La=class extends $t{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)}},Ho=class extends $t{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)}},qo=class extends $t{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)}},Ra=class extends $t{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)}},Wo=class extends Ra{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)}},Ko=class extends $t{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 kh(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,I=R+v;m.push(R,I,R+1,I,I+1,R+1)}}}e.setFromBuffers(l,c,f,m)}var Xo=class extends $t{constructor(e=1,t=.4,r=64,i=8,n=2,a=3){super(),r=Math.floor(r),i=Math.floor(i),kh(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)})}},hi=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)}},Yo=class extends hi{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)}},Qo=class extends hi{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)}},Zo=class extends hi{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)}},Jo=class extends hi{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))}},Ia=class extends $t{constructor(e=[new ar(0,-.5),new ar(.5,0),new ar(0,.5)],t=12,r=0,i=Math.PI*2){super();let n=Array.isArray(e)&&e.length>=2?e:[new ar(.2,0),new ar(.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)}},el=class extends $t{constructor(e,t=64,r=1,i=8,n=!1){super(),kh(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)})}},$a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",kn=class{constructor(e=""){this.isTexture=!0,this.wrapS=10497,this.wrapT=10497,this.repeat=new ar(1,1),this.offset=new ar(0,0),this.image=null,this.width=0,this.height=0,this.source=e,e&&typeof e=="object"&&(this.image=e)}dispose(){}},tl=class extends kn{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 I=0;I<t.length;I+=p)h=Math.imul(h^(t[I]*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,Eo(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=I=>{if(!Number.isFinite(I))return 0;let F=c&&I<=1?I*255:I;return F>0?F<255?F+.5|0:255:0};for(let I=0;I<m;I++){let F=I*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,Eo(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/_:sr(w/_),P?S/_:sr(S/_),P?E/_:sr(E/_),N/_];let R=["data:image/png;base64,"];for(let I=0;I<x.length;I+=3){let F=x[I]<<16|(x[I+1]??0)<<8|(x[I+2]??0);R.push($a[F>>18&63]+$a[F>>12&63]+(I+1<x.length?$a[F>>6&63]:"=")+(I+2<x.length?$a[F&63]:"="))}this.source=R.join("")}},rl=class{load(e,t){let r=new kn(e);return t?.(r),r}};function kt(e,t){return e!==void 0?Number(e):t}function il(e,t){return e!==void 0?!!e:t}var _r=class{constructor(e={}){this.name=e.name||"",this.color=new Br(e.color??16777215),this._em=e.emissive!==void 0,this.emissive=new Br(e.emissive??0),this.emissiveIntensity=kt(e.emissiveIntensity,1),this.roughness=kt(e.roughness,e.roughnessMap?1:.5),this.metalness=kt(e.metalness,e.metalnessMap?1:0),this.opacity=kt(e.opacity,1),this.transparent=il(e.transparent,!1),this.wireframe=il(e.wireframe,!1),this.side=kt(e.side,2),this.doubleSided=il(e.doubleSided,!0),this.map=e.map||null,this.normalMap=e.normalMap||null;let t=e.normalScale;this.normalScale=typeof t=="number"?new ar(t,t):new ar(kt(t?.x,1),kt(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=kt(e.aoMapIntensity,1),this.bumpMap=e.bumpMap||null,this.bumpScale=kt(e.bumpScale,1),this.clearcoat=kt(e.clearcoat,0),this.clearcoatRoughness=kt(e.clearcoatRoughness,0),this.sheen=kt(e.sheen,0),this.sheenColor=new Br(e.sheenColor??0),this.sheenRoughness=kt(e.sheenRoughness,0),this.transmission=kt(e.transmission,0),this.thickness=kt(e.thickness,0),this.attenuationColor=new Br(e.attenuationColor??16777215),this.attenuationDistance=kt(e.attenuationDistance,1/0),this.ior=kt(e.ior,1.5),this.dispersion=kt(e.dispersion,0),this.iridescence=kt(e.iridescence,0),this.iridescenceIOR=kt(e.iridescenceIOR,1.3)}dispose(){}},Gi=class extends _r{},nl=class extends _r{},al=class extends _r{},sl=class extends _r{},ol=class extends _r{},zr=class S0{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 Ca,this.quaternion=new Dn,this.scale=new Ze(1,1,1),this.matrix=new Ai,this.matrixWorld=new Ai,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 S0&&(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=>{Fh(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 Ai;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 Ai().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 Dn){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 Pi?new this.constructor(this._sourceGeo||this.geometry,this.material):this instanceof Yr?new Yr(this.geometry,this.material):new this.constructor;if(this instanceof fi){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 Za&&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}},ll=class extends zr{},Yr=class extends zr{constructor(e,t){super(),this.isMesh=!0;let r=Array.isArray(t)?t[0]:t;this.geometry=e instanceof $t?e:e?(Zr("unsupported geometry","BoxGeometry"),new La(.5,.5,.5)):new $t,this.material=r instanceof _r?r:r?(Zr("unsupported material","MeshStandardMaterial"),new Gi({color:13421772})):new Gi}};function Fh(e){typeof e?._bakeAuthorGeometry=="function"&&e._bakeAuthorGeometry();let t=We().materializeDeclarativeGeometry;typeof t=="function"&&t(e)}var Hi=1e4,Da=class extends Yr{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>Hi)throw new RangeError(`SecurityError: InstancedMesh count (${String(r)}) exceeds MAX_INSTANCES_PER_MESH (${Hi})`);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 zt(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 zt(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(){}},ka=class A0{constructor(){this.mapSize=new ar(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 A0().copy(this)}},fi=class extends zr{constructor(e=16777215,t=1){super(),this.isLight=!0,this.shadow=new ka,this.color=new Br(e),this.intensity=Number(t),this.type="directional"}},Fa=class extends fi{constructor(e,t){super(e,t),this.type="ambient"}},ul=class extends fi{constructor(e,t){super(e,t),this.target=new zr,this.type="directional"}},Ba=class extends fi{constructor(e,t,r=0,i=2){super(e,t),this.type="point",this.distance=r,this.decay=i}},za=class extends zr{},cl=class extends za{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)}},Va=class extends zr{constructor(){super(...arguments),this.background=null,this.environmentIntensity=1}toCanvas3D(){return Qr.validate(this),Vi(this)}toGLB(){return Qr.validate(this),En(this)}toUSDZ(){return Qr.validate(this),In(this)}getMeshTransforms(){this.updateMatrixWorld(!0);let e=new Map,t=0;return this.traverse(r=>{if(r instanceof Yr){let i=new Float32Array(r.matrixWorld.elements);e.set(t,i),r.name&&e.set(r.name,i),t++}}),e}},Ua=Vi,Oa=En,hl=In;We().makePngDeflater=oh;var Qr=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(Fh(o),o instanceof Yr||o.geometry?.attributes?.position?.count){if(i++,i>1e3&&a("MESHES",1e3,i),o instanceof Da){let c=s("instance",o.count);(c<0||c>Hi)&&a("INSTANCES",Hi,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))}}},fl=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 Br(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){Qr.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=Ua(e),a=Oa(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 Bh(){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 ml=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=Bh(),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=Bh();e=(t-this.oldTime)/1e3,this.oldTime=t,this.elapsedTime+=e}return e}};function Hp(){}var qi=new Proxy(Hp,{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:qi},getPrototypeOf:()=>null,setPrototypeOf:()=>!1,apply:()=>qi,construct:()=>qi}),zh=(()=>{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 ja(){return typeof document<"u"&&document.baseURI?document.baseURI:typeof location<"u"&&location.href?location.href:"https://localhost/"}function Ti(e,t){if(!e||typeof e!="string")return!1;let r=e.trim();if(!r)return!1;try{let i=new URL(r,ja());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 Vh,Fn;function pl(e){if(!Ti(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(Fn===void 0||Vh!==t){Vh=t;try{Fn=t.createPolicy("three-live#worker",{createScriptURL:r=>{if(!Ti(r))throw new TypeError(`SecurityError: Disallowed Three-Live worker script URL "${r}".`);return r}})}catch{Fn=null}}return Fn?Fn.createScriptURL(e):e}function Uh(e){We().sandboxEngineSrc=e}function Ga(){let e=We().sandboxEngineSrc;if(e)return e;if(zh)return zh;try{if(typeof document>"u")return null;let t=ja(),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)&&Ti(n,{requireSameOrigin:!0}))return n}}catch{}return null}function dl(e,t){if(!Ti(e))throw new Error(`SecurityError: Disallowed ${t} URL "${e}" (http:, https:, or blob: required).`);return new URL(e,ja()).href}function qp(){let e=Ga();if(!e)throw new Error("SecurityError: Could not locate Three-Live bundle URL for worker sandbox; set ThreeLiveElement.sandboxEngineSrc explicitly.");return dl(e,"sandbox engine")}function Oh(e){We().sandboxIframeSrc=e}function gl(){let e=We().sandboxIframeSrc;if(e)return e;let t=Ga();if(!t||!Ti(t))return null;let r=new URL(t,ja());return r.protocol==="blob:"?null:new URL("three-live-sandbox.html",r).href}function Wp(){let e=gl();if(!e)throw new Error("SecurityError: Could not locate three-live-sandbox.html; set ThreeLiveElement.sandboxIframeSrc explicitly.");return dl(e,"sandbox iframe")}function jh(e){We().allowClientScripts=e}function yl(){return!!We().allowClientScripts}function Kp(e){return dl(e,"procedural scene script")}var Xp="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 Yp(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 I of Object.keys(_)){let F=_[I],V=F&&F.size;R<64&&/^[0-9a-f]{16}$/.test(I)&&(V===256||V===512||V===1024)&&F.rgba instanceof Uint8Array&&F.rgba.length===V*V*4&&(P[I]=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),I=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=I,V(F),typeof i.__THREE_LIVE_SCENE__=="function"){let Y=i.__THREE_LIVE_SCENE__(y,P,R,I);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) {
|
|
343
393
|
return (function () {
|
|
344
|
-
`+
|
|
394
|
+
`+C.script+`
|
|
345
395
|
;
|
|
346
396
|
return typeof scene === "object" && scene ? scene : undefined;
|
|
347
397
|
})();
|
|
348
398
|
})`)):new Function("THREE","scene","camera","renderer",`return (function () {
|
|
349
|
-
`+
|
|
399
|
+
`+C.script+`
|
|
350
400
|
;
|
|
351
401
|
return typeof scene === "object" && scene ? scene : undefined;
|
|
352
|
-
})();`);f=null;let P=q(p,M,T,V);P&&typeof P.toGLB=="function"&&(M=P)}if(!x){p.SceneQuotaValidator&&p.SceneQuotaValidator.validate(M);let q=M.toGLB(),P=q instanceof ArrayBuffer?q:q.buffer.slice(q.byteOffset,q.byteOffset+q.byteLength);b({type:"3D_MODEL_READY",glbBuffer:P},[P])}o({type:"DONE",nonce:i})}catch(M){u(M&&M.message||M)}}},o({type:"READY",nonce:i})}function ei(e,t,r){let i=r?.allowedScriptUrl??null,s=r?.allowClientScripts??i===null,n={nonce:t,engineSrc:e,allowedScriptUrl:i,allowClientScripts:s,revoked:Il},l=(Se().workerExtensionInstallers??[]).map(a=>`(${a.toString()})`).join(",");return`'use strict';(${kl.toString()})(${JSON.stringify(n)},[${l}]);`}function Ia(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 Et=0;function ka(){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 Fl(e){try{return new TextEncoder().encode(e).length}catch{return e.length}}var Vl=1024,Ol=256;function Fa(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 ti(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,Vl)};case"3D_UPDATE_TRANSFORMS":{let i=r.transforms;if(Array.isArray(i)){if(i.length>1e3)return null;for(let s of i)if(!Fa(s))return null;return{type:"3D_UPDATE_TRANSFORMS",transforms:i}}if(i&&typeof i=="object"){let s=Object.keys(i);if(s.length>1e3)return null;let n=Object.create(null),l=i;for(let a of s){if(a.length>Ol||a==="__proto__"||a==="constructor"||a==="prototype")return null;let o=l[a];if(!Fa(o))return null;n[a]=o}return{type:"3D_UPDATE_TRANSFORMS",transforms:n}}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 Ul(e){let t=Fl(e);if(t>1048576)throw new Error(`SecurityError: Script length (${t} bytes) exceeds SECURITY_3D_MAX_SCRIPT_BYTES (1048576).`)}function Va(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 Bl(e,t,r,i){let s=ka(),n=ei(t,s,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,Et++;let a=!1,o=!1,u={modelDispatched:!1},h,c=()=>{if(a||o)return;let g=l.contentWindow;!g||typeof g.postMessage!="function"||(o=!0,g.postMessage(e.kind==="url"?{type:"SANDBOX_RUN",nonce:s,workerSource:n,scriptUrl:e.scriptUrl}:{type:"SANDBOX_RUN",nonce:s,workerSource:n,script:e.script},"*"))},f=()=>{},p=g=>{if(a||!l.contentWindow||g.source!==l.contentWindow)return;let x=g.data;if(x&&typeof x=="object"&&x.type==="IFRAME_READY"){c();return}let b=ti(x,s);b&&Va(b,i,f,u)};f=()=>{a||(a=!0,h!==void 0&&clearTimeout(h),Et=Math.max(0,Et-1),typeof globalThis.removeEventListener=="function"&&globalThis.removeEventListener("message",p),typeof l.remove=="function"?l.remove():l.parentNode&&l.parentNode.removeChild(l))},h=setTimeout(()=>{a||(f(),Ia(i))},3e3),typeof globalThis.addEventListener=="function"&&globalThis.addEventListener("message",p),l.onload=()=>{c()},l.onerror=()=>{f(),i.onError?.(new Error(`Sandbox iframe failed to load "${r}". Verify that three-live-sandbox.html is served at that URL.`))};let m=document.body||document.documentElement;if(!m||typeof m.appendChild!="function"){f();let g=new Error("SecurityError: Cannot mount sandbox iframe because document.body is unavailable.");throw i.onError?.(g),g}return m.appendChild(l),{terminate:f}}function Oa(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(Et>=32)return i(`SecurityError: ${Et} 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 s;try{s=Nl()}catch(f){let p=f instanceof Error?f.message:String(f);return i(p,"Security Error: sandbox engine URL is not configured.")}if(t==="iframe"){let f;try{f=_l()}catch(p){let m=p instanceof Error?p.message:String(p);return i(m,"Security Error: sandbox iframe URL is not configured.")}try{return Promise.resolve(Bl(e,s,f,r))}catch(p){return Promise.reject(p)}}let n=ka(),l=ei(s,n,e.kind==="url"?{allowClientScripts:!1,allowedScriptUrl:e.scriptUrl}:{allowClientScripts:!0,allowedScriptUrl:null}),a;try{let f=new Blob([l],{type:"application/javascript"}),p=URL.createObjectURL(f);try{let m=Ts(p);a=new Worker(m)}finally{URL.revokeObjectURL(p)}}catch(f){let p=f instanceof Error?f.message:String(f);return i(`Failed to initialize Web Worker for sandboxed execution (CSP may block blob workers): ${p}`,"Security Error: Failed to start Worker sandbox.")}Et++;let o=!1,u={modelDispatched:!1},h,c=()=>{o||(o=!0,h!==void 0&&clearTimeout(h),Et=Math.max(0,Et-1),a.terminate())};return h=setTimeout(()=>{o||(c(),Ia(r))},3e3),a.onmessage=f=>{let p=ti(f.data,n);p&&Va(p,r,c,u)},a.onerror=f=>{c(),r.onError?.(new Error(`Worker execution error: ${f.message}`))},e.kind==="url"?a.postMessage({type:"EXECUTE_URL",scriptUrl:e.scriptUrl,nonce:n}):a.postMessage({type:"EXECUTE",script:e.script,nonce:n}),Promise.resolve({terminate:c})}function Ua(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 Ba=e=>(t,r)=>{let i=new Error(t);return e.onError?.(i),r&&e.onToast?.(r),Promise.reject(i)},gr={execute(e,t,r,i){let s=Ba(r),n=Ua(t,s);if(n)return n;try{Ul(e)}catch(l){let a=l instanceof Error?l.message:String(l);return s(a,"Security Error: script exceeds the size limit.")}return i?.allowClientScripts??Cs()?Oa({kind:"script",script:e},t,r,s):s($n,Gn)},executeUrl(e,t,r){let i=Ba(r),s=Ua(t,i);if(s)return s;let n;try{n=Dl(e)}catch(l){let a=l instanceof Error?l.message:String(l);return i(a,"Security Error: disallowed scene script URL.")}return Oa({kind:"url",scriptUrl:n},t,r,i)}},ri=new Set;function Lt(e,t){let r=`[three-live] ${e} is unsupported; degraded to ${t}.`;ri.has(r)||(ri.add(r),typeof console<"u"&&typeof console.warn=="function"&&console.warn(r))}function Es(){return Array.from(ri)}function Ls(){ri.clear()}var ii=class extends Qt{constructor(e={}){Lt("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}},Ns=ii,Nt=class extends Ve{constructor(e=[],t=[],r=1,i=0){super();let s=Number(r)||1,n=Math.max(0,Math.min(7,Math.floor(Number(i)||0))),l=n+1,a=[],o=[],u=[],h=[],c=new be,f=new be,p=new be,m=(b,v)=>v.set(e[b*3]||0,e[b*3+1]||0,e[b*3+2]||0),g=(b,v)=>{let d=b.clone().normalize();a.push(d.x*s,d.y*s,d.z*s),o.push(v.x,v.y,v.z),u.push(Math.atan2(d.z,-d.x)/(2*Math.PI)+.5,1-Math.acos(Math.max(-1,Math.min(1,d.y)))/Math.PI)},x=(b,v,d)=>{let y=a.length/3,M=n===0?new be().subVectors(d,v).cross(new be().subVectors(b,v)).normalize():null;g(b,M||b.clone().normalize()),g(v,M||v.clone().normalize()),g(d,M||d.clone().normalize()),h.push(y,y+1,y+2)};for(let b=0;b<t.length;b+=3){m(t[b],c),m(t[b+1],f),m(t[b+2],p);let v=[];for(let d=0;d<=l;d++){v[d]=[];let y=c.clone().lerp(p,d/l),M=f.clone().lerp(p,d/l),T=l-d;for(let V=0;V<=T;V++)v[d][V]=T===0?y.clone():y.clone().lerp(M,V/T)}for(let d=0;d<l;d++)for(let y=0;y<2*(l-d)-1;y++){let M=y>>1;(y&1)===0?x(v[d][M+1],v[d+1][M],v[d][M]):x(v[d][M+1],v[d+1][M+1],v[d+1][M])}}this.setFromBuffers(a,o,u,h)}},za=Nt,_s=class extends Nt{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)}},si=[1,0,0,-1,0,0,0,1,0,0,-1,0,0,0,1,0,0,-1],$a=[0,2,4,0,4,3,0,3,5,0,5,2,1,2,5,1,5,3,1,3,4,1,4,2],Ds=class extends Nt{constructor(e=1,t=0){super(si,$a,e,t)}},Ie=(1+Math.sqrt(5))/2,Is=class extends Nt{constructor(e=1,t=0){super([-1,Ie,0,1,Ie,0,-1,-Ie,0,1,-Ie,0,0,-1,Ie,0,1,Ie,0,-1,-Ie,0,1,-Ie,Ie,0,-1,Ie,0,1,-Ie,0,-1,-Ie,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)}},tt=1/Ie,ks=class extends Nt{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,-tt,-Ie,0,-tt,Ie,0,tt,-Ie,0,tt,Ie,-tt,-Ie,0,-tt,Ie,0,tt,-Ie,0,tt,Ie,0,-Ie,0,-tt,Ie,0,-tt,-Ie,0,tt,Ie,0,tt],[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)}},Fs=class extends Gr{constructor(e=1,t=1,r=4,i=8){let s=Math.max(1e-4,Number(e)||1),n=Math.max(0,Number.isFinite(Number(t))?Number(t):1)*.5,l=Math.max(2,Math.min(64,Math.floor(Number(r)||4))),a=[];for(let o=-1;o<=1;o+=2)for(let u=0;u<=l;u++){if(o>0&&u===0&&n===0)continue;let h=(o<0?u/l-1:u/l)*(Math.PI/2);a.push(new it(Math.max(0,Math.cos(h)*s),o*n+Math.sin(h)*s))}super(a,Math.max(4,Math.min(128,Math.floor(Number(i)||8))))}},ni=class extends Ve{constructor(e=.5,t=1,r=32,i=1,s=0,n=Math.PI*2){super();let l=Math.max(1e-4,Number(t)||1),a=Number(e),o=Number.isFinite(a)?Math.max(0,a):l*.5,u=Math.max(l,o),h=Math.min(u*.999,Math.min(l,o)),c=Math.max(3,Math.min(256,Math.floor(Number(r)||32))),f=Math.max(1,Math.min(64,Math.floor(Number(i)||1))),p=Number.isFinite(Number(s))?Number(s):0,m=Number.isFinite(Number(n))?Number(n):Math.PI*2,g=[],x=[],b=[],v=[];for(let d=0;d<=f;d++){let y=h+d/f*(u-h);for(let M=0;M<=c;M++){let T=p+M/c*m,V=Math.cos(T),q=Math.sin(T);if(g.push(y*V,y*q,0),x.push(0,0,1),b.push(y/u*V*.5+.5,y/u*q*.5+.5),d<f&&M<c){let P=d*(c+1)+M,R=P+c+1;y>1e-6&&v.push(P,R,P+1),v.push(R,R+1,P+1)}}}this.setFromBuffers(g,x,b,v)}},Vs=class extends ni{constructor(e=1,t=32,r=0,i=Math.PI*2){super(0,e,t,1,r,i)}},ai=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)}},yr=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)}},Os=class extends yr{constructor(e={}){super(e),this.dashSize=Number(e.dashSize)||3,this.gapSize=Number(e.gapSize)||1,this.scale=Number(e.scale)||1}};function Ga(e,t){let r=e?.attributes?.position;if(!r?.array||r.count<3)return new Float32Array(0);let i=r.array,s=e?.index?.array,n=Math.min(8192,Math.floor((s?s.length:r.count)/3)),l=f=>`${Math.round((i[f*3]||0)*1e4)},${Math.round((i[f*3+1]||0)*1e4)},${Math.round((i[f*3+2]||0)*1e4)}`,a=t===void 0,o=a?1:Math.cos(t*Math.PI/180),u={},h=[],c=(f,p)=>h.push(i[f*3]||0,i[f*3+1]||0,i[f*3+2]||0,i[p*3]||0,i[p*3+1]||0,i[p*3+2]||0);for(let f=0;f<n;f++){let p=s?s[f*3]:f*3,m=s?s[f*3+1]:f*3+1,g=s?s[f*3+2]:f*3+2,x=i[p*3]||0,b=i[p*3+1]||0,v=i[p*3+2]||0,d=(i[m*3]||0)-x,y=(i[m*3+1]||0)-b,M=(i[m*3+2]||0)-v,T=(i[g*3]||0)-x,V=(i[g*3+1]||0)-b,q=(i[g*3+2]||0)-v,P=y*q-M*V,R=M*T-d*q,C=d*V-y*T,B=Math.hypot(P,R,C);if(!a&&B<1e-8)continue;B>0&&(P/=B,R/=B,C/=B);let L=[p,m,g];for(let w=0;w<3;w++){let ie=L[w],oe=L[(w+1)%3],k=l(ie),J=l(oe);if(k===J)continue;let z=k<J?`${k}|${J}`:`${J}|${k}`,Y=u[z];Y?Y.m||(Y.m=1,Y.nx*P+Y.ny*R+Y.nz*C<=o&&c(ie,oe)):(u[z]={va:ie,vb:oe,nx:P,ny:R,nz:C,m:a?1:0},a&&c(ie,oe))}}if(!a){let f=Object.keys(u);for(let p=0;p<f.length;p++){let m=u[f[p]];m&&!m.m&&c(m.va,m.vb)}}return new Float32Array(h)}var Us=class extends Ve{constructor(e){super(),this.setAttribute("position",new $e(Ga(e),3)),this.__isSegmentPairs=!0}},Bs=class extends Ve{constructor(e,t=1){super();let r=Number.isFinite(Number(t))?Number(t):1;this.setAttribute("position",new $e(Ga(e,r),3)),this.__isSegmentPairs=!0}};function zl(e,t,r=1){let i=new Ve;i.__baked=!0;let s=e?.attributes?.position;if(!s?.array||s.count<2)return i;let n=s.array,l=e.index?.array,a=e.__isSegmentPairs?"segments":t,o=l?l.length:s.count,u=Math.min(4096,Math.max(0,a==="segments"?Math.floor(o/2):a==="loop"&&o>=3?o:o-1));if(u===0)return i;e.computeBoundingBox();let h=e.boundingBox,c=h&&h.max.distanceTo(h.min)||1,f=Math.max(.0015,Math.min(.025,c*.003))*(.5+.5*Math.max(.5,Math.min(6,Number(r)||1))),p=[],m=[],g=[],x=[];for(let b=0;b<u;b++){let v=a==="segments"?b*2:b,d=a==="segments"?b*2+1:(b+1)%o,y=l?l[v]:v,M=l?l[d]:d,T=n[y*3]||0,V=n[y*3+1]||0,q=n[y*3+2]||0,P=(n[M*3]||0)-T,R=(n[M*3+1]||0)-V,C=(n[M*3+2]||0)-q,B=Math.hypot(P,R,C);if(B<1e-6)continue;let L=P/B,w=R/B,ie=C/B,oe=(Math.abs(w)<.9?Math.hypot(ie,L):Math.hypot(ie,w))||1,k=Math.abs(w)<.9?ie/oe:0,J=Math.abs(w)<.9?0:-ie/oe,z=Math.abs(w)<.9?-L/oe:w/oe,Y=w*z-ie*J,le=ie*k-L*z,he=L*J-w*k,$=p.length/3,U=[[k,J,z],[Y,le,he],[-k,-J,-z],[-Y,-le,-he]];for(let N=0;N<2;N++){let G=T+N*P,D=V+N*R,F=q+N*C;for(let E=0;E<4;E++){let H=U[E];p.push(G+H[0]*f,D+H[1]*f,F+H[2]*f),m.push(H[0],H[1],H[2]),g.push(E/4,N)}}for(let N=0;N<4;N++){let G=(N+1)%4;x.push($+N,$+G,$+4+G,$+N,$+4+G,$+4+N)}}return p.length>0&&i.setFromBuffers(p,m,g,x),i}function $l(e,t=.05){let r=new Ve;r.__baked=!0;let i=e?.attributes?.position;if(!i?.array||i.count<1)return r;let s=i.array,n=i.count,l=Math.min(n,5e3),a=Math.max(.003,Math.min(.25,(Number(t)||.05)*.6)),o=[],u=[],h=[],c=[];for(let f=0;f<l;f++){let p=n<=5e3?f:Math.floor(f*n/l),m=s[p*3]||0,g=s[p*3+1]||0,x=s[p*3+2]||0,b=f*6;for(let v=0;v<6;v++){let d=si[v*3],y=si[v*3+1],M=si[v*3+2];o.push(m+d*a,g+y*a,x+M*a),u.push(d,y,M),h.push(.5,.5)}for(let v=0;v<24;v++)c.push(b+$a[v])}return r.setFromBuffers(o,u,h,c),r}var Ft=class extends pt{constructor(e,t,r="strip"){let i=t&&typeof t=="object"?t:{},s=t instanceof et?t:r==="points"?new ai(i):new yr(i),n=e instanceof Ve?e:new Ve;super(n,s),this.isLine=!0,this._lineMode=r,this._sourceGeo=n}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),s=0,n=0,l=0;for(let a=0;a<i;a++)s+=r[a*3]||0,n+=r[a*3+1]||0,l+=r[a*3+2]||0;this.material.color.setRGB(s/i,n/i,l/i)}}!this.geometry?.__baked&&this._sourceGeo?.attributes?.position?.count>=(e?1:2)&&(this.geometry=e?$l(this._sourceGeo,this.material?.size??.05):zl(this._sourceGeo,this._lineMode,this.material?.linewidth??1))}},zs=class extends Ft{constructor(e,t){super(e,t,"loop"),this.isLineLoop=!0}},$s=class extends Ft{constructor(e,t){super(e,t,"segments"),this.isLineSegments=!0}},Gs=class extends Ft{constructor(e,t){super(e,t,"points"),this.isPoints=!0}},Hs=class extends Xr{constructor(e,t,r=0,i=Math.PI/3,s=0,n=2){super(e,t,r,n),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 a=Number(s);this.penumbra=Number.isFinite(a)?Math.max(0,Math.min(1,a)):0}},oi=class extends Wr{constructor(e,t,r){Lt("HemisphereLight","AmbientLight"),super(e,r),this.groundColor=new ot(t??4473924)}},js=oi,Ha={Vector2:it,Vector3:be,Vector4:Yi,Euler:Or,Quaternion:Ur,Matrix4:It,Matrix3:Zi,Color:ot,MathUtils:Qi,BufferAttribute:$e,Float32BufferAttribute:Ji,Uint16BufferAttribute:es,Uint32BufferAttribute:ts,BufferGeometry:Ve,BoxGeometry:zr,PlaneGeometry:rs,SphereGeometry:is,CylinderGeometry:$r,ConeGeometry:ss,TorusGeometry:ns,TorusKnotGeometry:as,Curve:Ct,Curve3:Ct,LineCurve3:os,QuadraticBezierCurve3:ls,CubicBezierCurve3:us,CatmullRomCurve3:hs,LatheGeometry:Gr,TubeGeometry:cs,PolyhedronGeometry:Nt,IcosahedronGeometry:Is,OctahedronGeometry:Ds,DodecahedronGeometry:ks,TetrahedronGeometry:_s,CapsuleGeometry:Fs,RingGeometry:ni,CircleGeometry:Vs,WireframeGeometry:Us,EdgesGeometry:Bs,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:pr,DataTexture:ms,TextureLoader:fs,Material:et,MeshStandardMaterial:Qt,MeshBasicMaterial:ds,MeshLambertMaterial:gs,MeshPhongMaterial:ys,MeshPhysicalMaterial:bs,PointsMaterial:ai,LineBasicMaterial:yr,LineDashedMaterial:Os,ShaderMaterial:ii,RawShaderMaterial:Ns,Object3D:lt,Group:xs,Mesh:pt,InstancedMesh:jr,Line:Ft,LineLoop:zs,LineSegments:$s,Points:Gs,Light:er,AmbientLight:Wr,DirectionalLight:vs,PointLight:Xr,SpotLight:Hs,HemisphereLight:oi,RectAreaLight:js,Camera:qr,PerspectiveCamera:Ms,Scene:Kr,WebGLRenderer:Ss,Clock:As,SceneQuotaValidator:dt,exportSceneToCanvas3D:Yr,exportSceneToGLB:Zr,exportSceneToUSDZ:ws,generateUSDZ:Fr,glbToUSDZ:kr,sceneToCanvas3D:Zt,sceneToGLB:mr,sceneToUSDZ:fr,authorScriptRunner:gr,getAuthorWarnings:Es,clearAuthorWarnings:Ls};Object.freeze(dt),Object.freeze(dt.prototype),Object.freeze(Kr.prototype),Object.freeze(Ha);var Vt=new Proxy(Ha,{get:(e,t)=>{if(t in e)return e[t];let r=Se().authorNamespace;return r&&typeof t=="string"&&t in r?r[t]:(typeof t=="string"&&t!=="then"&&t!=="toJSON"&&!t.startsWith("__")&&Lt(`THREE.${t}`,"no-op proxy"),tr)},has:(e,t)=>{if(t in e)return!0;let r=Se().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")}}),li=Se();if(li.threeNamespace=Vt,li.workerExtensionInstallers)for(let e of li.workerExtensionInstallers)e(Vt,li);var rr={name:"three_author",THREE:Vt},ja=rr,gt=typeof globalThis<"u"?globalThis:typeof window<"u"?window:void 0;if(typeof gt.THREE>"u"&&(gt.THREE=Vt),typeof gt.requestAnimationFrame!="function"&&(gt.requestAnimationFrame=e=>(typeof e=="function"&&typeof gt.__three_live_raf_cb__!="function"&&(gt.__three_live_raf_cb__=e),gt.__three_live_in_step__||Lt("requestAnimationFrame","single-frame static evaluation"),0)),typeof gt.cancelAnimationFrame!="function"&&(gt.cancelAnimationFrame=()=>{}),typeof window<"u"){let e=window;e.ThreeLive=e.ThreeLive||{},e.ThreeLive.THREE=Vt,e.ThreeLivePlugins=e.ThreeLivePlugins||{},e.ThreeLivePlugins.threeAuthor=rr,e.ThreeLivePlugins.three_author=rr,e.ThreeLivePlugins["three-author"]=rr}function ui(e,t){let r=e?.trim(),i=r?Number(r):NaN;return Number.isFinite(i)?i:t}var Ws=(e,t,r)=>({x:e,y:t,z:r,toString:()=>`${e}m ${t}m ${r}m`}),Gl=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 hi=class qe extends Gl{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 Se().arProvider}static set arProvider(t){Se().arProvider=t}static get scriptRunner(){return Se().scriptRunner}static set scriptRunner(t){Se().scriptRunner=t}static get sandboxEngineSrc(){return Se().sandboxEngineSrc??null}static set sandboxEngineSrc(t){Se().sandboxEngineSrc=t}static get sandboxIframeSrc(){return Se().sandboxIframeSrc??null}static set sandboxIframeSrc(t){Se().sandboxIframeSrc=t}static get allowClientScripts(){return!!Se().allowClientScripts}static set allowClientScripts(t){Se().allowClientScripts=t}static registerScriptRunner(t){qe.scriptRunner=t}static registerDecoder(t,r){Ze.registerDecoder(t,r)}static getDecoder(t){return Ze.getDecoder(t)}static registerAR(t){typeof t=="function"?qe.arProvider={activateAR:t}:qe.arProvider=t,typeof document<"u"&&document.querySelectorAll("three-live").forEach(r=>{r instanceof qe&&r.updateARButtonVisibility()})}static isARSupported(){return!!qe.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 Ze.getRegisteredPlugins())i.onElementConnected?.(this)}disconnectedCallback(){for(let t of Ze.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 s=parseFloat(i);isNaN(s)||this.viewer.setExposure(s)}break;case"shadow-intensity":case"shadow-softness":this.viewer&&this.viewer.setShadow(this.shadowIntensity,this.shadowSoftness);break;case"tone-mapping":this.viewer?.setToneMapping(Kt(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 s=this.cameraControls;this.viewer&&this.viewer.setInteractive?.(s),this.canvas&&(this.canvas.style.touchAction=s?"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 s of Ze.getRegisteredPlugins())s.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")||(Se().sandboxIframeSrc?"iframe":"worker")}set sandbox(t){this.setAttr("sandbox",t)}get allowClientScripts(){return this.getBoolAttr("allow-client-scripts")||qe.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 qe.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 Kt(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 ui(this.getAttr("bloom-threshold"),.62)}set bloomThreshold(t){this.setAttr("bloom-threshold",t)}get bloomRadius(){return ui(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,s){this.viewer&&this.viewer.setCamera(t,r,i,s)}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():Ws(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(s=>{s?r(s):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[s,n,l]=i.hitPoint||i.point,[a,o,u]=i.normal;return{position:Ws(s,n,l),normal:Ws(a,o,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 s;if(typeof t=="string"){let o=await fetch(t,{signal:i.signal});if(!o.ok)throw new Error(`Failed to load "${t}": HTTP ${o.status}`);s=await o.arrayBuffer()}else s=t;i.signal.throwIfAborted();let n=Dt(s);this.viewer.loadGLBData(n,r),this.currentModel=n,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 a=this.getAttr("variant-name");a&&this.selectVariant(a),this.fireEvent("load",{model:n}),this.fireEvent("three-load",{model:n,source:typeof t=="string"?"src":"model"})}catch(s){throw i.signal.aborted||this.emitError(s,"load"),s}}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 s=()=>{i&&(i.style.opacity="1",i.style.transform="translateX(-50%) translateY(0)")};typeof requestAnimationFrame<"u"?requestAnimationFrame(s):s(),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=(s,n=s.message)=>{throw this.fireEvent("ar-status",{status:"failed",error:s}),this.showToast(n,6e3),s};this.currentModel||t(new Error("No 3D model is loaded in <three-live>.")),qe.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 s=await qe.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:n=>{this.activeXRSession=null,this.fireEvent("ar-status",{status:"failed",error:n}),this.showToast(`AR error: ${n.message}`,6e3)}}});if(s.success){s.session&&(this.activeXRSession=s.session);let n=s.mode==="quick-look"?"Opening Apple AR Quick Look...":s.mode==="scene-viewer"?"Opening Google Scene Viewer...":s.mode==="webxr"?"WebXR AR session started.":"";n&&this.showToast(n)}else{let n=typeof navigator<"u"&&navigator.userAgent||"",l=/Macintosh/i.test(n)&&!(typeof navigator<"u"&&navigator.maxTouchPoints>1),a=/Android|iPhone|iPad|iPod/i.test(n),o=s.error?.message||"AR requires an iOS (Quick Look) or Android (WebXR / Scene Viewer) device.";if(l&&!a&&typeof document<"u"&&this.currentModel&&qe.arProvider.createUSDZBlob)try{let u=this.currentModel instanceof Blob&&this.currentModel.type==="model/vnd.usdz+zip"?this.currentModel:qe.arProvider.createUSDZBlob(this.currentModel),h=URL.createObjectURL(u),c=document.createElement("a");c.href=h,c.download="three_live_model.usdz",document.body.appendChild(c),c.click(),document.body.removeChild(c),setTimeout(()=>URL.revokeObjectURL(h),3e3),this.showToast("Downloaded USDZ preview for macOS Quick Look.",5e3)}catch{this.showToast(o,6e3)}else this.showToast(o,6e3);s.error&&this.fireEvent("ar-status",{status:"failed",error:s.error})}return s}catch(s){return this.activeXRSession=null,t(s,`AR error: ${s.message||String(s)}`)}}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")),s=this.parseOrbitLimit(this.getAttr("max-camera-orbit")),n=this.parseCameraTarget(this.getAttr("camera-target")),l=this.parseFieldOfView(this.getAttr("field-of-view"));this.viewer=new Ze(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:n,minCameraOrbit:i,maxCameraOrbit:s,onMeshClick:o=>{this.fireEvent("meshclick",o)},onCameraChange:o=>{this.updateHotspots();for(let u of Ze.getRegisteredPlugins())u.onCameraChange?.(this.viewer,this);this.fireEvent("camera-change",o)}}),this.viewer.setInteractive(this.cameraControls),this.skyboxImage&&this.viewer.setSkyboxImage(this.skyboxImage).catch(()=>{});let a=this.getAttr("camera-orbit");a&&this.applyCameraOrbit(a),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))}createARButton(){if(!(typeof document>"u")){if(!this.arButton){let t=document.createElement("button");t.type="button",t.className="three-live-ar-button";for(let[s,n]of[["aria-label","View in Augmented Reality"],["part","default-ar-button"]])t.setAttribute(s,n);let r="http://www.w3.org/2000/svg";if(typeof document.createElementNS=="function"){let s=document.createElementNS(r,"svg");for(let[l,a]of[["width","20"],["height","20"],["viewBox","0 0 24 24"],["fill","none"],["stroke","currentColor"],["stroke-width","2"],["stroke-linecap","round"],["stroke-linejoin","round"]])s.setAttribute(l,a);s.style.marginRight="6px";let n=document.createElementNS(r,"path");n.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"),s.appendChild(n),t.appendChild(s)}let i=document.createElement("span");i.textContent="View in AR",t.appendChild(i),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",s=>{s.stopPropagation(),this.activateAR()}),this.arButton=t,this.appendChild(t)}this.updateARButtonVisibility()}}updateARButtonVisibility(){let t=this.hasAttribute("ar")&&!!qe.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.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,s]=t.trim().split(/\s+/),n=s&&s!=="auto"?parseFloat(s):NaN;return{theta:r&&r!=="auto"?this.parseFieldOfView(r):void 0,phi:i&&i!=="auto"?this.parseFieldOfView(i):void 0,distance:isNaN(n)?void 0:n}}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 Ze.getRegisteredPlugins())if(t.updateHotspotsForElement){t.updateHotspotsForElement(this,this.viewer);return}}runWithScriptRunner(t){let r=qe.scriptRunner;if(!r){let n=new Error('Script execution requires "three-live/full" or registerScriptRunner().');return this.showToast(n.message),this.emitError(n,"script"),Promise.reject(n)}let i=this.beginLoad(),s=()=>!i.signal.aborted;return new Promise((n,l)=>{let a=()=>l(i.signal.reason);if(i.signal.addEventListener("abort",a,{once:!0}),!s()){a();return}let o={onModelReady:u=>{this.loadModelWithLimits(u,gl,i).then(()=>n(u),l)},onUpdateTransforms:u=>{s()&&this.viewer?.updateMeshTransforms(u)},onError:u=>{s()&&(this.showToast(u.message),this.emitError(u,"script"),l(u))},onToast:u=>{s()&&this.showToast(u)}};t(r,o).then(u=>{s()?this.scriptHandle=u||null:u?.terminate()},u=>{s()&&o.onError?.(u)})})}loadScriptFromSrc(t){return this.runWithScriptRunner((r,i)=>{if(typeof r.executeUrl!="function"){let s=new Error("Registered ScriptRunner does not support executeUrl() for server-generated scripts.");return i.onError?.(s),Promise.reject(s)}return r.executeUrl(t,this.sandbox,i)})}executeScript(t){if(!qe.scriptRunner)return this.runWithScriptRunner(()=>Promise.resolve());if(!this.allowClientScripts){let r=new Error($n);return this.showToast(Gn),this.emitError(r,"security"),Promise.reject(r)}return this.runWithScriptRunner((r,i)=>r.execute(t,this.sandbox,i,{allowClientScripts:!0}))}};hi.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"],hi.registerPlugin=Ze.registerPlugin,hi.getRegisteredPlugins=Ze.getRegisteredPlugins;var ir=hi;typeof customElements<"u"&&!customElements.get("three-live")&&customElements.define("three-live",ir);function Wa(e,t,r){return t%4===0?new Float32Array(e,t,r):new Float32Array(e.slice(t,t+r*4))}function Xs(e,t,r,i){let s=t[0],n=t[1],l=t[2],a=t[3],o=r[0],u=r[1],h=r[2],c=r[3],f=s*o+n*u+l*h+a*c;if(f<0&&(o=-o,u=-u,h=-h,c=-c,f=-f),Math.abs(f)>=1)return e[0]=s,e[1]=n,e[2]=l,e[3]=a,e;let p=Math.acos(f),m=Math.sqrt(1-f*f);if(Math.abs(m)<.001)return e[0]=.5*(s+o),e[1]=.5*(n+u),e[2]=.5*(l+h),e[3]=.5*(a+c),e;let g=Math.sin((1-i)*p)/m,x=Math.sin(i*p)/m;return e[0]=s*g+o*x,e[1]=n*g+u*x,e[2]=l*g+h*x,e[3]=a*g+c*x,e}function Xa(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 qs(e,t){if(!Array.isArray(e?.animations))return[];let r=[];for(let i=0;i<e.animations.length;i++){let s=e.animations[i],n=s.name||`Animation_${i}`,l=[],a=0;if(Array.isArray(s.channels)&&Array.isArray(s.samplers))for(let o of s.channels){if(!o.target||o.target.node===void 0||!o.target.path)continue;let u=s.samplers[o.sampler];if(!u)continue;let h=e.accessors?.[u.input],c=e.accessors?.[u.output];if(!h||!c)continue;let f=e.bufferViews?.[h.bufferView],p=e.bufferViews?.[c.bufferView];if(!f||!p)continue;let m=(f.byteOffset||0)+(h.byteOffset||0),g=(p.byteOffset||0)+(c.byteOffset||0),x=Xt(e,t,h,1)??Wa(t,m,h.count);x.length>0&&x[x.length-1]>a&&(a=x[x.length-1]);let b=o.target.path==="rotation"?4:o.target.path==="weights"?Math.max(1,Math.round(c.count/Math.max(1,h.count))):3,v=o.target.path==="weights"?1:b,d=Xt(e,t,c,v)??Wa(t,g,c.count*v),y=u.interpolation==="STEP"?"STEP":"LINEAR";l.push({nodeIndex:o.target.node,path:o.target.path,times:x,values:d,interpolation:y})}l.length>0&&r.push({name:n,duration:a,channels:l})}return r}function sr(e,t,r){let{times:i,values:s,path:n,interpolation:l}=e,a=i.length;if(a===0)return;let o=n==="rotation"?4:n==="weights"?Math.max(1,Math.round(s.length/a)):3;if(t<=i[0]){for(let v=0;v<o;v++)r[v]=s[v];return}if(t>=i[a-1]){let v=(a-1)*o;for(let d=0;d<o;d++)r[d]=s[v+d];return}let u=0,h=a-1;for(;u<=h;){let v=u+h>>1;i[v]<=t?u=v+1:h=v-1}let c=Math.max(0,h),f=Math.min(a-1,c+1);if(l==="STEP"||c===f){let v=c*o;for(let d=0;d<o;d++)r[d]=s[v+d];return}let p=i[c],m=i[f],g=(t-p)/Math.max(1e-5,m-p),x=c*o,b=f*o;if(n==="rotation"){let v=[s[x],s[x+1],s[x+2],s[x+3]],d=[s[b],s[b+1],s[b+2],s[b+3]];Xs(r,v,d,g)}else for(let v=0;v<o;v++)r[v]=s[x+v]+g*(s[b+v]-s[x+v])}var br=new WeakMap;function Ks(e,t,r=.3){if(!e?.animations)return;let i=e.animations.find(a=>a.name===t);if(!i)return;let s=br.get(e);s||(s=[],e.currentClip&&s.push({clip:e.currentClip,time:e.animationTime||0,weight:1,fadeSpeed:0}),br.set(e,s));let n=r>0?1/r:1e3;for(let a of s)a.clip.name!==t&&(a.fadeSpeed=-n);let l=s.find(a=>a.clip.name===t);l?l.fadeSpeed=n:s.push({clip:i,time:0,weight:r>0?0:1,fadeSpeed:n}),e.currentClip=i,e.isPlayingAnimation=!0}function Ys(e,t){if(!e.gltf||!Array.isArray(e.gltf.nodes))return;let r=br.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,s=[];for(let c=0;c<i;c++){let f=e.initialNodeTransforms[c];f?s.push({t:[f.t[0],f.t[1],f.t[2]],r:[f.r[0],f.r[1],f.r[2],f.r[3]],s:[f.s[0],f.s[1],f.s[2]]}):s.push({t:[0,0,0],r:[0,0,0,1],s:[1,1,1]})}let n=[0,0,0],l=[0,0,0,1],a=[1,1,1],o=new Float32Array(64);for(let c of r){let f=Math.max(0,Math.min(1,c.weight));if(!(f<=1e-4))for(let p of c.clip.channels){if(p.nodeIndex<0||p.nodeIndex>=i)continue;let m=s[p.nodeIndex];if(p.path==="translation")sr(p,c.time,n),Xa(m.t,m.t,n,f);else if(p.path==="rotation")sr(p,c.time,l),Xs(m.r,m.r,l,f);else if(p.path==="scale")sr(p,c.time,a),Xa(m.s,m.s,a,f);else if(p.path==="weights"&&(sr(p,c.time,o),e.meshes)){for(let g of e.meshes)if(g.nodeIndex===p.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 d=0;d<v;d++)b[d]=b[d]*(1-f)+o[d]*f}}}}}let u=[];for(let c=0;c<i;c++){let f=Ee(),{t:p,r:m,s:g}=s[c];or(f,m,p,g),u.push(f)}let h=Rr(e.gltf,u);e.worldMatrices=h;for(let c of e.meshes)c.nodeIndex>=0&&c.nodeIndex<h.length&&(c.transform.set(h[c.nodeIndex]),Ye(c.normalMatrix,c.transform))}var Zs=e=>{br.delete(e)},Qs={name:"keyframes",evaluateAnimation:Ys,crossFadeTo:Ks,onParseGLB(e){!e.animations&&e.gltf?.animations&&(e.animations=qs(e.gltf,e.bin))},onLoadModel:Zs,onClearScene:Zs,onDestroy:(e,t)=>Zs(t),onUpdate(e,t){if(!e.isPlayingAnimation)return;let r=br.get(e);if(r&&r.length>0){for(let i=r.length-1;i>=0;i--){let s=r[i];if(s.time+=t,s.clip.duration>0&&(s.time%=s.clip.duration),s.fadeSpeed!==0)if(s.weight+=s.fadeSpeed*t,s.weight<=0){r.splice(i,1);continue}else s.weight>=1&&(s.weight=1,s.fadeSpeed=0)}r.length>0&&(e.animationTime=r[r.length-1].time),Ys(e,e.animationTime)}else e.currentClip&&(e.animationTime+=t,e.currentClip.duration>0&&(e.animationTime%=e.currentClip.duration),Ys(e,e.animationTime))}},xr=64;function qa(e,t,r){if(!(!e?.meshes||t<0||t>=xr))for(let i of e.meshes)for(let s of i.primitives){let n=s.pluginData?.morph;n?.weights&&(n.weights[t]=r)}}var Js={name:"morph",onResolveShader(e,t,r,i){if(!Array.isArray(e?.targets)||e.targets.length===0)return null;let s=r.replace("uniform mat4 uMVP,uModel;",`uniform mat4 uMVP,uModel;
|
|
402
|
+
})();`);v=null;let V=F(y,P,R,I);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 Ha(e,t,r){let i=r?.allowedScriptUrl??null,n=r?.allowClientScripts??i===null,a={nonce:t,engineSrc:e,allowedScriptUrl:i,allowClientScripts:n,revoked:Xp},s=(We().workerExtensionInstallers??[]).map(o=>`(${o.toString()})`).join(",");return`'use strict';(${Yp.toString()})(${JSON.stringify(a)},[${s}],(${oh.toString()}));`}function Gh(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 mi=0;function Hh(){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 Qp(e){try{return new TextEncoder().encode(e).length}catch{return e.length}}var Zp=1024,Jp=256;function qh(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 qa(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,Zp)};case"3D_UPDATE_TRANSFORMS":{let i=r.transforms;if(Array.isArray(i)){if(i.length>1e3)return null;for(let n of i)if(!qh(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>Jp||o==="__proto__"||o==="constructor"||o==="prototype")return null;let l=s[o];if(!qh(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 ed(e){let t=Qp(e);if(t>1048576)throw new Error(`SecurityError: Script length (${t} bytes) exceeds SECURITY_3D_MAX_SCRIPT_BYTES (1048576).`)}function Wh(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 td(e,t,r,i){let n=Hh(),a=Ha(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,mi++;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=qa(v,n);y&&Wh(y,i,h,c)};h=()=>{o||(o=!0,f!==void 0&&clearTimeout(f),mi=Math.max(0,mi-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(),Gh(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 Kh(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(mi>=32)return i(`SecurityError: ${mi} workers running, meeting SECURITY_3D_MAX_CONCURRENT_TASKS (32).`,"Security Error: too many concurrent sandboxed scripts.");let n;try{n=qp()}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=Wp()}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(td(e,n,h,r))}catch(p){return Promise.reject(p)}}let a=Hh(),s=Ha(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=pl(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.")}mi++;let l=!1,c={modelDispatched:!1},f,m=()=>{l||(l=!0,f!==void 0&&clearTimeout(f),mi=Math.max(0,mi-1),o.terminate())};return f=setTimeout(()=>{l||(m(),Gh(r))},3e3),o.onmessage=h=>{let p=qa(h.data,a);p&&Wh(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 Xh(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 Yh=e=>(t,r)=>{let i=new Error(t);return e.onError?.(i),r&&e.onToast?.(r),Promise.reject(i)},Bn={execute(e,t,r,i){let n=Yh(r),a=Xh(t,n);if(a)return a;try{ed(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??yl()?Kh({kind:"script",script:e,texturePack:i?.texturePack},t,r,n):n(Hc,qc)},executeUrl(e,t,r,i){let n=Yh(r),a=Xh(t,n);if(a)return a;let s;try{s=Kp(e)}catch(o){let l=o instanceof Error?o.message:String(o);return n(l,"Security Error: disallowed scene script URL.")}return Kh({kind:"url",scriptUrl:s,texturePack:i?.texturePack},t,r,n)}},Wa=new Set;function Zr(e,t){let r=`[three-live] ${e} is unsupported; degraded to ${t}.`;Wa.has(r)||(Wa.add(r),typeof console<"u"&&typeof console.warn=="function"&&console.warn(r))}function bl(){return Array.from(Wa)}function xl(){Wa.clear()}var Ka=class extends Gi{constructor(e={}){Zr("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}},vl=Ka,pi=class extends $t{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)}},Qh=pi,wl=class extends pi{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)}},Ml=e=>Array.from(e,t=>parseInt(t,36)),Xa=[1,0,0,-1,0,0,0,1,0,0,-1,0,0,0,1,0,0,-1],Zh=Ml("024043035052125153134142"),_l=class extends pi{constructor(e=1,t=0){super(Xa,Zh,e,t)}},Tt=(1+Math.sqrt(5))/2,Sl=class extends pi{constructor(e=1,t=0){super([-1,Tt,0,1,Tt,0,-1,-Tt,0,1,-Tt,0,0,-1,Tt,0,1,Tt,0,-1,-Tt,0,1,-Tt,Tt,0,-1,Tt,0,1,-Tt,0,-1,-Tt,0,1],Ml("0b505101707a0ab1595b4ba2a7671839434232636838949524b62a867981"),e,t)}},Sr=1/Tt,Al=class extends pi{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,-Sr,-Tt,0,-Sr,Tt,0,Sr,-Tt,0,Sr,Tt,-Sr,-Tt,0,-Sr,Tt,0,Sr,-Tt,0,Sr,Tt,0,-Tt,0,-Sr,Tt,0,-Sr,-Tt,0,Sr,Tt,0,Sr],Ml("3b737f3fd7jh7h676fh48h8aha680g8g282a0c101i0ig6a262d6df2gi2i323di19i9bib34ec4c0408b95b5jbj7j5eje4j4h1ce1e5159"),e,t)}},Tl=class extends Ia{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 ar(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))))}},Ya=class extends $t{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)}},Pl=class extends Ya{constructor(e=1,t=32,r=0,i=Math.PI*2){super(0,e,t,1,r,i)}},Qa=class extends _r{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)}},zn=class extends _r{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)}},Nl=class extends zn{constructor(e={}){super(e),this.dashSize=Number(e.dashSize)||3,this.gapSize=Number(e.gapSize)||1,this.scale=Number(e.scale)||1}};function Jh(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,I=Math.hypot(_,P,R);if(!o&&I<1e-8)continue;I>0&&(_/=I,P/=I,R/=I);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 Cl=class extends $t{constructor(e){super(),this.setAttribute("position",new zt(Jh(e),3)),this.__isSegmentPairs=!0}},El=class extends $t{constructor(e,t=1){super();let r=Number.isFinite(Number(t))?Number(t):1;this.setAttribute("position",new zt(Jh(e,r),3)),this.__isSegmentPairs=!0}};function rd(e,t,r=1){let i=new $t;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,I=Math.hypot(_,P,R);if(I<1e-6)continue;let F=_/I,V=P/I,Y=R/I,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 id(e,t=.05){let r=new $t;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=Xa[A*3],w=Xa[A*3+1],S=Xa[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+Zh[A])}return r.setFromBuffers(l,c,f,m),r}var Pi=class extends Yr{constructor(e,t,r="strip"){let i=t&&typeof t=="object"?t:{},n=t instanceof _r?t:r==="points"?new Qa(i):new zn(i),a=e instanceof $t?e:new $t;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?id(this._sourceGeo,this.material?.size??.05):rd(this._sourceGeo,this._lineMode,this.material?.linewidth??1))}},Ll=class extends Pi{constructor(e,t){super(e,t,"loop"),this.isLineLoop=!0}},Rl=class extends Pi{constructor(e,t){super(e,t,"segments"),this.isLineSegments=!0}},Il=class extends Pi{constructor(e,t){super(e,t,"points"),this.isPoints=!0}},$l=class extends Ba{constructor(e,t,r=0,i=Math.PI/3,n=0,a=2){super(e,t,r,a),this.target=new zr,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}},Za=class extends fi{constructor(e,t,r){super(e,r),this.type="hemisphere",this.groundColor=new Br(t??4473924),this.position.set(0,1,0)}},Dl=class extends Fa{constructor(e,t){Zr("RectAreaLight","AmbientLight"),super(e,t)}},ef={Vector2:ar,Vector3:Ze,Vector4:Bo,Euler:Ca,Quaternion:Dn,Matrix4:Ai,Matrix3:zo,Color:Br,MathUtils:Uo,BufferAttribute:zt,Float32BufferAttribute:Oo,Uint16BufferAttribute:jo,Uint32BufferAttribute:Go,BufferGeometry:$t,BoxGeometry:La,PlaneGeometry:Ho,SphereGeometry:qo,CylinderGeometry:Ra,ConeGeometry:Wo,TorusGeometry:Ko,TorusKnotGeometry:Xo,Curve:hi,Curve3:hi,LineCurve3:Yo,QuadraticBezierCurve3:Qo,CubicBezierCurve3:Zo,CatmullRomCurve3:Jo,LatheGeometry:Ia,TubeGeometry:el,PolyhedronGeometry:pi,IcosahedronGeometry:Sl,OctahedronGeometry:_l,DodecahedronGeometry:Al,TetrahedronGeometry:wl,CapsuleGeometry:Tl,RingGeometry:Ya,CircleGeometry:Pl,WireframeGeometry:Cl,EdgesGeometry:El,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:kn,DataTexture:tl,TextureLoader:rl,Material:_r,MeshStandardMaterial:Gi,MeshBasicMaterial:nl,MeshLambertMaterial:al,MeshPhongMaterial:sl,MeshPhysicalMaterial:ol,PointsMaterial:Qa,LineBasicMaterial:zn,LineDashedMaterial:Nl,ShaderMaterial:Ka,RawShaderMaterial:vl,Object3D:zr,Group:ll,Mesh:Yr,InstancedMesh:Da,Line:Pi,LineLoop:Ll,LineSegments:Rl,Points:Il,LightShadow:ka,Light:fi,AmbientLight:Fa,DirectionalLight:ul,PointLight:Ba,SpotLight:$l,HemisphereLight:Za,RectAreaLight:Dl,Camera:za,PerspectiveCamera:cl,Scene:Va,WebGLRenderer:fl,Clock:ml,SceneQuotaValidator:Qr,exportSceneToCanvas3D:Ua,exportSceneToGLB:Oa,exportSceneToUSDZ:hl,generateUSDZ:Sa,glbToUSDZ:_a,sceneToCanvas3D:Vi,sceneToGLB:En,sceneToUSDZ:In,authorScriptRunner:Bn,warnUnsupported:Zr,getAuthorWarnings:bl,clearAuthorWarnings:xl};Object.freeze(Qr),Object.freeze(Qr.prototype),Object.freeze(Va.prototype),Object.freeze(ef);var Ni=new Proxy(ef,{get:(e,t)=>{if(t in e)return e[t];let r=We().authorNamespace;return r&&typeof t=="string"&&t in r?r[t]:(typeof t=="string"&&t!=="then"&&t!=="toJSON"&&!t.startsWith("__")&&Zr(`THREE.${t}`,"no-op proxy"),qi)},has:(e,t)=>{if(t in e)return!0;let r=We().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")}}),Ja=We();if(Ja.threeNamespace=Ni,Ja.workerExtensionInstallers)for(let e of Ja.workerExtensionInstallers)e(Ni,Ja);var Wi={name:"three_author",THREE:Ni},tf=Wi,Jr=typeof globalThis<"u"?globalThis:typeof window<"u"?window:void 0;if(typeof Jr.THREE>"u"&&(Jr.THREE=Ni),typeof Jr.requestAnimationFrame!="function"&&(Jr.requestAnimationFrame=e=>(typeof e=="function"&&typeof Jr.__three_live_raf_cb__!="function"&&(Jr.__three_live_raf_cb__=e),Jr.__three_live_in_step__||Zr("requestAnimationFrame","single-frame static evaluation"),0)),typeof Jr.cancelAnimationFrame!="function"&&(Jr.cancelAnimationFrame=()=>{}),typeof window<"u"){let e=window;e.ThreeLive=e.ThreeLive||{},e.ThreeLive.THREE=Ni,e.ThreeLivePlugins=e.ThreeLivePlugins||{},e.ThreeLivePlugins.threeAuthor=Wi,e.ThreeLivePlugins.three_author=Wi,e.ThreeLivePlugins["three-author"]=Wi}function es(e,t){let r=e?.trim(),i=r?Number(r):NaN;return Number.isFinite(i)?i:t}var kl=(e,t,r)=>({x:e,y:t,z:r,toString:()=>`${e}m ${t}m ${r}m`}),nd=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 ts=class xi extends nd{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 We().sandboxEngineSrc??null}static set sandboxEngineSrc(t){We().sandboxEngineSrc=t}static get sandboxIframeSrc(){return We().sandboxIframeSrc??null}static set sandboxIframeSrc(t){We().sandboxIframeSrc=t}static get allowClientScripts(){return!!We().allowClientScripts}static set allowClientScripts(t){We().allowClientScripts=t}static registerScriptRunner(t){We().scriptRunner=t}static defineModelViewer(t="model-viewer"){if(typeof customElements>"u")return!1;let r=customElements.get(t);return r!=null?r===xi||r.prototype instanceof xi:(customElements.define(t,class extends xi{}),!0)}static registerDecoder(t,r){ir.registerDecoder(t,r)}static getDecoder(t){return ir.getDecoder(t)}static registerAR(t){We().arProvider=typeof t=="function"?{activateAR:t}:t,typeof document<"u"&&document.querySelectorAll("three-live").forEach(r=>{r instanceof xi&&r.updateARButtonVisibility()})}static isARSupported(){return!!We().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 ir.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 ir.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(Bi(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 ir.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")||(We().sandboxIframeSrc?"iframe":"worker")}set sandbox(t){this.setAttr("sandbox",t)}get allowClientScripts(){return this.getBoolAttr("allow-client-scripts")||xi.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 xi.isARSupported()}get toneMapping(){return Bi(this.getAttr("tone-mapping"))}set toneMapping(t){this.setAttr("tone-mapping",t)}get bloomThreshold(){return es(this.getAttr("bloom-threshold"),.62)}set bloomThreshold(t){this.setAttr("bloom-threshold",t)}get bloomRadius(){return es(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():kl(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:kl(n,a,s),normal:kl(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=zi(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=We().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 ir(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 ir.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")&&xi.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 ir.getRegisteredPlugins())if(t.updateHotspotsForElement){t.updateHotspotsForElement(this,this.viewer);return}}runWithScriptRunner(t){let r=We().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,bp,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(!We().scriptRunner)return this.runWithScriptRunner(()=>Promise.resolve());if(!this.allowClientScripts){let r=new Error(Hc);return this.showToast(qc),this.emitError(r,"security"),Promise.reject(r)}return this.runWithScriptRunner((r,i)=>r.execute(t,this.sandbox,i,{allowClientScripts:!0}))}};ts.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(" "),ts.registerPlugin=ir.registerPlugin,ts.getRegisteredPlugins=ir.getRegisteredPlugins;var di=ts;{let e=di.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",di);function rf(e="model-viewer"){return di.defineModelViewer(e)}var nf={eye:[0,1.6,5],target:[0,.8,0]},af=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(" ")),ad=["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(" ")),rs=[["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"]],sf={grey:"gray",golden:"gold",crimson:"red",maroon:"red",violet:"purple",aqua:"cyan",turquoise:"cyan",tan:"beige"},Fl={};function Ir(e,t){for(let r of e.split(" "))Fl[r]=t}Ir("left leftmost",["right",!1]),Ir("right rightmost",["right",!0]),Ir("front nearest closest frontmost",["depth",!1]),Ir("back farthest furthest rear far backmost",["depth",!0]),Ir("top highest upper topmost",["up",!0]),Ir("bottom lowest lower bottommost",["up",!1]),Ir("biggest largest big large huge bigger larger",["size",!0]),Ir("smallest small tiny little smaller",["size",!1]),Ir("tallest tall taller",["height",!0]),Ir("shortest short shorter",["height",!1]),Ir("middle center centre central","middle");var of={first:0,second:1,third:2,fourth:3,fifth:4,last:-1},lf={two:2,pair:2,three:3,four:4,five:5,six:6,seven:7,eight:8,nine:9,ten:10},uf=new Set(["all","every","everything","each","everybody"]),Bl=e=>/^[0-9]+$/.test(e),is=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),zl=e=>is(Fl,e)?Fl[e]:null,cf=e=>is(of,e)?of[e]:null;function hf(e){let t;if(is(lf,e))t=lf[e];else if(/^[0-9]{1,3}$/.test(e))t=Number(e);else return null;return t>=1&&t<=50?t:null}function ff(e){return is(sf,e)?sf[e]:rs.some(t=>t[0]===e)?e:null}function sd(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&&!zl(a)&&a!=="side"&&a!=="end")return!0}}return!1}function od(e){return String(e??"").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)}function mf(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 ld(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(mf)}var ud=e=>e.replace(/[^A-Za-z0-9]/g,"").toLowerCase(),cd=(e,t)=>ad.some(r=>r.includes(e)&&r.includes(t));function pf(e,t){return e===t||cd(e,t)||t.length>=4&&e.length>=4&&(e.startsWith(t)||t.startsWith(e))}function Vl(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 hd(e){let t=[Vl(e[0]),Vl(e[1]),Vl(e[2])],r=rs[0][0],i=1/0;for(let[n,a]of rs){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 fd=e=>rs.find(t=>t[0]===e)?.[2]??"";function md(e,t){return e.words.includes(t)?!0:e.colorName!=null&&(e.colorName===t||fd(e.colorName)===t)}function ns(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:ld(t.name),colorName:t.color?hd(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 pd(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 Ki(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 df=e=>e.length?e.reduce((t,r)=>t+r,0)/e.length:0;function Ul(e,t,r){let i;if(t==="middle"){if(e.length<3)return e;let n=e.map(o=>Ki(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=>Ki(s,t[0],r)),a=df(n);i=e.filter((s,o)=>t[1]?n[o]>a+1e-6:n[o]<a-1e-6)}return i.length?i:e}function gf(e,t,r){let i;if(t==="middle"){let n=df(e.map(a=>Ki(a,"right",r)));i=e.map(a=>[a,Math.abs(Ki(a,"right",r)-n)])}else i=e.map(n=>[n,t[1]?-Ki(n,t[0],r):Ki(n,t[0],r)]);return i.sort((n,a)=>n[1]-a[1])}function or(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 Ci=e=>or([],"none",e);function Ol(e,t,r=nf,i){let n=i?e.filter(s=>i.includes(s.name)):[...e],a=od(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=jl(n,a.slice(0,s),r);if(f.confidence!=="high")return f;let m=n.filter(g=>f.ids.includes(g.id)),h=jl(m,a.slice(s+(c?1:2)),r);if(h.confidence!=="high")return or(m,"ambiguous","except");let p=m.filter(g=>!h.ids.includes(g.id));return p.length?or(p,"high","match"):Ci("no_match")}return jl(n,a,r)}function dd(e){return!(af.has(e)||uf.has(e)||e==="both"||hf(e)!==null||cf(e)!==null||ff(e)!==null||zl(e)!==null||Bl(e))}function jl(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(dd)))return yf(e,t,r);let a=[],s=!1;for(let l of n){let c=yf(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?or(o,"ambiguous","multiple"):or(o,"high","match")}function yf(e,t,r){if(!e.length)return Ci("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=>ud(A.name)===n);if(y.length)return or(y,"high","exact")}if(sd(t))return Ci("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(uf.has(y))o=!0,s=!0;else if(y==="both")l=2,s=!0;else if((A=hf(y))!==null)l=A,s=s||A>1;else if((A=cf(y))!==null)c=A;else if((b=ff(y))!==null)f.push(b);else if((w=zl(y))!==null)m.push(w);else if(!af.has(y)){let S=mf(y);S!==y&&(s=!0),a.push(S),h=!0}}if(!a.length&&!f.length&&!m.length&&c===null&&!o&&l===null)return Ci("empty");let p=pd(r),g=e;if(a.length){let y=g.map(S=>({e:S,n:a.filter(E=>S.words.some(N=>pf(N,E))).length})),A=Math.max(0,...y.map(S=>S.n));if(A===0)return Ci("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=>pf(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=>md(y,A)))),!g.length)return Ci("no_match");if(c!==null){for(let w of m)g=Ul(g,w,p);let y=gf(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 Ci("no_match");b=y.slice(w,w+A)}return or(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=Ul(g,b,p);let y=gf(g,m[m.length-1],p),A=v;if(y.length<A)return or(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 or(y.filter(w=>Math.abs(w[1]-b)<=1e-6).map(w=>w[0]),"ambiguous","multiple")}return or(y.slice(0,A).map(b=>b[0]),"high","match")}for(let y of m)g=Ul(g,y,p);return x?g.length===1?or(g,"high","match"):or(g,"ambiguous","multiple"):l!==null&&g.length!==l?or(g,"ambiguous","count_mismatch"):or(g,"high","match")}var bf="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(" "),as=(e,t)=>{for(let r of t)if(e.startsWith(r))return e.slice(r.length).trim()||null;return null},Gl=(e,t)=>{for(let r of t)if(e.endsWith(r))return e.slice(0,-r.length).trim()||null;return null},Hl=e=>e.replace(/[.!?,]+$/,"");function gd(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||!bf.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 xf(e,t){let r=e.split(/\s+/).filter(Boolean);return r.length&&Hl(r[r.length-1]).toLowerCase()==="please"&&r.pop(),Hl(r.slice(Math.max(0,r.length-t)).join(" "))}function ql(e,t,r){let[i,n]=gd(t),a=Gl(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:xf(r,s)}}return{kind:"select",mode:e,query:i}}var yd=["please ","ok ","ok, ","okay ","okay, ","now ","now, ","hey ","um ","um, ","uh ","uh, ","so ","so, ","and "],bd=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"]),xd=["select only ","select just ","only select ","just select ","select ","pick ","choose ","highlight ","grab ","focus on "];function Wl(e){let t=String(e??"").trim(),r=t.toLowerCase().replace(/[\u2018\u2019]/g,"'").split(/\s+/).filter(Boolean).join(" ");for(r=Hl(r);;){let n=r.length;for(let a of yd)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(),bd.has(r))return{kind:"clear",mode:"clear"};let i=as(r,["deselect ","unselect ","don't select ","do not select "]);if(i!==null)return ql("remove",i,t);for(let n of["remove ","take "])if(r.startsWith(n)){let a=Gl(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=as(r,["also select ","also pick ","also choose ","also add "]),i!==null)return ql("add",i,t);if(r.startsWith("add ")){let n=Gl(r.slice(4),[" to the selection"," to selection"]);if(n!==null)return{kind:"select",mode:"add",query:n}}return i=as(r,xd),i!==null||(i=as(r,["just ","only "]),i!==null&&!bf.includes(i.split(" ")[0]))?ql("replace",i,t):{kind:"edit",instruction:xf(t,1/0)}}var vf=50;function Kl(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>=vf)break}return t}function yr(e){let t=e.__tlSelection??[],r=e.selectedMesh||null;return(t[0]??null)!==r?r?[r]:[]:[...t]}function Ar(e,t,r={}){let i=r.mode??"replace",n=yr(e),a=Kl(typeof t=="string"?[t]:t??[]),s;switch(i){case"clear":s=[];break;case"add":s=Kl([...n,...a]);break;case"remove":s=n.filter(f=>!a.includes(f));break;case"toggle":s=Kl([...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 vd(e){!e||e.__tlSelectionInstalled||(e.__tlSelectionInstalled=!0,"selectedMeshes"in e||Object.defineProperty(e,"selectedMeshes",{get:()=>yr(e),set:t=>{Ar(e,t??[],{mode:"replace",source:"api"})},configurable:!0}),e.addEventListener?.("three-load",()=>{let t=yr(e);t.length>1&&e.viewer?.setSelectedMeshes?.(t)}))}function ss(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 Xl=new WeakMap;function wd(e){let t=e;if(Xl.has(t))return Xl.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 Xl.set(t,n),n}function Vn(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?wd(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 os(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 nf;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 Yl(e,t,r={}){let i=ns(Vn(e));return Ol(i,t,os(e),r.within??null)}var Md=["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(" "),Xi=e=>Math.round(e*100)/100;function Ql(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(Xi),target:r.target.map(Xi),right:[Xi(-n[2]/a),0,Xi(n[0]/a)]},objects:e.slice(0,300).map(o=>({id:o.id,name:o.name,color:o.colorName,center:o.center.map(Xi),size:Xi(Math.cbrt(o.size))})),selected:i.slice(0,50),request:String(t).slice(0,500)};return[{role:"system",content:Md},{role:"user",content:JSON.stringify(s)}]}function Zl(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<vf&&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 Jl(e,t,r,i={}){let n=Vn(e);i.within&&(n=n.filter(o=>i.within.includes(o.name)));let a=ns(n);if(!a.length)return{names:[],confidence:"low",question:""};let s=await r.complete({messages:Ql(a,t,os(e),yr(e)),signal:i.signal});return Zl(s,a)}var _d=32,Sd=32,Ad=80,wf=2e3,ls=32*1024*1024,Td=1024,Pd=256,Nd=2048,eu=["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 Mf(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,Ad).join("")}function ei(e){let t=Math.round(e*100)/100;return(Object.is(t,-0)||Math.abs(t)<1e-9?0:t).toFixed(2)}function _f(e){let t=Math.round(e),r=Object.is(t,-0)?0:t;return String(r)}function Yi(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 Cd(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 Ed(e){let t=Yi(e);return!t||t[0]<=0||t[1]<=0||t[2]<=0?null:t}function Un(e){return`[${ei(e[0])}, ${ei(e[1])}, ${ei(e[2])}]`}function us(e){if(!e||typeof e!="object")return"";let t=[];if(typeof e.floorY=="number"&&Number.isFinite(e.floorY)&&t.push(`- Floor height: y = ${ei(e.floorY)} m`),e.camera&&typeof e.camera=="object"){let r=Yi(e.camera.eye),i=Yi(e.camera.target);if(r&&i){let n=`- Camera: eye ${Un(r)}, target ${Un(i)}`,a=Number(e.camera.fovDeg);Number.isFinite(a)&&a>=1&&a<=179&&(n+=`, fov ${_f(a)} deg`),t.push(n)}}if(Array.isArray(e.planes)){let r=[];for(let i of e.planes){if(r.length>=_d)break;if(!i||typeof i!="object")continue;let n=Yi(i.center);if(!n)continue;let a=String(i.orientation??"").toLowerCase()==="vertical"?"vertical":"horizontal",s=Mf(i.label),o=Cd(i.extent),l=Yi(i.normal),c=` ${r.length+1}. ${a}`;s&&(c+=` "${s}"`),c+=` at ${Un(n)}`,o&&(c+=`, extent ${ei(o[0])}m x ${ei(o[1])}m`),l&&(c+=`, normal ${Un(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>=Sd)break;if(!i||typeof i!="object")continue;let n=Mf(i.label),a=Yi(i.center);if(!n||!a)continue;let s=Ed(i.size),o=typeof i.yawDeg=="number"&&Number.isFinite(i.yawDeg)?i.yawDeg:null,l=` ${r.length+1}. "${n}" at ${Un(a)}`;s&&(l+=`, size ${ei(s[0])}m x ${ei(s[1])}m x ${ei(s[2])}m`),o!==null&&(l+=`, yaw ${_f(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 $r(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 tu(e,t){let r=`Reconstruct the 3D scene shown in this reference image as a complete Three-Live script.
|
|
409
|
+
`;r+=us(t);let i=Array.from(String(e??"").trim()).slice(0,wf).join("");return i&&(r+=`Additional instructions: ${i}
|
|
410
|
+
`),r+="Return only the complete script in a single ```js code block.",r}function ru(e,t,r){let i=String(e??"").trim();if(!$r(i))throw new Error("compileFromImage: imageUrl must be a base64 data:image/(png|jpeg|webp) URI or an https:// URL.");let n=tu(t,r);return[{role:"system",content:eu},{role:"user",content:[{type:"image_url",image_url:{url:i}},{type:"text",text:n}]}]}function iu(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 nu(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 Ld(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 Rd(e){let t=Number(e);return Number.isFinite(t)?Math.max(Pd,Math.min(Nd,Math.round(t))):Td}function cs(e){if(e.byteLength===0)throw new Error("compileFromImage: image buffer is empty.");if(e.byteLength>ls)throw new Error("compileFromImage: image exceeds the 32 MB limit.");let t=nu(e);if(!t)throw new Error("compileFromImage: unsupported image format (expected PNG, JPEG, or WebP magic bytes).");return`data:${t};base64,${Ld(e)}`}function Id(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($r(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($r(m))return m}}}catch{}if(typeof l.toDataURL=="function")try{let c=l.toDataURL("image/jpeg",.88);if($r(c))return c}catch{}return null}async function hs(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=Rd(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(!$r(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)>ls)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)&&!$r(s))throw new Error("compileFromImage: remote image URLs must use https:// (or http:// on localhost).");let o=/^https?:/i.test(s)&&$r(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)&&!$r(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>ls)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 cs(new Uint8Array(h))}if(e instanceof ArrayBuffer||Object.prototype.toString.call(e)==="[object ArrayBuffer]")return cs(new Uint8Array(e));if(ArrayBuffer.isView(e))return cs(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>ls)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 cs(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=Id(e,n,a,r);if(s)return s}if(typeof i.toDataURL=="function"){let s=i.toDataURL("image/jpeg",.88);if($r(s))return s}if(typeof i.src=="string"&&i.src.trim())return hs(i.src,t);throw new Error("compileFromImage: unsupported or unloaded image source.")}async function au(e,t,r={}){if(!e?.allowClientScripts)throw new Error("compileFromImage requires client scripts: add the allow-client-scripts attribute.");let i=Su(e,r,"compileFromImage"),n=Au(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,wf).join(""),c=us(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 hs(t,{maxEdge:r.maxEdge,signal:o,fetch:r.fetch});if(o.aborted)throw o.reason;let A=ru(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=As(w),p=[],!m)h="The model reply did not contain a scene script.";else if(new TextEncoder().encode(m).length>Of)h="The generated script exceeds the 1 MB script limit.";else try{let S=await qf(e,m,o,"compileFromImage");p=[...S.warnings];let E=Hf(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:iu(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>jf&&y.shift()}e.__tlAiSource=m,Ar(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 su="three-live-texture-pack",ou=1,Sf=64,Af=6*1024*1024,fs=16*1024*1024,$d=64*1024*1024,lu=" Seamless tileable PBR albedo texture, flat even lighting, orthographic top-down view, no perspective, no shadows, no text.";function Tf(){return We()}function Pf(e){let t=Tf().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 Dd(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 ms(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 kd(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 Fd(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 uu(e){let t=String(e?.endpoint??"");if(!Dd(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+lu,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 ms(g.b64_json,fs);let x=typeof g?.url=="string"?g.url:"";if(x.startsWith("data:image/"))return ms(x.slice(x.indexOf(",")+1),fs);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>fs)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 Nf(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 On={async decode(e){let t=Nf(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=Tf().encodeRgbaPngDataUri;if(typeof r=="function"){let i=r(e,t,t),n=ms(i.slice(i.indexOf(",")+1),1/0),a=We().makePngDeflater?.(globalThis.CompressionStream);return a?a.png(n):n}throw new Error("PNG encoding needs the procedural plugin")}};function Bd(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 zd(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 cu(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:Bd(a,r,r,t,t);for(let o=3;o<s.length;o+=4)s[o]=255;return zd(s,t)}async function hu(e,t=On){let r=typeof e=="string"?JSON.parse(e):e;if(!r||r.format!==su)throw new Error(`texture pack: format must be "${su}"`);if(r.version!==ou)throw new Error(`texture pack: version must be ${ou}`);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>Sf)throw new Error(`texture pack: more than ${Sf} 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=Pf(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=ms(l.slice(c.length),Af);if(f.length>Af||Nf(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 fu(e,t=On){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,${kd(a)}`,...n.provenance?{provenance:n.provenance}:{}}}return{format:su,version:ou,entries:r}}function Vd(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 ps(e){let t=new Map;for(let r of Vd(e)?.nodes??[]){let i=r?.extras?.xr?.material;if(!i||typeof i!="object"||i.prompt==null)continue;let n=Pf(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 mu(e=$d){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 jn=null,Cf=!1;function Vr(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 Ud(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 Od(){let e=We(),t=e.scriptRunner;if(!t||t.__tlTexWrapped)return;let r=i=>jn&&!i?.texturePack?{...i,texturePack:jn}: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 Ef(e,t){Od();let r=jn;jn=Ud(e);try{return t()}finally{jn=r}}function Lf(e,t){let r=t??e.aiImageProvider;if(r&&typeof r.generateImage=="function")return r;let i=e.getAttribute?.("ai-image-endpoint");return i?uu({endpoint:i,model:e.getAttribute?.("ai-image-model")||void 0}):null}function Rf(e){if(e.textureCache!==void 0)return e.textureCache;let t=Vr(e);return t.cache===void 0&&(t.cache=mu()),t.cache}function pu(e){return e.textureCodec??On}function Gn(e){let t=e.querySelector?.('script[type="text/three"], script[type="text/three-live"]')?.textContent,r=Vr(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 If(e,t){let r=Vr(e);r.pack.set(t.key,t),r.packJson=null,r.failed.delete(t.key)}async function $f(e,t){let r=Rf(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&&(If(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 Df(e,t,r,i){let n=Vr(e),a=n.inflight.get(r.key);if(a)return a;let s=(async()=>{try{let o=await Fd(await t.generateImage({...r.spec,signal:i}));if(o.length>fs)throw new Error("generated image exceeds 16 MB");let l=cu(await pu(e).decode(o),r.spec.size),c={provider:t.name??"custom",...t.model?{model:t.model}:{},createdAt:new Date().toISOString()};return If(e,{key:r.key,spec:r.spec,rgba:l,provenance:c}),Rf(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 jd(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 kf(e,t){let r=Vr(e);r.lastModel=t;let i;try{i=ps(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 $f(e,n)).length){await Gn(e).catch(()=>{});return}if((e.getAttribute?.("ai-textures")||"auto").toLowerCase()==="manual")return;let a=Lf(e);if(!a)return;e.fireEvent?.("three-live-texture-start",{keys:n.map(o=>o.key)});let s=(await Promise.all(n.map(o=>Df(e,a,o)))).filter(Boolean).length;s&&(Cf||(Cf=!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 Gn(e).catch(()=>{}))})()}function Ff(e,t){Vr(e).lastRun=t}async function du(e,t){let r=Vr(e),i=++r.loadSeq;if(t==null){r.pack=new Map,r.packJson=null,await Gn(e).catch(()=>{});return}try{let n=await hu(t,pu(e));if(i!==r.loadSeq)return;r.pack=n,r.packJson=typeof t=="string"?JSON.parse(t):t,r.failed.clear(),await Gn(e).catch(()=>{})}catch(n){e.fireEvent?.("three-live-texture-error",{key:null,meshes:[],error:String(n?.message||n)})}}async function Bf(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 du(e,await i.json())}catch(r){e.fireEvent?.("three-live-texture-error",{key:null,meshes:[],error:String(r?.message||r)})}}async function Gd(e,t={}){let r=Vr(e),i=t.meshes?new Set(t.meshes):null,n=ps(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 $f(e,n));a.push(...c),l=n.filter(f=>!c.has(f.key))}if(l.length){let c=Lf(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 jd(l,f,async h=>{r.failed.delete(h.key),t.force&&r.pack.delete(h.key),await Df(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 Gn(e).catch(()=>{}),{generated:s,cached:a,failed:o,pack:await zf(e)}}async function zf(e){let t=Vr(e);return t.packJson??(t.packJson=await fu(t.pack,pu(e)))}function Hd(e){if(!e||e.__tlTexInstalled)return;e.__tlTexInstalled=!0,Vr(e),Object.defineProperty(e,"texturePack",{get:()=>e.__tlTex?.packJson??null,set:n=>{du(e,n)},configurable:!0}),e.generateTextures=n=>Gd(e,n),e.exportTexturePack=()=>zf(e);let t=e.querySelector?.('script[type="application/three-live-texture-pack"]');t?.textContent?.trim()&&du(e,t.textContent);let r=e.getAttribute?.("texture-pack");r&&Bf(e,r);let i=e;typeof MutationObserver<"u"&&i&&typeof i.nodeType=="number"&&new MutationObserver(()=>{let n=e.getAttribute?.("texture-pack");n&&Bf(e,n)}).observe(i,{attributes:!0,attributeFilter:["texture-pack"]})}var ds=12;function gs(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 qd(e){if(typeof document>"u")return!1;let t=(e.getAttribute?.("ai-select-chips")??"").toLowerCase();return t!=="off"&&t!=="false"}function ys(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 Hn(e){let t=e.__tlChips;t&&(t.off(),t.root.remove(),e.__tlChips=null)}function gu(e,t,r){if(!qd(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&&bs(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 bs(e,t,r),i.root}function bs(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,ds))n.appendChild(ys(gs(s),`Select ${gs(s)}`,()=>{Ar(e,[s],{mode:t.mode==="add"||t.mode==="remove"?t.mode:"replace",source:"tap",query:t.query}),bs(e,{pending:t.pending},r)}))}else{let s=yr(e);if(!s.length&&!t.pending){Hn(e);return}a(s.length?"Selected:":"Nothing selected");for(let o of s.slice(0,ds))n.appendChild(ys(`${gs(o)} \xD7`,`Remove ${gs(o)} from the selection`,()=>Ar(e,[o],{mode:"remove",source:"tap"})));if(s.length>ds&&a(`+${s.length-ds} more`),t.pending&&r&&s.length){let o=t.pending;n.appendChild(ys(`Apply: ${o.slice(0,40)}`,`Apply: ${o.slice(0,200)}`,()=>{bs(e,{},r),r(o)},!0))}}n.appendChild(ys("\u2715","Dismiss",()=>Hn(e)))}var Wd=500,Qi=2e3,Kd=8,Xd=[{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."}}}}],Yd=["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 Qd(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 Zd(e){if(!Qd(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 At(e){return typeof e=="string"?e:""}function Tr(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function yu(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)?yu(a,n):n}return r}function Vf(e){if(e&&typeof e=="object")return Tr(e);try{return Tr(JSON.parse(At(e)||"{}"))}catch{return{}}}var bu={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:yu(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(At(e.type)){case"response.output_audio.delta":case"response.audio.delta":return At(e.delta)?[{type:"audio",base64:At(e.delta),rate:24e3}]:[];case"response.output_audio_transcript.delta":case"response.audio_transcript.delta":return[{type:"transcript",speaker:"model",text:At(e.delta),isFinal:!1}];case"response.output_audio_transcript.done":case"response.audio_transcript.done":return[{type:"transcript",speaker:"model",text:At(e.transcript),isFinal:!0}];case"conversation.item.input_audio_transcription.delta":return[{type:"transcript",speaker:"user",text:At(e.delta),isFinal:!1}];case"conversation.item.input_audio_transcription.completed":return[{type:"transcript",speaker:"user",text:At(e.transcript),isFinal:!0}];case"response.function_call_arguments.done":return[{type:"toolCall",id:At(e.call_id)||At(e.item_id),name:At(e.name),args:Vf(e.arguments)}];case"input_audio_buffer.speech_started":return[{type:"interrupted"}];case"response.done":return[{type:"turnComplete"}];case"error":return[{type:"error",message:At(Tr(e.error).message)||"Realtime server error"}];default:return[]}}},xu={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:yu(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=Tr(e.serverContent);r.interrupted&&t.push({type:"interrupted"});let i=Tr(r.inputTranscription);At(i.text)&&t.push({type:"transcript",speaker:"user",text:At(i.text),isFinal:!1});let n=Tr(r.outputTranscription);At(n.text)&&t.push({type:"transcript",speaker:"model",text:At(n.text),isFinal:!1});let a=Tr(r.modelTurn).parts;for(let l of Array.isArray(a)?a:[]){let c=Tr(Tr(l).inlineData),f=At(c.mimeType);if(f.startsWith("audio/pcm")&&At(c.data)){let m=Number(/rate=(\d+)/.exec(f)?.[1])||24e3;t.push({type:"audio",base64:At(c.data),rate:m})}}r.turnComplete&&t.push({type:"turnComplete"});let s=Tr(e.toolCall).functionCalls;for(let l of Array.isArray(s)?s:[]){let c=Tr(l);t.push({type:"toolCall",id:At(c.id),name:At(c.name),args:Vf(c.args)})}let o=Tr(e.error);return At(o.message)&&t.push({type:"error",message:At(o.message)}),t}},Jd={"ai-realtime":bu,"gemini-live":xu};function e1(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 t1(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 r1(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 Uf(){let e=globalThis;return e.AudioContext??e.webkitAudioContext}function i1(){let e=null,t=null,r=null;return{async start(i,n){let a=Uf(),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=t1(c.inputBuffer.getChannelData(0),l,i);f.length&&n(e1(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 n1(){let e=null,t=0,r=new Set,i={play(n,a){let s=Uf();if(!e&&s)try{e=new s}catch{return}if(!e)return;e.state==="suspended"&&e.resume?.();let o=r1(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 Ut(e,t){e.fireEvent?.("three-live-voice",t)}var vu=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(ss(s))};let r=t.provider??"ai-realtime",i=Jd[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=Zd(t.url);else throw new Error("connectVoice: pass a wss:// url or a transport.");this.mic=t.microphone===!1?null:t.microphoneSource??i1(),this.sink=t.playAudio===!1?null:t.audioSink??n1()}async start(){this.transport.onMessage=r=>this.handle(r),this.transport.onClose=()=>this.shutdown();let e=[Yd,this.options.instructions].filter(Boolean).join(`
|
|
419
|
+
`);for(let r of this.adapter.setup({instructions:e,tools:Xd,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=yr(this.el);t.length&&this.sendContext(ss(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,Qi);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,Ut(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(-Qi),Ut(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(-Qi),Ut(this.el,{state:this.state,reply:this.modelText,isFinal:r.isFinal}),r.isFinal&&(this.modelText=""));break;case"turnComplete":this.userText&&(Ut(this.el,{state:this.state,transcript:this.userText,isFinal:!0}),this.userText=""),this.modelText&&(Ut(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<=Kd&&this.runTool(r.id,r.name,r.args);break;case"error":Ut(this.el,{state:this.state,error:r.message});break}}async runTool(e,t,r){let i;try{if(t==="edit_scene"){let n=At(r.instruction).trim().slice(0,Qi);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=At(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"?Mu(this.el,s,a):await qn(this.el,At(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 xs(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 vu(e,t??{});return e.__tlVoiceSession=r,Ut(e,{state:"connecting"}),r.start()}function wu(){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 vs(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 ws(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 Zi(e,t="and"){let r=e.slice(0,5).map(ws),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 Ji(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 ${Zi(t.names)}. ${r.length} selected.`:`Removed ${Zi(t.names)}. Nothing is selected.`:e==="add"?`Added ${Zi(t.names)}. ${r.length} selected.`:t.names.length===1?`Selected ${ws(t.names[0])}.`:`Selected ${t.names.length}: ${Zi(t.names)}.`;if(t.confidence==="ambiguous")return t.reason==="count_mismatch"?`I found ${t.candidates.length}: ${Zi(t.candidates)}. Which ones?`:`Which one: ${Zi(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 qn(e,t,r={}){let i=r.mode??"replace",n=String(t??"").slice(0,Qi);if(i==="clear")return Ar(e,[],{mode:"clear",source:"voice",query:n||"clear"}),{mode:i,query:n,match:null,applied:!0,tier:1,meshes:[],say:Ji(i,null,[],n)};let a=i==="remove"?yr(e):null;if(a&&!a.length)return{mode:i,query:n,match:null,applied:!1,tier:1,meshes:[],say:"Nothing is selected."};let s=Yl(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 Jl(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&&(Ar(e,s.names,{mode:i,source:"voice",query:n}),f=!0);let m=yr(e),h=!f&&l?l:Ji(i,s,m,n);return{mode:i,query:n,match:s,applied:f,tier:o,meshes:m,say:h}}function Mu(e,t,r="replace"){let i=new Set(Vn(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=yr(e);return{mode:r,query:a,match:l,applied:!1,tier:1,meshes:c,say:Ji(r,l,c,a)}}Ar(e,n,{mode:r,source:"voice",query:a});let s={ids:[],names:n,confidence:"high",candidates:[],reason:"exact"},o=yr(e);return{mode:r,query:a,match:s,applied:!0,tier:1,meshes:o,say:Ji(r,s,o,a)}}function Ms(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 a1(e,t,r){if(typeof e.editScene!="function")return;Ut(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)}}Ut(e,{state:"idle",transcript:t,isFinal:!0,result:i}),r.speak!==!1&&vs(Ms(i),r.lang)}async function _s(e,t={}){if(typeof e.editScene!="function")throw new Error("startVoiceEdit needs three-live-ai.min.js (el.editScene).");let r=t.recognizer??wu();if(!r)throw new Error("startVoiceEdit: this browser has no speech recognition; use el.connectVoice() (ai-realtime or gemini-live) instead.");Ut(e,{state:"listening"});let i="";try{i=(await r.listen({lang:t.lang,signal:t.signal,onPartial:l=>Ut(e,{state:"listening",transcript:l,isFinal:!1})})).trim().slice(0,Qi)}catch(l){throw Ut(e,{state:"error",error:l?.message||String(l)}),l}if(!i){let l="I didn't catch that.";throw Ut(e,{state:"idle",transcript:i,isFinal:!0,error:l}),t.speak!==!1&&vs(l,t.lang),new Error(`startVoiceEdit: ${l}`)}let n=i,a,s=t.talkToSelect===!1?null:Wl(i);if(s&&s.kind!=="edit"){Ut(e,{state:"thinking",transcript:i,isFinal:!0});try{a=await qn(e,s.kind==="clear"?"":s.query,{mode:s.mode,signal:t.signal})}catch(m){throw Ut(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;gu(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=>a1(e,h,t))}if(!c){if(Ut(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.":"";vs(a.say+m,t.lang)}return{transcript:i,result:null,selection:a}}n=l}else t.chips!==!1&&e.__tlChips&&Hn(e);Ut(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(Ut(e,{state:"idle",transcript:i,isFinal:!0,result:o,...a?{selection:a}:{}}),t.speak!==!1){let l=Ms(o);vs(a?`${a.say} ${l}`:l,t.lang)}return{transcript:i,result:o,...a?{selection:a}:{}}}function Ss(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>=Wd,l=yr(e);r||o?Ar(e,[s],{mode:"toggle",source:"tap"}):l.length===1&&l[0]===s?Ar(e,[],{mode:"clear",source:"tap"}):Ar(e,[s],{mode:"replace",source:"tap"}),r=!1,i=0},e.addEventListener?.("meshclick",e.__tlTapHandler)}var s1='<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 o1(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=s1,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";xs(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),_s(e,{signal:i.signal}).catch(()=>{}).finally(()=>{i=null,n(!1)})})}var Of=1048576,jf=20,Gf=15e3,l1=["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 u1(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 _u(e){let t=String(e?.endpoint??"");if(!u1(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 As(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 Hf(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 qf(e,t,r,i="editScene"){let n=We().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 ${Gf} ms.`))),Gf);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 c1=50;function h1(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>=c1)break}return r}function f1(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 Su(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 _u({endpoint:n,model:e.getAttribute?.("ai-model")||void 0})}function Au(e){return typeof e.__tlAiSource=="string"?e.__tlAiSource:e.querySelector?.('script[type="text/three"], script[type="text/three-live"]')?.textContent??""}async function Tu(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??Au(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=Su(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=h1(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:l1},{role:"user",content:`Current scene script:
|
|
423
|
+
\`\`\`js
|
|
424
|
+
${n}
|
|
425
|
+
\`\`\`
|
|
426
|
+
`+f1(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=As(b),!p)g="The model reply did not contain a scene script.";else if(new TextEncoder().encode(p).length>Of)g="The generated script exceeds the 1 MB script limit.";else try{let w=await qf(e,p,l);x=w.warnings;let S=Hf(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>jf&&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 Pu(e){let t=e?.__tlAiHistory?.pop();return typeof t!="string"?!1:(e.__tlAiSource=t,await e.executeScript(t),!0)}var Ts={name:"ai",onRegister(){typeof document>"u"||document.querySelectorAll?.("three-live, xr-live").forEach(e=>Ts.onElementConnected?.(e))},onElementConnected(e){let t=e;if(!t||t.__tlAiInstalled)return;t.__tlAiInstalled=!0,t.editScene=(s,o)=>Tu(t,s,o),t.compileFromImage=(s,o)=>au(t,s,o),t.undoEdit=()=>Pu(t),vd(t);let r=t;t.startVoiceEdit=s=>_s(r,s),r.__tlSelectProvider=()=>{try{return Su(t,{})}catch{return null}},t.selectByVoice=(s,o)=>qn(r,s,o),t.connectVoice=s=>xs(r,s),t.setSelectOnTap=s=>Ss(r,s),t.hasAttribute?.("ai-select-on-tap")&&Ss(r,!0),t.hasAttribute?.("ai-voice-button")&&o1(r),"sceneSource"in t||Object.defineProperty(t,"sceneSource",{get:()=>Au(t),configurable:!0});let i=t;Hd(i);let n=t.executeScript;typeof n=="function"&&(t.executeScript=s=>(Ff(i,{kind:"script",value:String(s)}),Ef(i,()=>n.call(t,s)).then(o=>(t.__tlAiSource=String(s),kf(i,o),o))));let a=i.loadScriptFromSrc;typeof a=="function"&&(i.loadScriptFromSrc=s=>(Ff(i,{kind:"url",value:String(s)}),Ef(i,()=>a.call(t,s)).then(o=>(kf(i,o),o))))}};Rt(Ts);function Wf(e,t,r){return t%4===0?new Float32Array(e,t,r):new Float32Array(e.slice(t,t+r*4))}function Nu(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 Kf(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 Cu(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=Fi(e,t,f,1)??Wf(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=Fi(e,t,m,A)??Wf(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 en(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]];Nu(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 Wn=new WeakMap;function Eu(e,t,r=.3){if(!e?.animations)return;let i=e.animations.find(o=>o.name===t);if(!i)return;let n=Wn.get(e);n||(n=[],e.currentClip&&n.push({clip:e.currentClip,time:e.animationTime||0,weight:1,fadeSpeed:0}),Wn.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 Lu(e,t){if(!e.gltf||!Array.isArray(e.gltf.nodes))return;let r=Wn.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")en(p,m.time,a),Kf(g.t,g.t,a,h);else if(p.path==="rotation")en(p,m.time,s),Nu(g.r,g.r,s,h);else if(p.path==="scale")en(p,m.time,o),Kf(g.s,g.s,o,h);else if(p.path==="weights"&&(en(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=lt(),{t:p,r:g,s:x}=n[m];Sn(h,g,p,x),c.push(h)}let f=An(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]),rr(m.normalMatrix,m.transform))}var Ru=e=>{Wn.delete(e)},Iu={name:"keyframes",evaluateAnimation:Lu,crossFadeTo:Eu,onParseGLB(e){(e.animationsParsed===!1||!e.animations)&&(e.animations=Cu(e.gltf,e.bin),e.animationsParsed=!0)},onLoadModel:Ru,onClearScene:Ru,onDestroy:(e,t)=>Ru(t),onUpdate(e,t){if(!e.isPlayingAnimation)return;let r=Wn.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),Lu(e,e.animationTime)}else e.currentClip&&(e.animationTime+=t,e.currentClip.duration>0&&(e.animationTime%=e.currentClip.duration),Lu(e,e.animationTime))}},Kn=64;function Xf(e,t,r){if(!(!e?.meshes||t<0||t>=Kn))for(let i of e.meshes)for(let n of i.primitives){let a=n.pluginData?.morph;a?.weights&&(a.weights[t]=r)}}var $u={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;
|
|
353
428
|
uniform sampler2D uMorphDeltasTex;
|
|
354
|
-
uniform float uMorphWeights[${
|
|
355
|
-
uniform int uNumMorphTargets;`);return
|
|
356
|
-
for (int m = 0; m < ${
|
|
429
|
+
uniform float uMorphWeights[${Kn}];
|
|
430
|
+
uniform int uNumMorphTargets;`);return n=n.replace("vec4 world=uModel*vec4(aPosition,1.0);",`vec3 morphedPos = aPosition;
|
|
431
|
+
for (int m = 0; m < ${Kn}; m++) {
|
|
357
432
|
if (m >= uNumMorphTargets) break;
|
|
358
433
|
float w = uMorphWeights[m];
|
|
359
434
|
if (abs(w) > 0.0001) {
|
|
360
435
|
morphedPos += texelFetch(uMorphDeltasTex, ivec2(gl_VertexID, m), 0).xyz * w;
|
|
361
436
|
}
|
|
362
437
|
}
|
|
363
|
-
vec4 world=uModel*vec4(morphedPos,1.0);`).replace("gl_Position=uMVP*vec4(aPosition,1.0);","gl_Position=uMVP*vec4(morphedPos,1.0);"),{vs:
|
|
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,Kn),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=Fi(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(Kn);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)}},Du=64,ku={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;
|
|
364
439
|
layout(location=4) in uvec4 aJoints;
|
|
365
440
|
layout(location=5) in vec4 aWeights;
|
|
366
|
-
uniform mat4 uJointMatrix[${
|
|
441
|
+
uniform mat4 uJointMatrix[${Du}];`),a=n.includes("morphedPos")?"morphedPos":"aPosition";return n=n.replace(`vec4 world=uModel*vec4(${a},1.0);`,`mat4 skinMatrix =
|
|
367
442
|
aWeights.x * uJointMatrix[int(aJoints.x)] +
|
|
368
443
|
aWeights.y * uJointMatrix[int(aJoints.y)] +
|
|
369
444
|
aWeights.z * uJointMatrix[int(aJoints.z)] +
|
|
370
445
|
aWeights.w * uJointMatrix[int(aJoints.w)];
|
|
371
|
-
vec4 world=uModel*(skinMatrix*vec4(${
|
|
372
|
-
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.);}`,
|
|
373
|
-
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);}`,vr=new WeakMap,Ka=new Float32Array(20);function rn(e,t){let[r,i,s,n,l,a]=t;return[e[0]*r+e[4]*i+e[8]*s+e[12],e[1]*r+e[5]*i+e[9]*s+e[13],e[2]*r+e[6]*i+e[10]*s+e[14],Math.abs(e[0])*n+Math.abs(e[4])*l+Math.abs(e[8])*a,Math.abs(e[1])*n+Math.abs(e[5])*l+Math.abs(e[9])*a,Math.abs(e[2])*n+Math.abs(e[6])*l+Math.abs(e[10])*a]}function Wl(e){if(e._lb!==void 0)return e._lb;let t=1e9,r=1e9,i=1e9,s=-1e9,n=-1e9,l=-1e9;for(let a of e.primitives||[]){let o=a.positions;if(o)for(let u=0;u<o.length;u+=3)o[u]<t&&(t=o[u]),o[u+1]<r&&(r=o[u+1]),o[u+2]<i&&(i=o[u+2]),o[u]>s&&(s=o[u]),o[u+1]>n&&(n=o[u+1]),o[u+2]>l&&(l=o[u+2])}return e._lb=t<=s?[(t+s)*.5,(r+n)*.5,(i+l)*.5,(s-t)*.5,(n-r)*.5,(l-i)*.5]:null}function Xl(e){let t=vr.get(e);if(t)return t;let r=(a,o)=>{let u=e.createShader(a);return e.shaderSource(u,o),e.compileShader(u),u},i=e.createProgram();e.attachShader(i,r(35633,Hl)),e.attachShader(i,r(35632,jl)),e.linkProgram(i);let s=e.createVertexArray(),n=e.createBuffer(),l=e.createBuffer();return e.bindVertexArray(s),e.bindBuffer(34962,n),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:s,vbo:n,ibo:l,uMVP:e.getUniformLocation(i,"uMVP"),uIntensity:e.getUniformLocation(i,"uShadowIntensity"),uSoftness:e.getUniformLocation(i,"uShadowSoftness")},vr.set(e,t),t}var ci={name:"contact-shadow",onContextRestored(e){vr.delete(e)},onAfterRender(e,t,r){let i=t.shadowIntensity;if(i<=0||!t.bounds)return;let s=Xl(e),n=!t.xrSessionActive&&(t.backdropMeshes?.length??0)>0,l=[],a=[];for(let m of t.meshes||[]){if(!m||m.visible===!1||m.isPluginMesh||m.name==="__xr_reticle__"||m.name?.startsWith("__xr_slot_"))continue;let g=Wl(m);if(!g)continue;m.transform&&(g=rn(m.transform,g)),t.modelRootMatrix&&(g=rn(t.modelRootMatrix,g));let[x,b,v,d,y,M]=g,T=[x,v,d,M,b-y,b+y];/floor|table|pedestal|ground|base|plane/i.test(m.name||"")||y<.14&&Math.min(d,M)>.45?a.push(T):l.push(T)}let o=[],u=t.bounds.center||[0,0,0],h=Math.max(.05,Number(t.bounds.radius)||.5),c=t.bounds.min,f=c?[u[0],u[1],u[2],h,Math.max(.01,u[1]-c[1]),h]:[u[0],u[1],u[2],h,h,h];t.modelRootMatrix&&(f=rn(t.modelRootMatrix,f));let p=t.xrSessionActive&&a.length===0&&String(t.container?.tagName||"").toLowerCase()==="xr-live"?(t.modelRootMatrix?t.modelRootMatrix[5]*-.25+t.modelRootMatrix[13]:-.25)+.002:f[1]-f[4]+.002;for(let[m,g,x,b,v]of l){let d=-1/0;for(let[M,T,V,q,,P]of a)v>=P-.08&&Math.abs(m-M)<=V&&Math.abs(g-T)<=q&&P+.002>d&&(d=P+.002);n&&(d=Math.max(d,m>=.04&&m<=.36&&g>=-.34&&g<=-.04&&v>=.01?.036:Math.hypot(m,g)<=.66&&v>=-.06?.003:-.477)),isFinite(d)||(d=p);let y=o.find(M=>Math.hypot(m-M[0],g-M[1])<.06&&Math.abs(d-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)):o.push([m,g,x,b,v,d])}if(o.length===0){let m=Math.max(.1,f[3]*1.5)/1.45;o.push([f[0],f[2],m,m,p,p])}e.useProgram(s.prog),e.uniformMatrix4fv(s.uMVP,!1,r),e.enable(3042),(e.blendFuncSeparate||e.blendFunc).call(e,770,771,1,771),e.depthMask(!1),e.bindVertexArray(s.vao),e.bindBuffer(34962,s.vbo);for(let[m,g,x,b,v,d]of o){let y=Math.max(0,v-d),M=i/(1+y*2);if(M<.02)continue;let T=1+Math.min(.75,y*.85),V=Math.max(.045,x*1.45*T),q=Math.max(.045,b*1.45*T);Ka.set([m-V,d,g-q,0,0,m+V,d,g-q,1,0,m+V,d,g+q,1,1,m-V,d,g+q,0,1]),e.bufferSubData(34962,0,Ka),e.uniform1f(s.uIntensity,M),e.uniform1f(s.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=vr.get(e);t&&(e.deleteVertexArray(t.vao),e.deleteBuffer(t.vbo),e.deleteBuffer(t.ibo),e.deleteProgram(t.prog),vr.delete(e))}};function sn(){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 nn(){if(typeof navigator>"u")return!1;let e=navigator.userAgent||"";return/android/i.test(e)}async function an(){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 Ya(){return(await mi()).bestMode}async function mi(){let[e,t,r]=await Promise.all([an(),Promise.resolve(sn()),Promise.resolve(nn())]),i=[];t&&i.push("quick-look"),e&&i.push("webxr"),r&&i.push("scene-viewer");let s=null;return t?s="quick-look":e?s="webxr":r&&(s="scene-viewer"),{webxr:e,quickLook:t,sceneViewer:r,availableModes:i,bestMode:s}}function Za(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=ql(e),!r)throw new Error("[XR-Live Security] Quick Look URL is empty.")}else r=URL.createObjectURL(e),i=!0;let s=[];if(t.allowScale===!1&&s.push("allowsContentScaling=0"),t.canonicalWebPageUrl){let a=fi(t.canonicalWebPageUrl,!1);a&&s.push(`canonicalWebPageURL=${encodeURIComponent(a)}`)}t.checkoutTitle&&s.push(`checkoutTitle=${encodeURIComponent(t.checkoutTitle)}`),t.checkoutSubtitle&&s.push(`checkoutSubtitle=${encodeURIComponent(t.checkoutSubtitle)}`),t.price&&s.push(`price=${encodeURIComponent(t.price)}`),s.length>0&&(r+=`#${s.join("&")}`);let n=document.createElement("a");n.setAttribute("rel","ar"),n.setAttribute("href",r);let l=document.createElement("img");l.setAttribute("src","data:image/svg+xml;utf8,<svg/>"),l.style.display="none",n.appendChild(l),document.body.appendChild(n),n.click(),setTimeout(()=>{document.body.removeChild(n),i&&URL.revokeObjectURL(r.split("#")[0])},3e3)}function fi(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 ql(e){try{return fi(e,!0)}catch{throw new Error(`[XR-Live Security] Rejected unsafe URL scheme in Quick Look launch: ${(e||"").trim().slice(0,32)}`)}}function Kl(e,t={}){let r=fi(e,!0),i=t.mode||"ar_preferred",s=new URLSearchParams({file:r,mode:i,resizable:t.resizable!==!1?"true":"false",enable_vertical_placement:t.enableVerticalPlacement?"true":"false"});return t.title&&s.set("title",t.title),t.link&&s.set("link",fi(t.link,!1)),`intent://arvr.google.com/scene-viewer/1.0?${s.toString()}#Intent;scheme=https;package=com.google.ar.core;action=android.intent.action.VIEW;end;`}function Yl(e,t={}){if(typeof window>"u")throw new Error("launchSceneViewer requires a browser environment");let r=Kl(e,t);window.location.href=r}var Ot=null;function Zl(e,t){let r=new Float32Array(144),i=new Float32Array(144),s=new Float32Array(96),n=new Uint16Array(144);for(let h=0;h<24;h++){let c=h/24*Math.PI*2,f=Math.cos(c),p=Math.sin(c),m=h*2,g=m+1,x=(h+1)%24*2;r[m*3]=f*.11,r[m*3+1]=.002,r[m*3+2]=p*.11,r[g*3]=f*.145,r[g*3+1]=.002,r[g*3+2]=p*.145,i[m*3+1]=i[g*3+1]=1,n.set([m,x,g,g,x,x+1],h*6)}let l=e.createVertexArray();e.bindVertexArray(l);let a=(h,c,f)=>{let p=e.createBuffer();return e.bindBuffer(34962,p),e.bufferData(34962,h,35044),e.enableVertexAttribArray(c),e.vertexAttribPointer(c,f,5126,!1,0,0),p},o=[a(r,0,3),a(i,1,3),a(s,2,2)],u=e.createBuffer();return o.push(u),e.bindBuffer(34963,u),e.bufferData(34963,n,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:n.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:n,texture:null,metallicRoughnessTexture:null,normalTexture:null,occlusionTexture:null,normalScale:1,occlusionStrength:1,buffers:o}]}}function Qa(e,t,r,i,s){let n=Math.cos(i),l=Math.sin(i),a=Math.max(.01,s);e.fill(0),e[0]=a*n,e[2]=-a*l,e[5]=a,e[8]=a*l,e[10]=a*n,e[12]=t[0]-a*(n*r[0]+l*r[2]),e[13]=t[1]-a*r[1],e[14]=t[2]-a*(-l*r[0]+n*r[2]),e[15]=1}var Ql=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.");Ot&&Ot!==this&&Ot.isSessionActive()&&await Ot.stop().catch(()=>{});let r=navigator.xr,i=this.opts,s=t||e?.container,n=String(s?.tagName||"").toLowerCase()==="xr-live",l=e?.bounds,a=Number(l?.radius)||1,o=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||"",c=/Android|iPhone|iPad|iPod/i.test(h)&&!/Quest|Oculus|Pico|Vision/i.test(h),f=n?i.arScale==="fixed"?1:c?.55:1:i.arScale==="fixed"?1:a>.45?.3/a:a<.05?.12/Math.max(a,.001):1,p=n?[0,-.25,0]:[o[0]||0,i.arPlacement==="wall"?o[1]:u[1]??0,o[2]||0],m="immersive-ar";try{await r.isSessionSupported("immersive-ar")||(m="immersive-vr")}catch{m="immersive-vr"}let g=s?.querySelector?.('[slot="ar-overlay"]')||null,x=!1,b=null,v=()=>{x&&g?.parentNode&&g.parentNode.removeChild(g),g=null,b=null,x=!1};if(m==="immersive-ar"){if(g)g.addEventListener?.("beforexrselect",N=>N.preventDefault());else if(typeof document<"u"&&document.body&&typeof document.createElement=="function"){let N=document.createElement("div");N.style.cssText="position:fixed;inset:0;pointer-events:none;background:transparent!important;z-index:2147483647;font-family:system-ui,sans-serif;user-select:none";let 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",D=>D.preventDefault()),G.addEventListener("click",D=>{D.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",N.appendChild(G),N.appendChild(b),document.body.appendChild(N),g=N,x=!0}}let d=new Set(i.optionalFeatures||["local","local-floor","hit-test","light-estimation"]),y={requiredFeatures:i.requiredFeatures?[...i.requiredFeatures]:[],optionalFeatures:Array.from(d)};g&&(d.add("dom-overlay"),y.optionalFeatures=Array.from(d),y.domOverlay={root:g});for(let N of Fe)N.onConfigureXRSessionInit?.(s,y);Array.isArray(y.optionalFeatures)&&y.optionalFeatures.includes("dom-overlay")&&!y.domOverlay?.root&&(y.optionalFeatures=y.optionalFeatures.filter(N=>N!=="dom-overlay"));let M=N=>{let G=String(N?.name||"");return G==="NotAllowedError"||G==="SecurityError"};try{this.s=await r.requestSession(m,y)}catch(N){if(v(),M(N))throw i.onError?.(N),N;try{this.s=await r.requestSession(m,{requiredFeatures:[],optionalFeatures:["local","hit-test"]})}catch(G){if(M(G))throw i.onError?.(G),G;try{this.s=await r.requestSession(m)}catch(D){throw i.onError?.(D),D}}}let T=this.s;Ot=this,this.placed=!1;let V=null,q=null,P=null,R=null,C=null,B=[0,-.25,-1.2],L=[0,-.25,-1.2],w=new Float32Array(16),ie=new Float32Array(16),oe=!1,k=1,J=0,z=!1,Y=null,le=null,he=0,$=null,U=()=>{Ot===this&&(Ot=null),$?.(),$=null;try{q?.cancel?.()}catch{}if(q=null,P){let N=e?.meshes;if(Array.isArray(N)){let D=N.indexOf(P);D!==-1&&N.splice(D,1)}let G=e.getGLContext?.()||e?.gl;if(G)for(let D of P.primitives||[]){G.deleteVertexArray?.(D.vao);for(let F of D.buffers||[])G.deleteBuffer?.(F)}P=null}e?.setXRSessionActive?.(!1),v(),this.s=null,this.placed=!1,this.cleanFn=null};this.cleanFn=U,T.addEventListener("end",()=>{U(),i.onExit?.()}),T.addEventListener("select",()=>{if(!this.placed){let N=C||B;L=[N[0],N[1],N[2]],Qa(this.placedMat,L,p,J,f*k),this.placed=!0,P&&(P.visible=!1),b&&(b.textContent="Placed \u2022 Drag to move \u2022 Pinch to scale"),i.onPlaced?.(this.placedMat)}});try{let N=e.getGLContext?.()||e?.gl;N&&typeof N.makeXRCompatible=="function"&&await N.makeXRCompatible();let G=typeof XRWebGLLayer<"u"?XRWebGLLayer:globalThis?.XRWebGLLayer;N&&typeof G=="function"&&typeof T.updateRenderState=="function"&&T.updateRenderState({baseLayer:new G(T,N,{alpha:!0})});try{V=await T.requestReferenceSpace("local")}catch{try{V=await T.requestReferenceSpace("local-floor")}catch{V=await T.requestReferenceSpace("viewer")}}let D=await T.requestReferenceSpace("viewer").catch(()=>V);if(typeof T.requestHitTestSource=="function"&&D&&(q=await T.requestHitTestSource({space:D}).catch(()=>null)),m==="immersive-ar"&&N&&typeof N.createVertexArray=="function"&&Array.isArray(e.meshes)&&(P=Zl(N,i.reticleColor),e.meshes.push(P)),typeof window<"u"&&typeof window.addEventListener=="function"){let E=j=>Math.hypot(j.touches[1].clientX-j.touches[0].clientX,j.touches[1].clientY-j.touches[0].clientY),H=j=>Math.atan2(j.touches[1].clientY-j.touches[0].clientY,j.touches[1].clientX-j.touches[0].clientX),ee=j=>{this.s&&(j.touches.length===1&&this.placed?z=!0:j.touches.length>=2&&(z=!1,Y=E(j),le=H(j)))},ne=j=>{if(!this.s||j.touches.length<2)return;let A=E(j),S=H(j);if(Y&&Y>4&&i.arScale!=="fixed"&&(k=Math.max(.15,Math.min(6,k*(A/Y)))),le!==null){let _=S-le;_>Math.PI&&(_-=Math.PI*2),_<-Math.PI&&(_+=Math.PI*2),J-=_}Y=A,le=S},ae=j=>{(!j.touches||j.touches.length===0)&&(z=!1),(!j.touches||j.touches.length<2)&&(Y=null,le=null)};window.addEventListener("touchstart",ee,{passive:!0}),window.addEventListener("touchmove",ne,{passive:!0}),window.addEventListener("touchend",ae,{passive:!0}),window.addEventListener("touchcancel",ae,{passive:!0}),$=()=>{window.removeEventListener("touchstart",ee),window.removeEventListener("touchmove",ne),window.removeEventListener("touchend",ae),window.removeEventListener("touchcancel",ae)}}e.setXRSessionActive?.(!0);let F=(E,H)=>{if(this.s!==T)return;T.requestAnimationFrame(F);let ee=he>0?Math.min(Math.max((E-he)/1e3,0),.1):1/60;he=E,e?.stepXRUpdate?.(ee);let ne=H.getViewerPose(V);if(!ne)return;let ae=ne.views?.[0];if(!oe&&ae?.transform){let I=ae.transform.position,W=ae.transform.matrix,Q=I?.x??(W?W[12]:0),K=I?.y??(W?W[13]:0),Z=I?.z??(W?W[14]:0),X=W?-W[8]:0,re=W?-W[10]:-1,se=Math.hypot(X,re);se>1e-4?(X/=se,re/=se):(X=0,re=-1),B=[Q+X*1.2,K-.25,Z+re*1.2],J=Math.atan2(-X,-re),oe=!0}if(q&&typeof H.getHitTestResults=="function"&&(!this.placed||z)){let I=H.getHitTestResults(q)||[],W=!1;for(let Q of I){let K=Q.getPose(V);if(K?.transform?.matrix){let Z=K.transform.matrix,X=Z[5];if(i.arPlacement==="wall"&&Math.abs(X)>.35||i.arPlacement==="floor"&&Math.abs(X)<.65)continue;R||(R=new Float32Array(16)),R.set(Z),C=[Z[12],Z[13],Z[14]],this.placed&&z&&(L=[Z[12],Z[13],Z[14]]),P&&(P.visible=!this.placed||z,P.transform.set(Z)),!this.placed&&b&&(b.textContent="Surface found \u2022 Tap to place \u2022 Pinch to scale"),i.onHit?.(R),W=!0;break}}!W&&P&&(P.visible=!1)}Qa(w,this.placed?L:C||B,p,J,f*k),this.placed&&this.placedMat.set(w);let j=e.xrRigMatrix;j instanceof Float32Array&&j.length===16?ke(ie,j,w):ie.set(w),e.modelRootMatrix&&e.modelRootMatrix.set(ie);for(let I of Fe)I.onXRFrame?.(e,T,H,V);let A=e.getGLContext?.()||e?.gl,S=T.renderState?.baseLayer;A&&S&&S.framebuffer!==void 0&&A.bindFramebuffer(36160,S.framebuffer);let _=m==="immersive-ar",O=ne.views||[];for(let I=0;I<O.length;I++){let W=O[I];if(typeof e.renderXRView=="function"){let Q;if(S&&typeof S.getViewport=="function"){let K=S.getViewport(W);K&&K.width>0&&K.height>0&&(Q=[K.x,K.y,K.width,K.height])}else S?.framebufferWidth>0&&S?.framebufferHeight>0&&(Q=[0,0,S.framebufferWidth,S.framebufferHeight]);e.renderXRView(W,ie,this.placed,Q,_,I)}}A&&S&&S.framebuffer&&A.bindFramebuffer(36160,null)};T.requestAnimationFrame(F)}catch(N){throw typeof T.end=="function"&&await T.end().catch(()=>{}),U(),i.onError?.(N),N}}async stop(){let e=this.s;if(e)try{await e.end()}catch{}finally{this.cleanFn?.()}else this.cleanFn?.()}};async function on(e){let t=await mi(),r=e.preferredModes||["quick-look","webxr","scene-viewer"],i=null;for(let a of r)if(t.availableModes.includes(a)){i=a;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 s={...e.quickLookOptions,allowScale:e.arScale==="fixed"?!1:e.quickLookOptions?.allowScale},n={...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 a;if(e.model instanceof Blob&&e.model.type==="model/vnd.usdz+zip")a=e.model;else{if(typeof e.model=="string")return Za(e.model,s),{mode:"quick-look",success:!0};a=Vr(e.model)}return Za(a,s),{mode:"quick-look",success:!0}}if(i==="scene-viewer"){let a=e.glbUrl||(typeof e.model=="string"?e.model:null);if(!a)throw new Error("Scene Viewer requires a hosted GLB URL (glbUrl option).");return Yl(a,n),{mode:"scene-viewer",success:!0}}if(i==="webxr"){if(!e.view)throw new Error("WebXR AR mode requires an active ThreeView instance.");let a=new Ql(l);return await a.start(e.view,e.element),{mode:"webxr",success:!0,session:a}}}catch(a){return{mode:i,success:!1,error:a}}return{mode:i,success:!1,error:new Error(`Unhandled AR mode: ${i}`)}}ir.registerAR({activateAR:on,createUSDZBlob:Vr}),ir.registerScriptRunner(gr),He(ci);var ln=new WeakMap;function un(e,t){let r=t instanceof Float32Array?t:new Float32Array(t);ln.set(e,r)}function Ja(e){return ln.get(e)}async function Jl(e,t){if(!t)return null;let r;if(typeof t=="string")if(typeof fetch<"u"&&typeof createImageBitmap=="function"){let s=await(await fetch(t)).blob();r=await createImageBitmap(s)}else if(typeof Image<"u")r=await new Promise((s,n)=>{let l=new Image;l.crossOrigin="anonymous",l.onload=()=>s(l),l.onerror=n,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 hn=new WeakMap,eo=new Float32Array(16);async function to(e,t,r){let i=r?await Jl(e.gl,r):null;e[t]&&e.gl.deleteTexture(e[t]),e[t]=i}var cn={name:"environment-map",onContextRestored(e){hn.delete(e)},setEnvironmentImage(e,t){return to(e,"environmentTexture",t)},setSkyboxImage(e,t){return to(e,"skyboxTexture",t)},onBeforeDrawScene(e,t,r,i,s){if(!e.skyboxTexture||typeof t.createProgram!="function")return;let n=hn.get(t);if(!n){let c=(m,g)=>{let x=t.createShader(m);return t.shaderSource(x,g),t.compileShader(x),x},f=t.createProgram();t.attachShader(f,c(35633,`#version 300 es
|
|
374
|
-
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(
|
|
375
|
-
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=Fi(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(Du*16);for(let f=0;f<o.length&&f<Du;f++){let m=o[f],h=n[m]||lt();l.subarray(f*16,(f+1)*16).set(h)}let c=e.getUniformLocation(t,"uJointMatrix[0]");c&&e.uniformMatrix4fv(c,!1,l)}};Rt($u),Rt(Iu),Rt(ku),Rt(vo),Rt(lo);var m1=`#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.);}`,p1=`#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);}`,Xn=new WeakMap,Yf=new Float32Array(20);function Fu(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 d1(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 g1(e){let t=Xn.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,m1)),e.attachShader(i,r(35632,p1)),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")},Xn.set(e,t),t}var Ps={name:"contact-shadow",onContextRestored(e){Xn.delete(e)},onAfterRender(e,t,r){let i=t.shadowIntensity;if(i<=0||!t.bounds)return;let n=g1(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=d1(g);if(!x)continue;g.transform&&(x=Fu(g.transform,x)),t.modelRootMatrix&&(x=Fu(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=Fu(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);Yf.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,Yf),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=Xn.get(e);t&&(e.deleteVertexArray(t.vao),e.deleteBuffer(t.vbo),e.deleteBuffer(t.ibo),e.deleteProgram(t.prog),Xn.delete(e))}};function Bu(){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 zu(){if(typeof navigator>"u")return!1;let e=navigator.userAgent||"";return/android/i.test(e)}async function Vu(){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 Qf(){return(await Ns()).bestMode}async function Ns(){let[e,t,r]=await Promise.all([Vu(),Promise.resolve(Bu()),Promise.resolve(zu())]),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 Zf(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=y1(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=Cs(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 Cs(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 y1(e){try{return Cs(e,!0)}catch{throw new Error(`[XR-Live Security] Rejected unsafe URL scheme in Quick Look launch: ${(e||"").trim().slice(0,32)}`)}}function b1(e,t={}){let r=Cs(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",Cs(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 x1(e,t={}){if(typeof window>"u")throw new Error("launchSceneViewer requires a browser environment");let r=b1(e,t);window.location.href=r}var Ei=null;function v1(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 Jf(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 w1=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.");Ei&&Ei!==this&&Ei.isSessionActive()&&await Ei.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 Lt)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;Ei=this,this.placed=!1;let N=null,C=null,_=null,P=null,R=null,I=[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=()=>{Ei===this&&(Ei=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||I;F=[Z[0],Z[1],Z[2]],Jf(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)&&(_=v1(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),ke=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",ke,{passive:!0}),window.addEventListener("touchmove",_e,{passive:!0}),window.addEventListener("touchend",Le,{passive:!0}),window.addEventListener("touchcancel",Le,{passive:!0}),H=()=>{window.removeEventListener("touchstart",ke),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 ke=q>0?Math.min(Math.max((me-q)/1e3,0),.1):1/60;q=me,e?.stepXRUpdate?.(ke);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),I=[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)}Jf(V,this.placed?F:R||I,p,Q,h*re),this.placed&&this.placedMat.set(V);let ne=e.xrRigMatrix;ne instanceof Float32Array&&ne.length===16?ft(Y,ne,V):Y.set(V),e.modelRootMatrix&&e.modelRootMatrix.set(Y);for(let O of Lt)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 Uu(e){let t=await Ns(),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 Zf(e.model,n),{mode:"quick-look",success:!0};o=Aa(e.model)}return Zf(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 x1(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 w1(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}`)}}di.registerAR({activateAR:Uu,createUSDZBlob:Aa}),di.registerScriptRunner(Bn),Rt(Ps),Rt(_o);var Ou=new WeakMap;function ju(e,t){let r=t instanceof Float32Array?t:new Float32Array(t);Ou.set(e,r)}function em(e){return Ou.get(e)}async function M1(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 Gu=new WeakMap,tm=new Float32Array(16);async function rm(e,t,r){let i=r?await M1(e.gl,r):null;e[t]&&e.gl.deleteTexture(e[t]),e[t]=i}var Hu={name:"environment-map",onContextRestored(e){Gu.delete(e)},setEnvironmentImage(e,t){return rm(e,"environmentTexture",t)},setSkyboxImage(e,t){return rm(e,"skyboxTexture",t)},onBeforeDrawScene(e,t,r,i,n){if(!e.skyboxTexture||typeof t.createProgram!="function")return;let a=Gu.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},Gu.set(t,a)}let s=co(tm,r)||tm;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];
|
|
376
451
|
uniform int uHasSH;
|
|
377
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);}
|
|
378
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));}
|
|
379
|
-
void main(){`);return
|
|
454
|
+
void main(){`);return n=n.replace(`if(uHasEnvironmentMap==1){
|
|
380
455
|
specularIBL=texture(uEnvironmentMap,equirectangularUV(R)).rgb*(F*brdf.x+brdf.y);
|
|
381
456
|
envDiffuse=texture(uEnvironmentMap,equirectangularUV(N)).rgb;
|
|
382
457
|
}`,`if(uHasEnvironmentMap==1){
|
|
@@ -385,15 +460,15 @@ envDiffuse=uHasSH==1?evalSHIrradiance(N):textureLod(uEnvironmentMap,equirectangu
|
|
|
385
460
|
}else if(uHasSH==1){
|
|
386
461
|
specularIBL=getStudioRadiance(R,roughness)*integrateBRDFApprox(F,roughness,NoV);
|
|
387
462
|
envDiffuse=evalSHIrradiance(N);
|
|
388
|
-
}`),{vs:r,fs:s}},onBeforeDrawPrimitive(e,t,r,i,s,n){let l=ln.get(e),a=e.getUniformLocation(t,"uHasSH");if(l&&l.length>=27){a&&e.uniform1i(a,1);let o=e.getUniformLocation(t,"uSH");o&&e.uniform3fv(o,l)}else a&&e.uniform1i(a,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)}},mn=new WeakMap;function fn(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 s=0;s<i.length;s++){let n=i[s],l=n.getAttribute("data-position");if(!l)continue;let a=l.trim().split(/\s+/).map(c=>parseFloat(c.replace(/m$/,"")));if(a.length<3||a.some(isNaN))continue;let o=n.getAttribute("data-normal"),u;if(o){let c=o.trim().split(/\s+/).map(f=>parseFloat(f));c.length>=3&&!c.some(isNaN)&&(u=[c[0],c[1],c[2]])}let h=r.projectPointToScreen([a[0],a[1],a[2]],u);n.style.position="absolute",n.style.left="0",n.style.top="0",n.style.transform=`translate(-50%, -50%) translate3d(${h.x}px, ${h.y}px, 0)`,n.style.zIndex="3",h.visible?(n.style.opacity="1",n.style.pointerEvents="auto",n.removeAttribute("data-occluded")):(n.style.opacity="0",n.style.pointerEvents="none",n.setAttribute("data-occluded",""))}}var pn={name:"hotspots",updateHotspotsForElement:fn,onElementConnected(e){if(typeof MutationObserver>"u"||!e)return;let t=new MutationObserver(()=>{fn(e)});t.observe(e,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["data-position","data-normal"]}),mn.set(e,t)},onCameraChange(e,t){t&&fn(t,e)},onElementDisconnected(e){let t=mn.get(e);t&&(t.disconnect(),mn.delete(e))}},ro=1024,dn=256,pi=2048,eu=128,tu=64,ru=16,iu=1e4,su=8,yt=new Set(["__proto__","constructor","prototype"]),io={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))},so={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},di={translation:[0,0,0],rotation:[0,0,0,1],scale:[1,1,1]},gi=(e,t)=>e!==null&&typeof e=="object"&&!yt.has(t)&&Object.prototype.hasOwnProperty.call(e,t),rt=e=>Array.isArray(e)?[...e]:e,no=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)&&gi(e,"value")?e.value:e,_e=(e,t)=>gi(e.configuration,t)?no(e.configuration[t]):void 0,pe=(e,t=0)=>{let r=Number(e);return Number.isFinite(r)?r:t},Ut=e=>Math.max(0,Math.min(1,e)),st=e=>typeof e=="boolean"?e:typeof e=="number"?e!==0&&!Number.isNaN(e):typeof e=="string"?e.length>0&&e!=="false":!!e;function Mr(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||yt.has(i)||yt.has(r))return null;t.push(i)}return{segments:t}}var nr=(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},ao=e=>{let t=pe(e[0]),r=pe(e[1]),i=pe(e[2]),s=pe(e[3],1),n=Math.hypot(t,r,i,s);return n>1e-8?[t/n,r/n,i/n,s/n]:[0,0,0,1]},oo=(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 s=[0,0,0,1];return Xs(s,ao(e),ao(t),r),s}return e.slice(0,t.length).map((s,n)=>s+(t[n]-s)*r)}return r>=.5?t:e},gn=(e,t,r)=>Array.isArray(e)&&Array.isArray(t)?e.slice(0,t.length).map((i,s)=>r(pe(i),pe(t[s]))):Array.isArray(e)?e.map(i=>r(pe(i),pe(t))):Array.isArray(t)?t.map(i=>r(pe(e),pe(i))):r(pe(e),pe(t)),nu=(e,t)=>Array.isArray(e)?e.map(r=>t(pe(r))):t(pe(e)),lo=(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,yn=class{constructor(e,t,r){let i=Array.isArray(r.nodes)?r.nodes:[];if(i.length>ro)throw new Error(`SecurityError: Exceeds MAX_GRAPH_NODES (${ro})`);let s=Array.isArray(r.variables)?r.variables:[];if(s.length>dn)throw new Error(`SecurityError: Exceeds MAX_VARIABLES (${dn})`);let n=Array.isArray(r.declarations)?r.declarations:[],l=Array.isArray(r.events)?r.events:[],a=new Map,o=new Map,u=new Map,h=new Map,c=new Map,f=new Map,p=[],m=[],g=new Map,x=1,b=0,v=0,d=0,y=0,M=!1,T=!1,V=!1;s.forEach(($,U)=>{if(!$||typeof $!="object")return;let N=rt(no($.value));a.set(U,N);let G=$.id??$.name;typeof G=="string"&&G&&!yt.has(G)&&a.set(G,N)}),(t?.nodes||[]).forEach(($,U)=>{for(let N of $?.children||[])typeof N=="number"&&g.set(N,U)});let q=$=>$.op||typeof $.declaration=="number"&&n[$.declaration]?.op||"",P=($,U,N)=>{if(yt.has(U))return;let G=o.get($);G||o.set($,G=Object.create(null)),G[U]=N},R=($,U)=>{if(typeof $!="number"&&typeof $!="string"||typeof $=="string"&&yt.has($)||!a.has($)&&a.size>=dn*2)return;let N=rt(U);if(a.set($,N),typeof $=="number"){let G=s[$]?.id??s[$]?.name;typeof G=="string"&&!yt.has(G)&&a.set(G,N)}},C=$=>typeof $=="number"?l[$]?.id??String($):typeof $=="string"?/^\d+$/.test($)&&l[Number($)]?.id?l[Number($)].id:$:"",B=($,U)=>{for(let N=$,G=0;N!==void 0&&N>=0&&G<128;N=g.get(N),G++)if(N===U)return!0;return!1},L=$=>{for(let U=p.length-1;U>=0;U--)p[U].key===$&&p.splice(U,1)},w=$=>{L($.key),p.length>=eu&&p.shift(),p.push($)},ie=$=>{let U=Mr($)?.segments;if(U){if(U[0]==="nodes"&&Array.isArray(t?.nodes)){let N=t.nodes[nr(U[1],t.nodes.length)];if(!N)return;let G=U[2];if(G in di){let D=di[G],F=N[G]||D;return D.map((E,H)=>pe(F[H],E))}if(G==="weights"){let D=Array.isArray(N.weights)?N.weights:[0],F=U.length===4?nr(U[3],64):-2;return F===-2?D.map(E=>pe(E)):F>=0?pe(D[F]):void 0}if(G==="visible"||G==="extensions"&&U[3]==="KHR_node_visibility"&&U[4]==="visible")return N.extensions?.KHR_node_visibility?.visible??N.visible??!0}else if(U[0]==="materials"&&Array.isArray(t?.materials)){let N=t.materials[nr(U[1],t.materials.length)];if(!N)return;let G=N.pbrMetallicRoughness||{};if(U[2]==="pbrMetallicRoughness"){if(U[3]==="baseColorFactor"){let D=G.baseColorFactor||[1,1,1,1];return[pe(D[0],1),pe(D[1],1),pe(D[2],1),pe(D[3],1)]}if(U[3]==="metallicFactor"||U[3]==="roughnessFactor")return pe(G[U[3]],1)}if(U[2]==="emissiveFactor"){let D=N.emissiveFactor||[0,0,0];return[pe(D[0]),pe(D[1]),pe(D[2])]}if(U[2]==="alphaCutoff")return pe(N.alphaCutoff,.5)}}},oe=($,U)=>{let N=Mr($)?.segments;if(!N)return!1;if(N[0]==="nodes"&&Array.isArray(t?.nodes)){let G=nr(N[1],t.nodes.length),D=t.nodes[G];if(!D)return!1;let F=N[2];if(F in di&&Array.isArray(U)){let E=di[F];if(U.length<E.length)return!1;let H=E.map((ne,ae)=>pe(U[ae],ne));if(F==="rotation"){let ne=Math.hypot(...H);H=ne>1e-8?H.map(ae=>ae/ne):[0,0,0,1]}D[F]=H,delete D.matrix;let ee=e?.initialNodeTransforms?.[G];return ee&&(ee[F[0]]=[...H]),M=!0,!0}if(F==="weights"){Array.isArray(D.weights)||(D.weights=[]);let E=(H,ee)=>{for(let ne of e?.meshes||[])if(ne.nodeIndex===G)for(let ae of ne.primitives||[])ae.pluginData?.morph?.weights&&(ae.pluginData.morph.weights[H]=ee)};if(N.length===4){let H=nr(N[3],64);if(H<0)return!1;E(H,D.weights[H]=pe(U))}else if(Array.isArray(U))D.weights=U.slice(0,64).map(H=>pe(H)),D.weights.forEach((H,ee)=>E(ee,H));else return!1;return V=!0,!0}if(F==="visible"||F==="extensions"&&N[3]==="KHR_node_visibility"&&N[4]==="visible"){let E=st(U);return D.visible=E,(!D.extensions||typeof D.extensions!="object")&&(D.extensions={}),D.extensions.KHR_node_visibility={visible:E},T=!0,!0}}else if(N[0]==="materials"&&Array.isArray(t?.materials)){let G=nr(N[1],t.materials.length),D=t.materials[G];if(!D)return!1;let F=D.pbrMetallicRoughness||(D.pbrMetallicRoughness={}),E=H=>{for(let ee of e?.meshes||[])for(let ne of ee.primitives||[])(ne.materialIndex??0)===G&&H(ne)};if(N[2]==="pbrMetallicRoughness"){if(N[3]==="baseColorFactor"&&Array.isArray(U)&&U.length>=3){let H=[Ut(pe(U[0],1)),Ut(pe(U[1],1)),Ut(pe(U[2],1)),U[3]!==void 0?Ut(pe(U[3],1)):F.baseColorFactor?.[3]??1];return F.baseColorFactor=H,E(ee=>ee.baseColor=[...H]),V=!0}if(N[3]==="metallicFactor"||N[3]==="roughnessFactor"){let H=N[3]==="metallicFactor",ee=Ut(pe(U,H?0:.5));return F[N[3]]=ee,E(ne=>ne[H?"metallic":"roughness"]=ee),V=!0}}if(N[2]==="emissiveFactor"&&Array.isArray(U)&&U.length>=3)return D.emissiveFactor=[0,1,2].map(H=>Math.max(0,pe(U[H]))),V=!0;if(N[2]==="alphaCutoff")return D.alphaCutoff=Ut(pe(U,.5)),V=!0}return!1},k=($,U,N=new Set)=>{let G=_e(U,"pointer");if(typeof G!="string"||!G.startsWith("/"))return null;let D=G.replace(/\{([a-zA-Z0-9_]+)\}/g,(F,E)=>{let H=Math.trunc(Number(J($,E,void 0,N)??_e(U,E)));return Number.isSafeInteger(H)&&H>=0?String(H):"-1"});return Mr(D)?D:null},J=($,U,N,G)=>{let D=i[$]?.values;if(!gi(D,U))return N;let F=D[U];if(F==null)return N;if(typeof F!="object"||Array.isArray(F))return rt(F);let E=F;return typeof E.node=="number"?z(E.node,E.socket||"value",G):gi(E,"value")?rt(E.value):N},z=($,U,N)=>{if($<0||$>=i.length||N.has($)||N.size>128||++d>iu)return;let G=i[$],D=q(G);if(/^(event\/|pointer\/on|scene\/on|flow\/)/.test(D))return rt(o.get($)?.[U]);N.add($);try{let F=(E,H=0)=>J($,E,H,N);if(D==="variable/get"){let E=_e(G,"variable")??_e(G,"id");return typeof E=="number"||typeof E=="string"?rt(a.get(E)):void 0}if(D==="pointer/get"){let E=k($,G,N);return E?ie(E):void 0}if(D.startsWith("math/")){let E=D.slice(5);if(E in io)return nu(F("a"),io[E]);if(E in so){let H=/^(mul|div|rem|mod|pow)$/.test(E)?1:0;return gn(F("a",E==="mul"?1:0),F("b",H),so[E])}if(E==="pi")return Math.PI;if(E==="e")return Math.E;if(E==="random")return Math.random();if(E==="clamp")return gn(gn(F("a"),F("b",F("min",0)),Math.max),F("c",F("max",1)),Math.min);if(E==="mix"||E==="quatSlerp")return oo(F("a",0),F("b",1),pe(F("c",F("t",.5)),.5),E==="quatSlerp");if(E==="dot"){let H=F("a"),ee=F("b");return Array.isArray(H)&&Array.isArray(ee)?H.reduce((ne,ae,j)=>ne+(ae||0)*(ee[j]||0),0):pe(H)*pe(ee)}if(E==="cross"){let H=F("a",[0,0,0]),ee=F("b",[0,0,0]);return Array.isArray(H)&&Array.isArray(ee)?[(H[1]||0)*(ee[2]||0)-(H[2]||0)*(ee[1]||0),(H[2]||0)*(ee[0]||0)-(H[0]||0)*(ee[2]||0),(H[0]||0)*(ee[1]||0)-(H[1]||0)*(ee[0]||0)]:[0,0,0]}if(E==="length"){let H=F("a");return Array.isArray(H)?Math.hypot(...H):Math.abs(pe(H))}if(E==="distance"){let H=F("a"),ee=F("b");return Array.isArray(H)&&Array.isArray(ee)?Math.hypot(...H.map((ne,ae)=>(ne||0)-(ee[ae]||0))):Math.abs(pe(H)-pe(ee))}if(E==="normalize"){let H=F("a");if(!Array.isArray(H))return pe(H)>=0?1:-1;let ee=Math.hypot(...H);return ee>1e-8?H.map(ne=>ne/ee):H.map(()=>0)}if(E.startsWith("combine"))return["a","b","c","d"].slice(0,Number(E[7])||2).map(H=>pe(F(H)));if(E.startsWith("extract")){let H=F("a");return Array.isArray(H)?H[U==="0"||U==="x"?0:U==="1"||U==="y"?1:U==="2"||U==="z"?2:3]??0:0}if(E==="eq")return lo(F("a"),F("b"));if(E==="ne")return!lo(F("a"),F("b"));if(E==="lt")return pe(F("a"))<pe(F("b"));if(E==="le")return pe(F("a"))<=pe(F("b"));if(E==="gt")return pe(F("a"))>pe(F("b"));if(E==="ge")return pe(F("a"))>=pe(F("b"));if(E==="isNaN")return Number.isNaN(Number(F("a")));if(E==="isInf"){let H=Number(F("a"));return!Number.isFinite(H)&&!Number.isNaN(H)}return E==="and"?st(F("a",!1))&&st(F("b",!1)):E==="or"?st(F("a",!1))||st(F("b",!1)):E==="xor"?st(F("a",!1))!==st(F("b",!1)):E==="not"?!st(F("a",!1)):E==="select"?rt(st(F("condition",!1))?F("a"):F("b")):void 0}return D==="type/boolToInt"||D==="type/boolToFloat"?st(F("a",!1))?1:0:D==="type/intToBool"||D==="type/floatToBool"?pe(F("a",0))!==0:D==="type/intToFloat"?pe(F("a",0)):D==="type/floatToInt"?Math.trunc(pe(F("a",0))):void 0}finally{N.delete($)}},Y=()=>{if(M){M=!1,V=!0;let $=Rr(t);if(e){e.worldMatrices=$;for(let U of e.meshes||[])U.nodeIndex>=0&&U.nodeIndex<$.length&&(U.transform.set($[U.nodeIndex]),Ye(U.normalMatrix,U.transform))}}if(T){T=!1,V=!0;let $=t?.nodes;if(Array.isArray(e?.meshes)&&Array.isArray($))for(let U of e.meshes){let N=!0;for(let G=U.nodeIndex,D=0;G!==void 0&&G>=0&&D<128;G=g.get(G),D++){let F=$[G];if(F?.visible===!1||F?.extensions?.KHR_node_visibility?.visible===!1){N=!1;break}}U.visible=N}}V&&(V=!1,e?.render?.())},le=($,U={steps:0})=>{if(!$||typeof $.node!="number")return;U.steps===0&&(d=0);let N=[$],G=D=>{N.length+U.steps<pi&&N.push(D)};for(;N.length>0&&U.steps<pi;){U.steps++;let D=N.shift();if(!D||D.node<0||D.node>=i.length)continue;let F=D.node,E=i[F];if(!E)continue;let H=D.socket||"in",ee=q(E),ne=(j,A=void 0)=>J(F,j,A,new Set),ae=(j="out")=>{let A=E.flows?.[j];A&&G(A)};switch(ee){case"flow/branch":ae(st(ne("condition",!1))?"true":"false");break;case"flow/sequence":for(let j of Object.keys(E.flows||{}).sort((A,S)=>Number(A)-Number(S)||A.localeCompare(S)))ae(j);break;case"flow/switch":{let j=E.flows?.[String(ne("selection",ne("value",0)))]??E.flows?.default;j&&G(j);break}case"flow/for":{let j=Math.trunc(pe(ne("startIndex",0))),A=Math.trunc(pe(ne("endIndex",0))),S=Math.max(1,Math.trunc(pe(ne("step",1),1))),_=E.flows?.body;if(_&&A>j&&y<su){let I=Math.min(Math.ceil((A-j)/S),pi);y++;try{for(let W=0;W<I&&U.steps<pi;W++)P(F,"index",j+W*S),le(_,U)}finally{y--}}let O=E.flows?.completed??E.flows?.out;O&&G(O);break}case"flow/doN":{let j=H==="reset"?0:(u.get(F)||0)+1;if(u.set(F,j),P(F,"currentCount",j),P(F,"count",j),H!=="reset"){let A=Math.trunc(pe(ne("n",_e(E,"stopIterations")??_e(E,"n")??1),1));j<=A&&ae()}break}case"flow/multiGate":{if(H==="reset"){f.set(F,0);break}let j=Object.keys(E.flows||{}).sort();if(!j.length)break;let A=_e(E,"isRandom")?Math.floor(Math.random()*j.length):f.get(F)||0;A<j.length&&(ae(j[A]),f.set(F,_e(E,"isLoop")!==!1?(A+1)%j.length:A+1));break}case"flow/waitAll":{if(H==="reset"){h.delete(F);break}let j=h.get(F);j||h.set(F,j=new Set),j.add(H),j.size>=Math.max(1,Math.trunc(Number(_e(E,"inputFlows")??2)||2))&&(j.clear(),ae("out"),ae("completed"));break}case"flow/throttle":{if(H==="reset"){c.delete(F);break}let j=Math.max(0,pe(ne("duration",0))),A=c.get(F);A===void 0||b-A>=j?(c.set(F,b),P(F,"lastRemainingTime",0),ae()):P(F,"lastRemainingTime",Math.max(0,j-(b-A)));break}case"flow/delay":case"flow/setDelay":{if(H==="cancel"){for(let _=m.length-1;_>=0;_--)m[_].nodeIdx===F&&m.splice(_,1);P(F,"lastDelayIndex",-1);break}let j=Math.max(0,pe(ne("duration",_e(E,"duration")??0))),A=E.flows?.done??E.flows?.out;if(j<=0){P(F,"lastDelayIndex",-1),A&&G(A);break}m.length>=tu&&m.shift();let S=x++;P(F,"lastDelayIndex",S),m.push({id:S,nodeIdx:F,rem:j,done:A}),ee==="flow/setDelay"&&E.flows?.out&&E.flows?.done&&ae("out");break}case"flow/cancelDelay":{let j=Math.trunc(pe(ne("delayIndex",-1),-1));if(j<0)m.length=0;else for(let A=m.length-1;A>=0;A--)m[A].id===j&&m.splice(A,1);ae();break}case"variable/set":R(_e(E,"variable")??_e(E,"id"),ne("value")),ae();break;case"variable/interpolate":{let j=_e(E,"variable")??_e(E,"id"),A=ne("value",ne("target")),S=Math.max(0,pe(ne("duration",_e(E,"duration")??.3),.3));j!==void 0&&A!==void 0&&w({key:`var:${String(j)}`,varKey:j,from:rt(ne("from")??a.get(j)??0),to:rt(A),dur:S,elapsed:0,quat:!1,linear:_e(E,"easing")==="linear",done:E.flows?.done}),ae();break}case"pointer/set":{let j=k(F,E),A=ne("value");j&&A!==void 0&&(L(`ptr:${j}`),oe(j,A)),ae();break}case"pointer/interpolate":{let j=k(F,E),A=ne("value",ne("target")),S=Math.max(0,pe(ne("duration",_e(E,"duration")??.3),.3));if(j&&A!==void 0){let _=ne("from")??ie(j);_!==void 0&&(S<=0?(oe(j,A),ae("done")):w({key:`ptr:${j}`,ptr:j,from:rt(_),to:rt(A),dur:S,elapsed:0,quat:j.endsWith("/rotation"),linear:_e(E,"easing")==="linear",done:E.flows?.done}))}ae();break}case"animation/start":{let j=ne("animation")??_e(E,"animation")??_e(E,"clipName"),A=typeof j=="number"?e?.animations?.[j]?.name??t?.animations?.[j]?.name:typeof j=="string"?j:void 0;e?.playAnimation?.(A),V=!0,ae();break}case"animation/stop":case"animation/resetAt":e?.pauseAnimation?.(),ee==="animation/resetAt"&&e?.evaluateAnimation?.(pe(ne("time",0))),V=!0,ae();break;case"event/send":case"customEvent/send":{let j=C(_e(E,"event")??_e(E,"id")),A={};for(let S of Object.keys(E.values||{}))yt.has(S)||(A[S]=ne(S));j&&(typeof CustomEvent<"u"&&typeof e?.container?.dispatchEvent=="function"&&e.container.dispatchEvent(new CustomEvent("interactivityEvent",{bubbles:!0,composed:!0,detail:{id:j,values:A}})),he(j,A,U)),ae();break}default:ae();break}}};this.readScenePointer=ie,this.writeScenePointer=oe,this.fireOnStart=()=>{i.forEach($=>{q($)==="event/onStart"&&le($.flows?.out)}),Y()},this.fireOnSelect=$=>{if(!$)return;let U=typeof $.meshIndex=="number"?$.meshIndex:-1,N=typeof $.nodeIndex=="number"?$.nodeIndex:e?.meshes?.[U]?.nodeIndex??-1;i.forEach((G,D)=>{if(!/^(pointer|event|scene)\/onSelect$/.test(q(G)))return;let F=_e(G,"nodeIndex")??_e(G,"node")??J(D,"nodeIndex",void 0,new Set),E=_e(G,"meshName");if(typeof E=="string"&&E?$.meshName===E:F==null||Number(F)<0||Number.isNaN(Number(F))||B(N,Math.trunc(Number(F)))){if(P(D,"nodeIndex",N),P(D,"meshIndex",U),Array.isArray($.hitPoint)){let H=[pe($.hitPoint[0]),pe($.hitPoint[1]),pe($.hitPoint[2])];P(D,"hitPoint",H),P(D,"point",H),P(D,"intersectionPoint",H)}if(Array.isArray($.normal)){let H=[pe($.normal[0]),pe($.normal[1],1),pe($.normal[2])];P(D,"normal",H),P(D,"hitNormal",H)}typeof $.distance=="number"&&P(D,"distance",$.distance),le(G.flows?.out)}}),Y()},this.receiveCustomEvent=($,U={})=>he($,U,{steps:0});function he($,U,N){if(!(v>=ru)){v++;try{let G=C($);i.forEach((D,F)=>{if(!/^(customE|e)vent\/receive$/.test(q(D)))return;let E=_e(D,"event")??_e(D,"id");if(!(C(E)!==G&&String(E)!==String($))){for(let[H,ee]of Object.entries(U))yt.has(H)||P(F,H,rt(ee));le(D.flows?.out,N)}}),Y()}finally{v--}}}this.tick=$=>{if(!Number.isFinite($)||$<0)return;let U=Math.min($,.25);b+=U,i.forEach((G,D)=>{q(G)==="event/onTick"&&(P(D,"timeDelta",U),P(D,"dt",U),P(D,"timeElapsed",b),le(G.flows?.out))});let N=[];for(let G=p.length-1;G>=0;G--){let D=p[G];D.elapsed+=U;let F=D.dur>1e-6?Ut(D.elapsed/D.dur):1,E=D.linear?F:F*F*(3-2*F),H=oo(D.from,D.to,E,D.quat);D.ptr?oe(D.ptr,H):D.varKey!==void 0&&R(D.varKey,H),F>=1&&(p.splice(G,1),D.done&&N.push(D.done))}for(let G=m.length-1;G>=0;G--){let D=m[G];D.rem-=U,D.rem<=0&&(m.splice(G,1),D.done&&N.push(D.done))}for(let G of N)le(G);Y()},this.dispose=()=>{p.length=0,m.length=0,a.clear(),o.clear(),u.clear(),h.clear(),c.clear(),f.clear()}}},ut=new WeakMap,yi=new WeakMap;function au(e,t){if(!e||typeof e!="object"||!Number.isFinite(t)||t<=0||Hn().some(a=>a.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 s=Math.min(t,.1),n=(yi.get(e)||0)+s,l=!1;for(let a=0;a<i.length;a++){let o=i[a],u=Rl(o?.extras?.xr?.orbit);if(!u)continue;let h=0,c=0,f=0;if(Array.isArray(u.target))h=u.target[0],c=u.target[1],f=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=pe(b.translation[0]),c=pe(b.translation[1]),f=pe(b.translation[2]))}let p=u.phase+u.speed*n,m=h+Math.cos(p)*u.radius,g=c+u.height,x=f+Math.sin(p)*u.radius;if(o.translation=[m,g,x],u.faceCenter){let b=Math.atan2(h-m,f-x);o.rotation=[0,Math.sin(b*.5),0,Math.cos(b*.5)]}l=!0}if(l){yi.set(e,n);let a=Rr(r);e.worldMatrices=a;for(let o of e.meshes||[])o.nodeIndex>=0&&o.nodeIndex<a.length&&(o.transform.set(a[o.nodeIndex]),Ye(o.normalMatrix,o.transform))}}function bi(e){if(!(!e||typeof e!="object"))return ut.get(e)||ut.get(e.viewer)||ut.get(e._view)}function bn(e,t,r){let i=bi(e);return i?(i.receiveCustomEvent(t,r),!0):!1}var xn={name:"khr-interactivity",sendInteractivityEvent:bn,getInteractivityVM:bi,onLoadModel(e,t){if(!e||typeof e!="object")return;ut.get(e)?.dispose(),ut.delete(e),yi.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 s=new yn(e,t,i);ut.set(e,s),s.fireOnStart()},onMeshSelect(e,t){ut.get(e)?.fireOnSelect(t)},onUpdate(e,t){ut.get(e)?.tick(t),au(e,t)},onDestroy(e,t){ut.get(t)?.dispose(),ut.delete(t),yi.delete(t)}},wr=new Map,xi=new WeakMap;function uo(e,t){wr.set(e,t)}var vn={name:"materials",onContextRestored(e){xi.delete(e)},onBuildPrimitiveVAO(e,t,r,i,s){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=xi.get(e);r||(r=e.createTexture(),xi.set(e,r));let i=Math.max(1,t.canvas.width),s=Math.max(1,t.canvas.height);e.activeTexture(33990),e.bindTexture(3553,r),e.copyTexImage2D(3553,0,6408,0,0,i,s,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&&wr.has(t.name)){let m=wr.get(t.name);return{vs:m.vs||r,fs:m.fs||i}}let s=t.extensions||{},n=s.KHR_materials_clearcoat,l=s.KHR_materials_sheen,a=!!s.KHR_materials_transmission,o=!!s.KHR_materials_ior,u=s.KHR_materials_iridescence;if(!n&&!l&&!s.KHR_materials_unlit&&!a&&!s.KHR_materials_volume&&!o&&!s.KHR_materials_dispersion&&!u)return null;if(s.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(a){let m=h.includes("uniform vec2 uViewportSize;")?"":`uniform vec2 uViewportSize;
|
|
389
|
-
`;
|
|
390
|
-
${
|
|
391
|
-
vec2 sUV=gl_FragCoord.xy/max(uViewportSize,vec2(1.));float iorB=${
|
|
463
|
+
}`),{vs:r,fs:n}},onBeforeDrawPrimitive(e,t,r,i,n,a){let s=Ou.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)}},qu=new WeakMap;function Wu(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 Ku={name:"hotspots",updateHotspotsForElement:Wu,onElementConnected(e){if(typeof MutationObserver>"u"||!e)return;let t=new MutationObserver(()=>{Wu(e)});t.observe(e,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["data-position","data-normal"]}),qu.set(e,t)},onCameraChange(e,t){t&&Wu(t,e)},onElementDisconnected(e){let t=qu.get(e);t&&(t.disconnect(),qu.delete(e))}},im=1024,Xu=256,Es=2048,_1=128,S1=64,A1=16,T1=1e4,P1=8,ti=new Set(["__proto__","constructor","prototype"]),nm={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))},am={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},Ls={translation:[0,0,0],rotation:[0,0,0,1],scale:[1,1,1]},Rs=(e,t)=>e!==null&&typeof e=="object"&&!ti.has(t)&&Object.prototype.hasOwnProperty.call(e,t),Pr=e=>Array.isArray(e)?[...e]:e,sm=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)&&Rs(e,"value")?e.value:e,_t=(e,t)=>Rs(e.configuration,t)?sm(e.configuration[t]):void 0,Ge=(e,t=0)=>{let r=Number(e);return Number.isFinite(r)?r:t},Li=e=>Math.max(0,Math.min(1,e)),Dr=e=>typeof e=="boolean"?e:typeof e=="number"?e!==0&&!Number.isNaN(e):typeof e=="string"?e.length>0&&e!=="false":!!e;function Yn(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||ti.has(i)||ti.has(r))return null;t.push(i)}return{segments:t}}var tn=(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},om=e=>{let t=Ge(e[0]),r=Ge(e[1]),i=Ge(e[2]),n=Ge(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]},lm=(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 Nu(n,om(e),om(t),r),n}return e.slice(0,t.length).map((n,a)=>n+(t[a]-n)*r)}return r>=.5?t:e},Yu=(e,t,r)=>Array.isArray(e)&&Array.isArray(t)?e.slice(0,t.length).map((i,n)=>r(Ge(i),Ge(t[n]))):Array.isArray(e)?e.map(i=>r(Ge(i),Ge(t))):Array.isArray(t)?t.map(i=>r(Ge(e),Ge(i))):r(Ge(e),Ge(t)),N1=(e,t)=>Array.isArray(e)?e.map(r=>t(Ge(r))):t(Ge(e)),um=(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,Qu=class{constructor(e,t,r){let i=Array.isArray(r.nodes)?r.nodes:[];if(i.length>im)throw new Error(`SecurityError: Exceeds MAX_GRAPH_NODES (${im})`);let n=Array.isArray(r.variables)?r.variables:[];if(n.length>Xu)throw new Error(`SecurityError: Exceeds MAX_VARIABLES (${Xu})`);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=Pr(sm(H.value));o.set(te,Z);let ae=H.id??H.name;typeof ae=="string"&&ae&&!ti.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(ti.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"&&ti.has(H)||!o.has(H)&&o.size>=Xu*2)return;let Z=Pr(te);if(o.set(H,Z),typeof H=="number"){let ae=n[H]?.id??n[H]?.name;typeof ae=="string"&&!ti.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:"",I=(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>=_1&&p.shift(),p.push(H)},Y=H=>{let te=Yn(H)?.segments;if(te){if(te[0]==="nodes"&&Array.isArray(t?.nodes)){let Z=t.nodes[tn(te[1],t.nodes.length)];if(!Z)return;let ae=te[2];if(ae in Ls){let ie=Ls[ae],de=Z[ae]||ie;return ie.map((me,Se)=>Ge(de[Se],me))}if(ae==="weights"){let ie=Array.isArray(Z.weights)?Z.weights:[0],de=te.length===4?tn(te[3],64):-2;return de===-2?ie.map(me=>Ge(me)):de>=0?Ge(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[tn(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[Ge(ie[0],1),Ge(ie[1],1),Ge(ie[2],1),Ge(ie[3],1)]}if(te[3]==="metallicFactor"||te[3]==="roughnessFactor")return Ge(ae[te[3]],1)}if(te[2]==="emissiveFactor"){let ie=Z.emissiveFactor||[0,0,0];return[Ge(ie[0]),Ge(ie[1]),Ge(ie[2])]}if(te[2]==="alphaCutoff")return Ge(Z.alphaCutoff,.5)}}},J=(H,te)=>{let Z=Yn(H)?.segments;if(!Z)return!1;if(Z[0]==="nodes"&&Array.isArray(t?.nodes)){let ae=tn(Z[1],t.nodes.length),ie=t.nodes[ae];if(!ie)return!1;let de=Z[2];if(de in Ls&&Array.isArray(te)){let me=Ls[de];if(te.length<me.length)return!1;let Se=me.map((_e,Le)=>Ge(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 ke=e?.initialNodeTransforms?.[ae];return ke&&(ke[de[0]]=[...Se]),S=!0,!0}if(de==="weights"){Array.isArray(ie.weights)||(ie.weights=[]);let me=(Se,ke)=>{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]=ke)};if(Z.length===4){let Se=tn(Z[3],64);if(Se<0)return!1;me(Se,ie.weights[Se]=Ge(te))}else if(Array.isArray(te))ie.weights=te.slice(0,64).map(Se=>Ge(Se)),ie.weights.forEach((Se,ke)=>me(ke,Se));else return!1;return N=!0,!0}if(de==="visible"||de==="extensions"&&Z[3]==="KHR_node_visibility"&&Z[4]==="visible"){let me=Dr(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=tn(Z[1],t.materials.length),ie=t.materials[ae];if(!ie)return!1;let de=ie.pbrMetallicRoughness||(ie.pbrMetallicRoughness={}),me=Se=>{for(let ke of e?.meshes||[])for(let _e of ke.primitives||[])(_e.materialIndex??0)===ae&&Se(_e)};if(Z[2]==="pbrMetallicRoughness"){if(Z[3]==="baseColorFactor"&&Array.isArray(te)&&te.length>=3){let Se=[Li(Ge(te[0],1)),Li(Ge(te[1],1)),Li(Ge(te[2],1)),te[3]!==void 0?Li(Ge(te[3],1)):de.baseColorFactor?.[3]??1];return de.baseColorFactor=Se,me(ke=>ke.baseColor=[...Se]),N=!0}if(Z[3]==="metallicFactor"||Z[3]==="roughnessFactor"){let Se=Z[3]==="metallicFactor",ke=Li(Ge(te,Se?0:.5));return de[Z[3]]=ke,me(_e=>_e[Se?"metallic":"roughness"]=ke),N=!0}}if(Z[2]==="emissiveFactor"&&Array.isArray(te)&&te.length>=3)return ie.emissiveFactor=[0,1,2].map(Se=>Math.max(0,Ge(te[Se]))),N=!0;if(Z[2]==="alphaCutoff")return ie.alphaCutoff=Li(Ge(te,.5)),N=!0}return!1},re=(H,te,Z=new Set)=>{let ae=_t(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)??_t(te,me)));return Number.isSafeInteger(Se)&&Se>=0?String(Se):"-1"});return Yn(ie)?ie:null},Q=(H,te,Z,ae)=>{let ie=i[H]?.values;if(!Rs(ie,te))return Z;let de=ie[te];if(de==null)return Z;if(typeof de!="object"||Array.isArray(de))return Pr(de);let me=de;return typeof me.node=="number"?ee(me.node,me.socket||"value",ae):Rs(me,"value")?Pr(me.value):Z},ee=(H,te,Z)=>{if(H<0||H>=i.length||Z.has(H)||Z.size>128||++b>T1)return;let ae=i[H],ie=C(ae);if(/^(event\/|pointer\/on|scene\/on|flow\/)/.test(ie))return Pr(l.get(H)?.[te]);Z.add(H);try{let de=(me,Se=0)=>Q(H,me,Se,Z);if(ie==="variable/get"){let me=_t(ae,"variable")??_t(ae,"id");return typeof me=="number"||typeof me=="string"?Pr(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 nm)return N1(de("a"),nm[me]);if(me in am){let Se=/^(mul|div|rem|mod|pow)$/.test(me)?1:0;return Yu(de("a",me==="mul"?1:0),de("b",Se),am[me])}if(me==="pi")return Math.PI;if(me==="e")return Math.E;if(me==="random")return Math.random();if(me==="clamp")return Yu(Yu(de("a"),de("b",de("min",0)),Math.max),de("c",de("max",1)),Math.min);if(me==="mix"||me==="quatSlerp")return lm(de("a",0),de("b",1),Ge(de("c",de("t",.5)),.5),me==="quatSlerp");if(me==="dot"){let Se=de("a"),ke=de("b");return Array.isArray(Se)&&Array.isArray(ke)?Se.reduce((_e,Le,ne)=>_e+(Le||0)*(ke[ne]||0),0):Ge(Se)*Ge(ke)}if(me==="cross"){let Se=de("a",[0,0,0]),ke=de("b",[0,0,0]);return Array.isArray(Se)&&Array.isArray(ke)?[(Se[1]||0)*(ke[2]||0)-(Se[2]||0)*(ke[1]||0),(Se[2]||0)*(ke[0]||0)-(Se[0]||0)*(ke[2]||0),(Se[0]||0)*(ke[1]||0)-(Se[1]||0)*(ke[0]||0)]:[0,0,0]}if(me==="length"){let Se=de("a");return Array.isArray(Se)?Math.hypot(...Se):Math.abs(Ge(Se))}if(me==="distance"){let Se=de("a"),ke=de("b");return Array.isArray(Se)&&Array.isArray(ke)?Math.hypot(...Se.map((_e,Le)=>(_e||0)-(ke[Le]||0))):Math.abs(Ge(Se)-Ge(ke))}if(me==="normalize"){let Se=de("a");if(!Array.isArray(Se))return Ge(Se)>=0?1:-1;let ke=Math.hypot(...Se);return ke>1e-8?Se.map(_e=>_e/ke):Se.map(()=>0)}if(me.startsWith("combine"))return["a","b","c","d"].slice(0,Number(me[7])||2).map(Se=>Ge(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 um(de("a"),de("b"));if(me==="ne")return!um(de("a"),de("b"));if(me==="lt")return Ge(de("a"))<Ge(de("b"));if(me==="le")return Ge(de("a"))<=Ge(de("b"));if(me==="gt")return Ge(de("a"))>Ge(de("b"));if(me==="ge")return Ge(de("a"))>=Ge(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"?Dr(de("a",!1))&&Dr(de("b",!1)):me==="or"?Dr(de("a",!1))||Dr(de("b",!1)):me==="xor"?Dr(de("a",!1))!==Dr(de("b",!1)):me==="not"?!Dr(de("a",!1)):me==="select"?Pr(Dr(de("condition",!1))?de("a"):de("b")):void 0}return ie==="type/boolToInt"||ie==="type/boolToFloat"?Dr(de("a",!1))?1:0:ie==="type/intToBool"||ie==="type/floatToBool"?Ge(de("a",0))!==0:ie==="type/intToFloat"?Ge(de("a",0)):ie==="type/floatToInt"?Math.trunc(Ge(de("a",0))):void 0}finally{Z.delete(H)}},k=()=>{if(S){S=!1,N=!0;let H=An(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]),rr(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<Es&&Z.push(ie)};for(;Z.length>0&&te.steps<Es;){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",ke=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(ke){case"flow/branch":Le(Dr(_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(Ge(_e("startIndex",0))),Re=Math.trunc(Ge(_e("endIndex",0))),W=Math.max(1,Math.trunc(Ge(_e("step",1),1))),D=me.flows?.body;if(D&&Re>ne&&w<P1){let O=Math.min(Math.ceil((Re-ne)/W),Es);w++;try{for(let X=0;X<O&&te.steps<Es;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(Ge(_e("n",_t(me,"stopIterations")??_t(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=_t(me,"isRandom")?Math.floor(Math.random()*ne.length):h.get(de)||0;Re<ne.length&&(Le(ne[Re]),h.set(de,_t(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(_t(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,Ge(_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,Ge(_e("duration",_t(me,"duration")??0))),Re=me.flows?.done??me.flows?.out;if(ne<=0){_(de,"lastDelayIndex",-1),Re&&ae(Re);break}g.length>=S1&&g.shift();let W=v++;_(de,"lastDelayIndex",W),g.push({id:W,nodeIdx:de,rem:ne,done:Re}),ke==="flow/setDelay"&&me.flows?.out&&me.flows?.done&&Le("out");break}case"flow/cancelDelay":{let ne=Math.trunc(Ge(_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(_t(me,"variable")??_t(me,"id"),_e("value")),Le();break;case"variable/interpolate":{let ne=_t(me,"variable")??_t(me,"id"),Re=_e("value",_e("target")),W=Math.max(0,Ge(_e("duration",_t(me,"duration")??.3),.3));ne!==void 0&&Re!==void 0&&V({key:`var:${String(ne)}`,varKey:ne,from:Pr(_e("from")??o.get(ne)??0),to:Pr(Re),dur:W,elapsed:0,quat:!1,linear:_t(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,Ge(_e("duration",_t(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:Pr(D),to:Pr(Re),dur:W,elapsed:0,quat:ne.endsWith("/rotation"),linear:_t(me,"easing")==="linear",done:me.flows?.done}))}Le();break}case"animation/start":{let ne=_e("animation")??_t(me,"animation")??_t(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?.(),ke==="animation/resetAt"&&e?.evaluateAnimation?.(Ge(_e("time",0))),N=!0,Le();break;case"event/send":case"customEvent/send":{let ne=R(_t(me,"event")??_t(me,"id")),Re={};for(let W of Object.keys(me.values||{}))ti.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=_t(ae,"nodeIndex")??_t(ae,"node")??Q(ie,"nodeIndex",void 0,new Set),me=_t(ae,"meshName");if(typeof me=="string"&&me?H.meshName===me:de==null||Number(de)<0||Number.isNaN(Number(de))||I(Z,Math.trunc(Number(de)))){if(_(ie,"nodeIndex",Z),_(ie,"meshIndex",te),Array.isArray(H.hitPoint)){let Se=[Ge(H.hitPoint[0]),Ge(H.hitPoint[1]),Ge(H.hitPoint[2])];_(ie,"hitPoint",Se),_(ie,"point",Se),_(ie,"intersectionPoint",Se)}if(Array.isArray(H.normal)){let Se=[Ge(H.normal[0]),Ge(H.normal[1],1),Ge(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>=A1)){A++;try{let ae=R(H);i.forEach((ie,de)=>{if(!/^(customE|e)vent\/receive$/.test(C(ie)))return;let me=_t(ie,"event")??_t(ie,"id");if(!(R(me)!==ae&&String(me)!==String(H))){for(let[Se,ke]of Object.entries(te))ti.has(Se)||_(de,Se,Pr(ke));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?Li(ie.elapsed/ie.dur):1,me=ie.linear?de:de*de*(3-2*de),Se=lm(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()}}},Ur=new WeakMap,Is=new WeakMap;function C1(e,t){if(!e||typeof e!="object"||!Number.isFinite(t)||t<=0||Wc().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=(Is.get(e)||0)+n,s=!1;for(let o=0;o<i.length;o++){let l=i[o],c=Op(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=Ge(y.translation[0]),m=Ge(y.translation[1]),h=Ge(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){Is.set(e,a);let o=An(r);e.worldMatrices=o;for(let l of e.meshes||[])l.nodeIndex>=0&&l.nodeIndex<o.length&&(l.transform.set(o[l.nodeIndex]),rr(l.normalMatrix,l.transform))}}function $s(e){if(!(!e||typeof e!="object"))return Ur.get(e)||Ur.get(e.viewer)||Ur.get(e._view)}function Zu(e,t,r){let i=$s(e);return i?(i.receiveCustomEvent(t,r),!0):!1}var Ju={name:"khr-interactivity",sendInteractivityEvent:Zu,getInteractivityVM:$s,onLoadModel(e,t){if(!e||typeof e!="object")return;Ur.get(e)?.dispose(),Ur.delete(e),Is.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 Qu(e,t,i);Ur.set(e,n),n.fireOnStart()},onMeshSelect(e,t){Ur.get(e)?.fireOnSelect(t)},onUpdate(e,t){Ur.get(e)?.tick(t),C1(e,t)},onDestroy(e,t){Ur.get(t)?.dispose(),Ur.delete(t),Is.delete(t)}},Qn=new Map,Ds=new WeakMap;function cm(e,t){Qn.set(e,t)}var ec={name:"materials",onContextRestored(e){Ds.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=Ds.get(e);r||(r=e.createTexture(),Ds.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&&Qn.has(t.name)){let g=Qn.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);
|
|
392
467
|
vec3 refractedR=refract(-V,N,1./(iorB-.02*dV)),rG=refract(-V,N,1./iorB),refractedB=refract(-V,N,1./(iorB+.02*dV));
|
|
393
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);
|
|
394
|
-
vec3 aCol=vec3(${
|
|
395
|
-
vec3 volumeAtten=exp(-tV*(vec3(1.)-aCol)/max(${
|
|
396
|
-
diffuseIBL=mix(diffuseIBL,tr*volumeAtten*base.rgb,${m});`)}if(n&&!i.includes("uClearcoat")){let m=c(n.clearcoatFactor,1,0,1),g=c(n.clearcoatRoughnessFactor,0,0,1);h=h.replace("fragColor=vec4(color,base.a);",`vec3 ccF=F_SchlickRoughness(vec3(.04),${g},NoV)*${m};color=color*(vec3(1.)-ccF)+getStudioRadiance(R,${g})*ccF;fragColor=vec4(color,base.a);`)}if(l){let m=Array.isArray(l.sheenColorFactor)?l.sheenColorFactor:[1,1,1],g=`color+=vec3(${c(m[0],1,0,1)},${c(m[1],1,0,1)},${c(m[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,s,n){let l=r.materialIndex;if(l!==void 0&&n?.materials){let a=n.materials[l];a?.name&&wr.has(a.name)&&wr.get(a.name).onBindUniforms?.(e,t,r)}if(r.isTransmissive){let a=xi.get(e);if(a){e.activeTexture(33990),e.bindTexture(3553,a);let o=e.getUniformLocation(t,"uTransmissionTex");o&&e.uniform1i(o,6);let u=e.getUniformLocation(t,"uViewportSize");u&&e.uniform2f(u,e.drawingBufferWidth||1,e.drawingBufferHeight||1)}}}},ho=64*1024*1024,co=128*1024*1024,ou=16777216;function lu(e){return(e>>>1^-(e&1))&255}function uu(e){return(e>>>1^-(e&1))&65535}function hu(e){let t=e<<24>>24;return(t<<1^t>>7)&255}function mo(e){return(e<<1^e>>31)>>>0}function fo(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 ar(e){return Math.trunc(we(e+(e>=0?.5:-.5)))}function Mn(e,t,r,i="NONE"){if(fo(i),!i||i==="NONE"||t<=0)return;let s=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 c=r===8,f=c?32767:127,p=x=>c?s.getInt16(x,!0):s.getInt8(x),m=(x,b)=>c?s.setInt16(x,b,!0):s.setInt8(x,b<<24>>24),g=c?2:1;for(let x=0;x<t;x++){let b=x*r,v=p(b),d=p(b+g),y=we(p(b+2*g)-Math.abs(v)-Math.abs(d)),M=y>=0?0:y;v=we(v+(v>=0?M:-M)),d=we(d+(d>=0?M:-M));let T=we(Math.sqrt(we(we(we(v*v)+we(d*d))+we(y*y))));if(T===0){m(b,0),m(b+g,0),m(b+2*g,f);continue}let V=we(f/T);m(b,ar(we(v*V))),m(b+g,ar(we(d*V))),m(b+2*g,ar(we(y*V)))}return}if(i==="QUATERNION"){if(r!==8)throw Re(`QUATERNION filter requires byteStride 8 (got ${r})`);let c=we(32767/we(Math.SQRT2));for(let f=0;f<t;f++){let p=f*8,m=s.getInt16(p+6,!0),g=m|3,x=s.getInt16(p,!0),b=s.getInt16(p+2,!0),v=s.getInt16(p+4,!0),d=we(g*g),y=we(we(we(we(d*2)-we(x*x))-we(b*b))-we(v*v)),M=we(Math.sqrt(y>=0?y:0)),T=we(c/g),V=m&3,q=[0,0,0,0];q[V+1&3]=ar(we(x*T)),q[V+2&3]=ar(we(b*T)),q[V+3&3]=ar(we(v*T)),q[V]=Math.trunc(we(we(M*T)+.5));for(let P=0;P<4;P++)s.setInt16(p+P*2,q[P]<<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 c=t*r>>>2;for(let f=0;f<c;f++){let p=f*4,m=s.getUint32(p,!0),g=m<<8>>8,x=m>>24;s.setUint32(p,x+127<<23>>>0,!0);let b=s.getFloat32(p,!0);s.setFloat32(p,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 n=r===8,l=n?65535:255,a=c=>n?s.getUint16(c,!0):s.getUint8(c),o=c=>n?s.getInt16(c,!0):s.getInt8(c),u=(c,f)=>n?s.setUint16(c,f&65535,!0):s.setUint8(c,f&255),h=n?2:1;for(let c=0;c<t;c++){let f=c*r,p=a(f+3*h);p|=p>>1,p|=p>>2,p|=p>>4,p|=p>>8;let m=a(f),g=o(f+h),x=o(f+2*h),b=m+g-x,v=m+x,d=m-g-x,y=a(f+3*h);y=y<<1&p|y&1;let M=p===0?0:we(l/p);u(f,Math.trunc(we(we(b*M)+.5))),u(f+h,Math.trunc(we(we(v*M)+.5))),u(f+2*h,Math.trunc(we(we(d*M)+.5))),u(f+3*h,Math.trunc(we(we(y*M)+.5)))}}var po=160,ht=16,cu=24,go=32,mu=24,fu=[0,2,4,8],pu=[0,1,2,4,8];function yo(e){let t=Math.floor(8192/e)&~(ht-1);return t<256?t:256}function Re(e){return new Error(`EXT_meshopt_compression: ${e}`)}function du(e,t,r,i,s){if(s===0)return r.fill(0,i,i+ht),t;if(s===8)return r.set(e.subarray(t,t+ht),i),t+ht;let n=(1<<s)-1,l=8/s,a=t+ht*s/8;for(let o=0;o<ht;o++){let u=e[t+Math.floor(o/l)],h=o%l,c=s===1?u>>h&1:u>>8-s-h*s&n;r[i+o]=c===n?e[a++]:c}return a}function bo(e,t,r,i,s,n,l,a){let o=n/ht,u=o+3>>2;if(r-t<u)throw Re("truncated ATTRIBUTES stream");let h=t;t+=u;for(let c=0;c<o;c++){if(r-t<cu)throw Re("truncated ATTRIBUTES stream");let f=e[h+(c>>2)]>>(c&3)*2&3;t=du(e,t,i,s+c*ht,l[a+f])}return t}function gu(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 s=e.byteLength;if(s<1)throw Re("truncated ATTRIBUTES stream");let n=e[0];if((n&240)!==po)throw Re(`unsupported ATTRIBUTES header 0x${n.toString(16)}`);let l=n&15;if(l>1)throw Re(`unsupported ATTRIBUTES codec version ${l}`);let a=r+(l===0?0:r/4),o=l===0?go:mu,u=a<o?o:a;if(s-1<u)throw Re("truncated ATTRIBUTES stream");let h=s-a,c=e.slice(h,h+r),f=h+r,p=yo(r),m=new Uint8Array(256*4),g=1;for(let x=0;x<t;){let b=Math.min(p,t-x),v=b+ht-1&~(ht-1),d=l===0?0:r/4;if(s-g<d)throw Re("truncated ATTRIBUTES stream");let y=g;g+=d;for(let M=0;M<r;M+=4){let T=l===0?0:e[y+M/4];for(let P=0;P<4;P++){let R=T>>P*2&3;if(R===3){if(s-g<b)throw Re("truncated ATTRIBUTES stream");m.set(e.subarray(g,g+b),P*b),g+=b}else R===2?m.fill(0,P*b,P*b+b):g=l===0?bo(e,g,s,m,P*b,v,fu,0):bo(e,g,s,m,P*b,v,pu,R)}let V=l===0?0:e[f+M/4],q=V&3;if(q===0)for(let P=0;P<4;P++){let R=c[M+P];for(let C=0;C<b;C++)R=lu(m[P*b+C])+R&255,i[(x+C)*r+M+P]=R}else if(q===1)for(let P=0;P<4;P+=2){let R=c[M+P]|c[M+P+1]<<8,C=P*b;for(let B=0;B<b;B++){let L=m[C+B]|m[C+b+B]<<8;R=uu(L)+R&65535;let w=(x+B)*r+M+P;i[w]=R&255,i[w+1]=R>>8}}else if(q===2){let P=32-(V>>4)&31,R=(c[M]|c[M+1]<<8|c[M+2]<<16|c[M+3]<<24)>>>0;for(let C=0;C<b;C++){let B=(m[C]|m[b+C]<<8|m[2*b+C]<<16|m[3*b+C]<<24)>>>0;B=((B<<P|B>>>(32-P&31))^R)>>>0,R=B;let L=(x+C)*r+M;i[L]=B&255,i[L+1]=B>>>8&255,i[L+2]=B>>>16&255,i[L+3]=B>>>24}}else throw Re(`invalid ATTRIBUTES channel ${V}`)}c.set(i.subarray((x+b-1)*r,(x+b)*r)),x+=b}if(s-g!==u)throw Re("ATTRIBUTES trailing data")}var xo=224,vo=208;function Mo(e,t){let r=e[t.pos++]??0;if(r<128)return r;let i=r&127,s=7;for(let n=0;n<4;n++){let l=e[t.pos++]??0;if(i=(i|(l&127)<<s)>>>0,s+=7,l<128)break}return i>>>0}function vi(e,t,r){let i=Mo(e,t),s=i>>>1^-(i&1);return r+s>>>0}function yu(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 s=e[0];if((s&240)!==xo)throw Re(`unsupported TRIANGLES header 0x${s.toString(16)}`);let n=s&15;if(n>1)throw Re(`unsupported TRIANGLES codec version ${n}`);let l=new Uint32Array(16).fill(4294967295),a=new Uint32Array(16).fill(4294967295),o=new Uint32Array(16).fill(4294967295),u=0,h=0,c=(T,V)=>{l[u]=T,a[u]=V,u=u+1&15},f=(T,V=1)=>{o[h]=T,h=h+V&15},p=0,m=0,g=n>=1?13:15,x=1+i,b=e.byteLength-16,v=b,d={pos:x},y=0,M=(T,V,q)=>{r(y++,T),r(y++,V),r(y++,q)};for(let T=1;T<x;T++){let V=e[T];if(V<240){let q=V>>4,P=u-1-q&15,R=l[P],C=a[P],B=0,L=V&15;if(L<g){let w=o[h-1-L&15];B=L===0?p:w;let ie=L===0?1:0;p=p+ie>>>0,f(B,ie)}else{if(d.pos>b)throw Re("truncated TRIANGLES stream");B=L!==15?m+(L*2-27)>>>0:vi(e,d,m),m=B,f(B)}c(B,C),c(R,B),M(R,C,B)}else if(V<254){let q=e[v+(V&15)],P=q>>4,R=q&15,C=p;p=p+1>>>0;let B=o[h-P&15],L=P===0?p:B,w=P===0?1:0;p=p+w>>>0;let ie=o[h-R&15],oe=R===0?p:ie,k=R===0?1:0;p=p+k>>>0,M(C,L,oe),f(C),f(L,w),f(oe,k),c(L,C),c(oe,L),c(C,oe)}else{if(d.pos>b)throw Re("truncated TRIANGLES stream");let q=e[d.pos++],P=V===254?0:15,R=q>>4,C=q&15;q===0&&(p=0);let B=0;P===0&&(B=p,p=p+1>>>0);let L;R===0?(L=p,p=p+1>>>0):L=o[h-R&15];let w;C===0?(w=p,p=p+1>>>0):w=o[h-C&15],P===15&&(m=B=vi(e,d,m)),R===15&&(m=L=vi(e,d,m)),C===15&&(m=w=vi(e,d,m)),M(B,L,w),f(B),f(L,R===0||R===15?1:0),f(w,C===0||C===15?1:0),c(L,B),c(w,L),c(B,w)}}if(d.pos!==b)throw Re("TRIANGLES trailing data")}function bu(e,t,r){if(e.byteLength<1+t+4)throw Re("truncated INDICES stream");let i=e[0];if((i&240)!==vo)throw Re(`unsupported INDICES header 0x${i.toString(16)}`);let s=i&15;if(s>1)throw Re(`unsupported INDICES codec version ${s}`);let n=e.byteLength-4,l=[0,0],a={pos:1};for(let o=0;o<t;o++){if(a.pos>=n)throw Re("truncated INDICES stream");let u=Mo(e,a),h=u&1;u>>>=1;let c=u>>>1^-(u&1),f=l[h]+c>>>0;l[h]=f,r(o,f)}if(a.pos!==n)throw Re("INDICES trailing data")}function wn(e,t,r,i,s="NONE"){if(fo(s),!Number.isInteger(t)||t<0||t>ou||!Number.isInteger(r)||r<=0||r>256)throw Re(`invalid count (${t}) or byteStride (${r})`);let n=t*r;if(n>ho)throw Re(`decompressed size (${n}) exceeds MAX_MESHOPT_BUFFER_BYTES (${ho})`);if(t===0)return new Uint8Array(0);let l=new Uint8Array(n);if(i==="ATTRIBUTES")return gu(e,t,r,l),Mn(l,t,r,s),l;if(i==="TRIANGLES"||i==="INDICES"){if(r!==2&&r!==4)throw Re(`${i} byteStride must be 2 or 4 (got ${r})`);if(s&&s!=="NONE")throw Re(`filter ${s} is only valid for ATTRIBUTES`);let a=new DataView(l.buffer),o=r===2?(u,h)=>a.setUint16(u*2,h&65535,!0):(u,h)=>a.setUint32(u*4,h>>>0,!0);return i==="TRIANGLES"?yu(e,t,o):bu(e,t,o),l}throw Re(`unknown mode "${String(i)}"`)}function wo(e,t){t>>>=0;do e.push(t&127|(t>127?128:0)),t>>>=7;while(t)}function So(e,t,r,i){let s=t*r;if(e.byteLength<s)throw new Error(`encodeMeshoptBuffer: raw buffer (${e.byteLength}) smaller than count * byteStride (${s})`);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 a=[po],o=yo(r),u=new Uint8Array(r);t>0&&u.set(e.subarray(0,r));let h=u.slice(),c=new Uint8Array(256);for(let f=0;f<t;){let p=Math.min(o,t-f),m=p+15&-16;for(let g=0;g<r;g++){c.fill(0);let x=u[g];for(let d=0;d<p;d++){let y=e[(f+d)*r+g];c[d]=hu(y-x&255),x=y}u[g]=x;let b=m/16,v=a.length;for(let d=0;d<b+3>>2;d++)a.push(0);for(let d=0;d<b;d++){let y=c.subarray(d*16,d*16+16);if(!y.every(M=>M===0)){a[v+(d>>2)]|=3<<(d&3)*2;for(let M of y)a.push(M)}}}f+=p}for(let f=r;f<go;f++)a.push(0);for(let f=0;f<r;f++)a.push(h[f]);return new Uint8Array(a)}if(r!==2&&r!==4)throw new Error(`encodeMeshoptBuffer: ${i} byteStride must be 2 or 4 (got ${r})`);let n=new DataView(e.buffer,e.byteOffset,e.byteLength),l=a=>r===2?n.getUint16(a*2,!0):n.getUint32(a*4,!0);if(i==="INDICES"){let a=[vo|1],o=0;for(let u=0;u<t;u++){let h=l(u),c=h-o|0;o=h,wo(a,mo(c)<<1>>>0)}return a.push(0,0,0,0),new Uint8Array(a)}if(i==="TRIANGLES"){if(t%3!==0)throw new Error(`encodeMeshoptBuffer: TRIANGLES count must be divisible by 3 (got ${t})`);let a=t/3,o=[xo|1];for(let h=0;h<a;h++)o.push(255);let u=0;for(let h=0;h<a;h++){o.push(255);for(let c=0;c<3;c++){let f=l(h*3+c);wo(o,mo(f-u|0)),u=f}}for(let h=0;h<16;h++)o.push(0);return new Uint8Array(o)}throw new Error(`encodeMeshoptBuffer: unknown mode "${String(i)}"`)}function Mi(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 s=new Uint8Array(r.bin),n=[],l=0;for(let c=0;c<i.bufferViews.length;c++){let f=i.bufferViews[c],p=f?.extensions?.KHR_meshopt_compression,m=p??f?.extensions?.EXT_meshopt_compression;if(!m||typeof m!="object")continue;let g=p?"KHR_meshopt_compression":"EXT_meshopt_compression",x=Number(m.count),b=Number(m.byteStride),v=Number(m.byteOffset??0),d=Number(m.byteLength??0),y=m.mode||"ATTRIBUTES",M=m.filter||"NONE";if(M==="COLOR"&&!p)throw Re(`bufferView ${c} uses the COLOR filter, which requires KHR_meshopt_compression`);if(Number(m.buffer??0)!==0)throw new Error(`${g}: bufferView ${c} references buffer ${String(m.buffer)}; only the GLB BIN chunk (buffer 0) is supported`);if(!Number.isInteger(v)||v<0||!Number.isInteger(d)||d<0||v+d>s.byteLength)throw new Error(`${g}: bufferView ${c} compressed range [${v}, ${v+d}] out of bounds (${s.byteLength})`);let T=x*b;if(l+=T,l>co)throw Re(`total decompressed size (${l}) exceeds MAX_MESHOPT_TOTAL_BYTES (${co})`);let V=s.subarray(v,v+d),q=wn(V,x,b,y,M);n.push({index:c,bytes:q,ext:m})}if(n.length===0)return;let a=s.byteLength+3&-4,o=0;for(let c of n)o+=c.bytes.byteLength+3&-4;let u=new Uint8Array(a+o);u.set(s,0);let h=a;for(let c of n){u.set(c.bytes,h);let f=i.bufferViews[c.index];f.buffer=0,f.byteOffset=h,f.byteLength=c.bytes.byteLength,f._decoded=c.bytes,c.ext.mode==="ATTRIBUTES"&&f.byteStride===void 0&&(f.byteStride=Number(c.ext.byteStride)),f.extensions&&(delete f.extensions.EXT_meshopt_compression,delete f.extensions.KHR_meshopt_compression),h+=c.bytes.byteLength+3&-4}r.bin=u.buffer}var wi={decodeBufferViews(e,t){Mi(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}};Se().decoders.set("meshopt",wi);var Sn={name:"meshopt",onParseGLB(e){Se().decoders.set("meshopt",wi),Mi(e)}},xu=`#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&&Qn.has(o.name)&&Qn.get(o.name).onBindUniforms?.(e,t,r)}if(r.isTransmissive){let o=Ds.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)}}}},hm=64*1024*1024,fm=128*1024*1024,E1=16777216;function L1(e){return(e>>>1^-(e&1))&255}function R1(e){return(e>>>1^-(e&1))&65535}function I1(e){let t=e<<24>>24;return(t<<1^t>>7)&255}function mm(e){return(e<<1^e>>31)>>>0}function pm(e){if(e!==void 0&&e!=="NONE"&&e!=="OCTAHEDRAL"&&e!=="QUATERNION"&&e!=="EXPONENTIAL"&&e!=="COLOR")throw mt(`unknown filter "${String(e)}"`)}var st=Math.fround;function rn(e){return Math.trunc(st(e+(e>=0?.5:-.5)))}function tc(e,t,r,i="NONE"){if(pm(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 mt(`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=st(p(y+2*x)-Math.abs(A)-Math.abs(b)),S=w>=0?0:w;A=st(A+(A>=0?S:-S)),b=st(b+(b>=0?S:-S));let E=st(Math.sqrt(st(st(st(A*A)+st(b*b))+st(w*w))));if(E===0){g(y,0),g(y+x,0),g(y+2*x,h);continue}let N=st(h/E);g(y,rn(st(A*N))),g(y+x,rn(st(b*N))),g(y+2*x,rn(st(w*N)))}return}if(i==="QUATERNION"){if(r!==8)throw mt(`QUATERNION filter requires byteStride 8 (got ${r})`);let m=st(32767/st(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=st(x*x),w=st(st(st(st(b*2)-st(v*v))-st(y*y))-st(A*A)),S=st(Math.sqrt(w>=0?w:0)),E=st(m/x),N=g&3,C=[0,0,0,0];C[N+1&3]=rn(st(v*E)),C[N+2&3]=rn(st(y*E)),C[N+3&3]=rn(st(A*E)),C[N]=Math.trunc(st(st(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 mt(`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,st(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:st(s/p);c(h,Math.trunc(st(st(y*S)+.5))),c(h+f,Math.trunc(st(st(A*S)+.5))),c(h+2*f,Math.trunc(st(st(b*S)+.5))),c(h+3*f,Math.trunc(st(st(w*S)+.5)))}}var dm=160,Or=16,$1=24,gm=32,D1=24,k1=[0,2,4,8],F1=[0,1,2,4,8];function ym(e){let t=Math.floor(8192/e)&~(Or-1);return t<256?t:256}function mt(e){return new Error(`EXT_meshopt_compression: ${e}`)}function B1(e,t,r,i,n){if(n===0)return r.fill(0,i,i+Or),t;if(n===8)return r.set(e.subarray(t,t+Or),i),t+Or;let a=(1<<n)-1,s=8/n,o=t+Or*n/8;for(let l=0;l<Or;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 bm(e,t,r,i,n,a,s,o){let l=a/Or,c=l+3>>2;if(r-t<c)throw mt("truncated ATTRIBUTES stream");let f=t;t+=c;for(let m=0;m<l;m++){if(r-t<$1)throw mt("truncated ATTRIBUTES stream");let h=e[f+(m>>2)]>>(m&3)*2&3;t=B1(e,t,i,n+m*Or,s[o+h])}return t}function z1(e,t,r,i){if(r%4!==0||r>256)throw mt(`ATTRIBUTES byteStride must be a multiple of 4 and <= 256 (got ${r})`);let n=e.byteLength;if(n<1)throw mt("truncated ATTRIBUTES stream");let a=e[0];if((a&240)!==dm)throw mt(`unsupported ATTRIBUTES header 0x${a.toString(16)}`);let s=a&15;if(s>1)throw mt(`unsupported ATTRIBUTES codec version ${s}`);let o=r+(s===0?0:r/4),l=s===0?gm:D1,c=o<l?l:o;if(n-1<c)throw mt("truncated ATTRIBUTES stream");let f=n-o,m=e.slice(f,f+r),h=f+r,p=ym(r),g=new Uint8Array(256*4),x=1;for(let v=0;v<t;){let y=Math.min(p,t-v),A=y+Or-1&~(Or-1),b=s===0?0:r/4;if(n-x<b)throw mt("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 mt("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?bm(e,x,n,g,_*y,A,k1,0):bm(e,x,n,g,_*y,A,F1,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=L1(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 I=0;I<y;I++){let F=g[R+I]|g[R+y+I]<<8;P=R1(F)+P&65535;let V=(v+I)*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 I=(g[R]|g[y+R]<<8|g[2*y+R]<<16|g[3*y+R]<<24)>>>0;I=((I<<_|I>>>(32-_&31))^P)>>>0,P=I;let F=(v+R)*r+S;i[F]=I&255,i[F+1]=I>>>8&255,i[F+2]=I>>>16&255,i[F+3]=I>>>24}}else throw mt(`invalid ATTRIBUTES channel ${N}`)}m.set(i.subarray((v+y-1)*r,(v+y)*r)),v+=y}if(n-x!==c)throw mt("ATTRIBUTES trailing data")}var xm=224,vm=208;function wm(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 ks(e,t,r){let i=wm(e,t),n=i>>>1^-(i&1);return r+n>>>0}function V1(e,t,r){if(t%3!==0)throw mt(`TRIANGLES count must be divisible by 3 (got ${t})`);let i=t/3;if(e.byteLength<1+i+16)throw mt("truncated TRIANGLES stream");let n=e[0];if((n&240)!==xm)throw mt(`unsupported TRIANGLES header 0x${n.toString(16)}`);let a=n&15;if(a>1)throw mt(`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[_],I=0,F=N&15;if(F<x){let V=l[f-1-F&15];I=F===0?p:V;let Y=F===0?1:0;p=p+Y>>>0,h(I,Y)}else{if(b.pos>y)throw mt("truncated TRIANGLES stream");I=F!==15?g+(F*2-27)>>>0:ks(e,b,g),g=I,h(I)}m(I,R),m(P,I),S(P,R,I)}else if(N<254){let C=e[A+(N&15)],_=C>>4,P=C&15,R=p;p=p+1>>>0;let I=l[f-_&15],F=_===0?p:I,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 mt("truncated TRIANGLES stream");let C=e[b.pos++],_=N===254?0:15,P=C>>4,R=C&15;C===0&&(p=0);let I=0;_===0&&(I=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=I=ks(e,b,g)),P===15&&(g=F=ks(e,b,g)),R===15&&(g=V=ks(e,b,g)),S(I,F,V),h(I),h(F,P===0||P===15?1:0),h(V,R===0||R===15?1:0),m(F,I),m(V,F),m(I,V)}}if(b.pos!==y)throw mt("TRIANGLES trailing data")}function U1(e,t,r){if(e.byteLength<1+t+4)throw mt("truncated INDICES stream");let i=e[0];if((i&240)!==vm)throw mt(`unsupported INDICES header 0x${i.toString(16)}`);let n=i&15;if(n>1)throw mt(`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 mt("truncated INDICES stream");let c=wm(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 mt("INDICES trailing data")}function rc(e,t,r,i,n="NONE"){if(pm(n),!Number.isInteger(t)||t<0||t>E1||!Number.isInteger(r)||r<=0||r>256)throw mt(`invalid count (${t}) or byteStride (${r})`);let a=t*r;if(a>hm)throw mt(`decompressed size (${a}) exceeds MAX_MESHOPT_BUFFER_BYTES (${hm})`);if(t===0)return new Uint8Array(0);let s=new Uint8Array(a);if(i==="ATTRIBUTES")return z1(e,t,r,s),tc(s,t,r,n),s;if(i==="TRIANGLES"||i==="INDICES"){if(r!==2&&r!==4)throw mt(`${i} byteStride must be 2 or 4 (got ${r})`);if(n&&n!=="NONE")throw mt(`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"?V1(e,t,l):U1(e,t,l),s}throw mt(`unknown mode "${String(i)}"`)}function Mm(e,t){t>>>=0;do e.push(t&127|(t>127?128:0)),t>>>=7;while(t)}function _m(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=[dm],l=ym(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]=I1(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<gm;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=[vm|1],l=0;for(let c=0;c<t;c++){let f=s(c),m=f-l|0;l=f,Mm(o,mm(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=[xm|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);Mm(l,mm(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 Fs(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 mt(`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>fm)throw mt(`total decompressed size (${s}) exceeds MAX_MESHOPT_TOTAL_BYTES (${fm})`);let N=n.subarray(A,A+b),C=rc(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 Bs={decodeBufferViews(e,t){Fs(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}};We().decoders.set("meshopt",Bs);var ic={name:"meshopt",onParseGLB(e){We().decoders.set("meshopt",Bs),Fs(e)}},O1=`#version 300 es
|
|
397
472
|
layout(location=0) in vec3 aPosition;
|
|
398
473
|
layout(location=1) in vec3 aNormal;
|
|
399
474
|
uniform mat4 uMVP,uVP;
|
|
@@ -414,19 +489,19 @@ vec2 pxOffset=dir*(uOutlineThickness*2.0/max(uViewportSize,vec2(1.0)))*clipPos.w
|
|
|
414
489
|
clipPos.xy+=pxOffset;
|
|
415
490
|
clipPos.z+=1e-4*clipPos.w;
|
|
416
491
|
gl_Position=clipPos;
|
|
417
|
-
}`,
|
|
492
|
+
}`,j1=`#version 300 es
|
|
418
493
|
precision highp float;
|
|
419
494
|
uniform vec4 uOutlineColor;
|
|
420
495
|
out vec4 fragColor;
|
|
421
496
|
void main(){
|
|
422
497
|
fragColor=uOutlineColor;
|
|
423
|
-
}`,
|
|
498
|
+
}`,Sm=`#version 300 es
|
|
424
499
|
out vec2 vUV;
|
|
425
500
|
void main(){
|
|
426
501
|
vec2 pos=vec2((gl_VertexID<<1)&2,gl_VertexID&2);
|
|
427
502
|
vUV=pos;
|
|
428
503
|
gl_Position=vec4(pos*2.0-1.0,0.0,1.0);
|
|
429
|
-
}`,
|
|
504
|
+
}`,G1=`#version 300 es
|
|
430
505
|
precision highp float;
|
|
431
506
|
in vec2 vUV;
|
|
432
507
|
uniform sampler2D uSourceTex;
|
|
@@ -449,7 +524,7 @@ c+=prefilter(texture(uSourceTex,vUV+vec2(h.x,-h.y)).rgb)*0.125;
|
|
|
449
524
|
c+=prefilter(texture(uSourceTex,vUV+vec2(-h.x,h.y)).rgb)*0.125;
|
|
450
525
|
c+=prefilter(texture(uSourceTex,vUV+vec2(h.x,h.y)).rgb)*0.125;
|
|
451
526
|
fragColor=vec4(c,1.0);
|
|
452
|
-
}`,
|
|
527
|
+
}`,H1=`#version 300 es
|
|
453
528
|
precision highp float;
|
|
454
529
|
in vec2 vUV;
|
|
455
530
|
uniform sampler2D uBloomTex;
|
|
@@ -471,4 +546,674 @@ sum+=texture(uBloomTex,vUV+vec2(-d.x,-d.y)).rgb*2.0;
|
|
|
471
546
|
vec3 bloom=(sum/12.0)*uStrength;
|
|
472
547
|
float a=clamp(min(bloom.r,min(bloom.g,bloom.b)),0.0,1.0);
|
|
473
548
|
fragColor=vec4(bloom,a);
|
|
474
|
-
}`,Si=3,Sr=new WeakMap;function An(e,t=[.22,.74,.97]){let r=Sa(e,"");if(!r.startsWith("#"))return[t[0],t[1],t[2]];let i=r.slice(1);if(i.length===3){let s=+("0x"+i[0]+i[0])/255,n=+("0x"+i[1]+i[1])/255,l=+("0x"+i[2]+i[2])/255;return[s,n,l]}if(i.length===6){let s=+("0x"+i.slice(0,2))/255,n=+("0x"+i.slice(2,4))/255,l=+("0x"+i.slice(4,6))/255;return[s,n,l]}return[t[0],t[1],t[2]]}function To(e,t,r=.8,i=.5){let s=Number.isFinite(t)?Math.max(0,t):0;if(s<=0)return[0,0,0];let n=Math.max(0,Number(e[0])||0),l=Math.max(0,Number(e[1])||0),a=Math.max(0,Number(e[2])||0),o=Math.max(n,l,a);if(o<=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),c=Math.max(0,Math.min(2*h,o-u+h)),f=c*c/(4*h+1e-4),p=Math.min(1,Math.max(0,Math.max(f,o-u)/Math.max(o,1e-4)))*s;return[n*p,l*p,a*p]}function Po(e,t,r,i){let s=Number(e[0])||0,n=Number(e[1])||0,l=Math.hypot(s,n);if(l<=1e-5||t<=0||r<=0)return[0,0];let a=Math.max(1,Number(i[0])||1),o=Math.max(1,Number(i[1])||1),u=Math.max(0,r)*2*t;return[s/l*(u/a),n/l*(u/o)]}var Ro=new WeakSet;function Co(e){let t=Sr.get(e);if(t){if(typeof e.isProgram!="function"||e.isProgram(t.outlineProg))return t;Sr.delete(e)}if(Ro.has(e)||e.isContextLost?.())return null;let r=qt(e,xu,vu,!1),i=qt(e,Ao,Mu,!1),s=qt(e,Ao,wu,!1);if(!r||!i||!s){for(let l of[r,i,s])l&&e.deleteProgram(l);return Ro.add(e),null}let n=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:s,uUpBloomTex:e.getUniformLocation(s,"uBloomTex"),uUpTexelSize:e.getUniformLocation(s,"uTexelSize"),uUpRadius:e.getUniformLocation(s,"uRadius"),uUpStrength:e.getUniformLocation(s,"uStrength"),fsVao:n,sceneTex:null,bloomTex:[],bloomFbo:[],mipWidth:[],mipHeight:[],texWidth:0,texHeight:0},Sr.set(e,t),t}function Su(e,t,r,i){if(typeof e.createFramebuffer!="function"||typeof e.copyTexSubImage2D!="function")return!1;let s=Math.max(2,r|0),n=Math.max(2,i|0);if(t.sceneTex&&t.bloomFbo.length===Si&&t.texWidth===s&&t.texHeight===n)return!0;t.sceneTex||(t.sceneTex=e.createTexture()),e.bindTexture(3553,t.sceneTex),e.texImage2D(3553,0,6408,s,n,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=s,a=n;for(let o=0;o<Si;o++)l=Math.max(1,l>>1),a=Math.max(1,a>>1),t.mipWidth[o]=l,t.mipHeight[o]=a,t.bloomTex[o]||(t.bloomTex[o]=e.createTexture()),e.bindTexture(3553,t.bloomTex[o]),e.texImage2D(3553,0,6408,l,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),t.bloomFbo[o]||(t.bloomFbo[o]=e.createFramebuffer()),e.bindFramebuffer(36160,t.bloomFbo[o]),e.framebufferTexture2D(36160,36064,3553,t.bloomTex[o],0);return e.bindFramebuffer(36160,null),t.texWidth=s,t.texHeight=n,!0}function Au(e){let t=e.container;if(t&&typeof t.getAttribute=="function"){let i=t.getAttribute("bloom");if(i!==null){let s=i.trim().toLowerCase();if(s==="false"||s==="0"||s==="none")return null;let n=s===""||s==="true"?.35:Number(s);if(!Number.isFinite(n)||n<=0)return null;let l=Aa({strength:n,threshold:ui(t.getAttribute("bloom-threshold"),.62),radius:ui(t.getAttribute("bloom-radius"),.75)});if(l)return l}}let r=null;for(let i of e.meshes||[]){if(i.visible===!1)continue;let s=i?.extras?.xr?.bloom??i?.userData?.xr?.bloom,n=Aa(s);n&&(!r||n.strength>r.strength)&&(r=n)}return r}function Tu(e,t){if(e==null)return null;let r=e.trim(),i=r.toLowerCase();if(i==="false"||i==="0"||i==="none")return null;let s=t,n=3.5,l=!1;if(r&&i!=="true"){let a=r.split(/\s+/);for(let o of a)if(o.startsWith("#"))s=o;else if(o.toLowerCase()==="pulse")l=!0;else{let u=Number(o);Number.isFinite(u)&&u>0&&(n=u)}}return Ki({color:s,thickness:n,pulse:l})}var Pu=new Set(["floor","pedestal","ground","table","grid","pad"]);function Ru(e){return e.replace(/([a-z\d])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z]+/).some(t=>Pu.has(t))}function Cu(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 s=t?.extras?.xr?.outline??t?.userData?.xr?.outline,n=Ki(s);if(n)return n;let l=typeof r?.getAttribute=="function"&&r.getAttribute("outline-color")||"#38bdf8",a=Tu(i,l),o=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:a||(o?Ki({color:l,thickness:3,pulse:!1}):null);if(a){let h=t.name||"";return Ru(h)?null:a}return null}var Tn={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),s=Math.max(1,t.canvas?.height||150),n=[];for(let f of t.meshes){if(f.visible===!1)continue;let p=Cu(t,f);p&&n.push({mesh:f,trait:p})}let l=n.length>0?Co(e):null;if(l){let f=l,p=Ee(),m=Ee(),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),d=Math.max(1,b?.[3]||s);e.useProgram(f.outlineProg),f.uOutlineViewportSize&&e.uniform2f(f.uOutlineViewportSize,v,d),f.uOutlineVP&&e.uniformMatrix4fv(f.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 n){let[T,V,q]=An(M.color),P=M.pulse?.8+.25*Math.sin(x*4):1;f.uOutlineColor&&e.uniform4f(f.uOutlineColor,T,V,q,1),f.uOutlineThickness&&e.uniform1f(f.uOutlineThickness,M.thickness*P),y.worldSpace===!0?p.set(y.transform):ke(p,t.modelRootMatrix,y.transform);let R=y.instanceMatrices;for(let C of y.primitives)if(!(C.pluginData?.skinning?.hasSkin||C.pluginData?.morph?.hasMorph))if(e.bindVertexArray(C.vao),R&&R.length>=16){let B=R.length>>4,L=Ee();for(let w=0;w<B;w++)ke(L,p,R.subarray(w*16,w*16+16)),ke(m,r,L),Ye(g,L),e.uniformMatrix4fv(f.uOutlineMVP,!1,m),e.uniformMatrix3fv(f.uOutlineNormalMatrix,!1,g),C.indices?e.drawElements(4,C.indexCount,C.indexType,0):e.drawArrays(4,0,C.indexCount)}else ke(m,r,p),Ye(g,p),e.uniformMatrix4fv(f.uOutlineMVP,!1,m),e.uniformMatrix3fv(f.uOutlineNormalMatrix,!1,g),C.indices?e.drawElements(4,C.indexCount,C.indexType,0):e.drawArrays(4,0,C.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 a=Au(t);if(!a||a.strength<=0)return;let o=Co(e);if(!o||!Su(e,o,i,s)||!o.fsVao)return;e.activeTexture(33984),e.bindTexture(3553,o.sceneTex),e.copyTexSubImage2D(3553,0,0,0,0,0,i,s),e.disable(2929),e.depthMask(!1),e.disable(3042),e.useProgram(o.downProg),e.uniform1i(o.uDownSourceTex,0),e.bindVertexArray(o.fsVao);let u=o.sceneTex,h=i,c=s;for(let f=0;f<Si;f++){let p=o.mipWidth[f],m=o.mipHeight[f];e.bindFramebuffer(36160,o.bloomFbo[f]),e.viewport(0,0,p,m),e.bindTexture(3553,u),e.uniform2f(o.uDownTexelSize,1/h,1/c),e.uniform1f(o.uDownThreshold,f===0?a.threshold:0),e.drawArrays(4,0,3),u=o.bloomTex[f],h=p,c=m}e.enable(3042),typeof e.blendFuncSeparate=="function"?e.blendFuncSeparate(e.ONE,e.ONE,e.ONE,771):e.blendFunc(e.ONE,e.ONE),e.useProgram(o.upProg),e.uniform1i(o.uUpBloomTex,0),e.uniform1f(o.uUpRadius,a.radius);for(let f=Si-1;f>=1;f--){let p=f-1;e.bindFramebuffer(36160,o.bloomFbo[p]),e.viewport(0,0,o.mipWidth[p],o.mipHeight[p]),e.bindTexture(3553,o.bloomTex[f]),e.uniform2f(o.uUpTexelSize,1/o.mipWidth[f],1/o.mipHeight[f]),e.uniform1f(o.uUpStrength,.85),e.drawArrays(4,0,3)}e.bindFramebuffer(36160,null),e.viewport(0,0,i,s),e.bindTexture(3553,o.bloomTex[0]),e.uniform2f(o.uUpTexelSize,1/o.mipWidth[0],1/o.mipHeight[0]),e.uniform1f(o.uUpStrength,a.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=Sr.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);Sr.delete(e)}}};function Pn(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 s=t[i]?.name;r.push(typeof s=="string"&&s.length>0?s:`Variant_${i}`)}return r}function Eo(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 s=i,n=Number(s.material);if(!Number.isInteger(n)||n<0)continue;let l=[];if(Array.isArray(s.variants))for(let a of s.variants){let o=Number(a);Number.isInteger(o)&&o>=0&&l.push(o)}l.length>0&&r.push({material:n,variants:l})}return r}function Lo(e,t,r,i=0){let s=e;if(s&&typeof s.selectVariant=="function"&&!Array.isArray(t))return s.selectVariant(typeof t=="string"?t:null);let n=e,l=Array.isArray(t)?t:[],a=r??null;if(!a)return i;let o=Pn(n).indexOf(a);if(o<0)return i;for(let u of l)if(u.variants.includes(o))return u.material;return i}var Rn={name:"variants",onLoadModel(e,t){let r=e.getVariantName?.();r&&e.selectVariant(r)}},No=new WeakMap,Cn={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",s=>{s.preventDefault()})),t.optionalFeatures=Array.from(r)},onXRFrame(e,t,r,i){if(!e||!t||!r||!i)return;let s=No.get(t);if(s||(s={lightProbe:null},No.set(t,s),typeof t.requestLightProbe=="function"&&t.requestLightProbe().then(n=>{s&&n&&(s.lightProbe=n)}).catch(()=>{})),s.lightProbe&&typeof r.getLightEstimate=="function"){let n=r.getLightEstimate(s.lightProbe);if(n){let l=n.primaryLightDirection,a=n.primaryLightIntensity;if(l&&a&&Array.isArray(e.lights)){let o=e.lights.find(h=>h.type==="directional");o||(o={type:"directional",direction:[.5,1,.8],color:[1,1,1],intensity:1},e.lights.push(o)),o.direction=[l.x,l.y,l.z];let u=Math.max(a.x,a.y,a.z,.001);o.color=[a.x/u,a.y/u,a.z/u],o.intensity=u}n.sphericalHarmonicsCoefficients&&e.gl&&un(e.gl,n.sphericalHarmonicsCoefficients)}}}};He(ci),He(pn),He(cn),He(vn),He(Cn),He(xn),He(Sn),He(Rn),He(Tn),He(Ui),ir.registerScriptRunner(gr),typeof window<"u"&&(window.ThreeLiveBundle=zn);export{Wr as AmbientLight,zr as BoxGeometry,$e as BufferAttribute,Ve as BufferGeometry,qr as Camera,Fs as CapsuleGeometry,hs as CatmullRomCurve3,Vs as CircleGeometry,As as Clock,ot as Color,ss as ConeGeometry,us as CubicBezierCurve3,Ct as Curve3,$r as CylinderGeometry,ms as DataTexture,vs as DirectionalLight,ks as DodecahedronGeometry,Bs as EdgesGeometry,Or as Euler,Ji as Float32BufferAttribute,xs as Group,oi as HemisphereLight,Zn as IKSolver,Is as IcosahedronGeometry,jr as InstancedMesh,yn as InteractivityVM,ra as LOD,Gr as LatheGeometry,er as Light,Ft as Line,yr as LineBasicMaterial,os as LineCurve3,Os as LineDashedMaterial,zs as LineLoop,$s as LineSegments,Oi as LodController,Wn as MAX_BSP_DEPTH,jn as MAX_CSG_TRIANGLES,Jt as MAX_INSTANCES_PER_MESH,qn as MAX_SHAPE_POINTS,Xn as MAX_TEXT_GEOMETRY_CHARS,et as Material,Qi as MathUtils,Zi as Matrix3,It as Matrix4,pt as Mesh,ds as MeshBasicMaterial,gs as MeshLambertMaterial,ys as MeshPhongMaterial,bs as MeshPhysicalMaterial,Qt as MeshStandardMaterial,lt as Object3D,Ds as OctahedronGeometry,Ms as PerspectiveCamera,rs as PlaneGeometry,Xr as PointLight,Gs as Points,ai as PointsMaterial,za as PolyhedronFallbackGeometry,Nt as PolyhedronGeometry,ls as QuadraticBezierCurve3,Ur as Quaternion,Ns as RawShaderMaterial,js as RectAreaLight,ni as RingGeometry,Kr as Scene,dt as SceneQuotaValidator,ii as ShaderMaterial,is as SphereGeometry,Hs as SpotLight,Vt as THREE,_s as TetrahedronGeometry,pr as Texture,fs as TextureLoader,ir as ThreeLiveElement,Ze as ThreeView,ns as TorusGeometry,as as TorusKnotGeometry,cs as TubeGeometry,es as Uint16BufferAttribute,ts as Uint32BufferAttribute,it as Vector2,be as Vector3,Yi as Vector4,Ss as WebGLRenderer,Us as WireframeGeometry,on as activateAR,Mn as applyMeshoptFilter,gr as authorScriptRunner,ei as buildSandboxWorkerSource,Pi as cadPlugin,Ls as clearAuthorWarnings,Po as computeOutlineClipOffset,ci as contactShadowPlugin,Vr as createUSDZBlob,Ks as crossFadeTo,ta as decimateGeometry,wn as decodeMeshoptBuffer,Mi as decodeMeshoptGLB,So as encodeMeshoptBuffer,cn as environmentMapPlugin,To as evaluateKawaseBloom,la as evaluateToneMapping,Yr as exportSceneToCanvas3D,Zr as exportSceneToGLB,ws as exportSceneToUSDZ,Pn as extractMaterialVariants,Eo as extractPrimitiveVariantMappings,Fr as generateUSDZ,mi as getARCapabilities,Cs as getAllowClientScripts,Es as getAuthorWarnings,Ya as getBestARMode,Ja as getEnvironmentSH,bi as getInteractivityVM,ia as getLodController,Jr as getSandboxEngineSrc,Rs as getSandboxIframeSrc,kr as glbToUSDZ,pn as hotspotPlugin,Vi as ikPlugin,Tr as installCadExtension,lr as installLodExtension,xn as interactivityPlugin,kt as isAllowedSandboxEngineUrl,sn as isQuickLookSupported,nn as isSceneViewerSupported,an as isWebXRSupported,Qs as keyframeAnimationPlugin,Ui as lodPlugin,vn as materialsPlugin,wi as meshoptDecoder,Sn as meshoptPlugin,Js as morphPlugin,tr as noopProxy,qs as parseAnimations,An as parseHexRgb,Nr as parseLod,Mr as parseSafeGltfPointer,Tn as postprocessingPlugin,Cr as quatFromUnitVectors,uo as registerMaterialShader,sr as sampleChannel,Zt as sceneToCanvas3D,mr as sceneToGLB,fr as sceneToUSDZ,Lr as selectLodLevelIndex,Lo as selectMaterialVariant,bn as sendInteractivityEvent,Da as setAllowClientScripts,un as setEnvironmentSH,qa as setMorphTargetWeight,Na as setSandboxEngineSrc,_a as setSandboxIframeSrc,tn as skinningPlugin,Ni as solveFABRIK,Li as solveTwoBoneIK,rr as threeAuthorPlugin,ja as threeMicroPlugin,Dt as toGLBData,Ts as toTrustedWorkerScriptURL,ti as validateSandboxWorkerMessage,Rn as variantsPlugin,Lt as warnUnsupported,Cn as webxrPlugin};
|
|
549
|
+
}`,zs=3,Zn=new WeakMap;function nc(e,t=[.22,.74,.97]){let r=Ih(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 Am(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 Tm(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 Pm=new WeakSet;function Nm(e){let t=Zn.get(e);if(t){if(typeof e.isProgram!="function"||e.isProgram(t.outlineProg))return t;Zn.delete(e)}if(Pm.has(e)||e.isContextLost?.())return null;let r=_i(e,O1,j1,!1),i=_i(e,Sm,G1,!1),n=_i(e,Sm,H1,!1);if(!r||!i||!n){for(let s of[r,i,n])s&&e.deleteProgram(s);return Pm.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},Zn.set(e,t),t}function q1(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===zs&&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<zs;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 W1(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=$h({strength:a,threshold:es(t.getAttribute("bloom-threshold"),.62),radius:es(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=$h(n);a&&(!r||a.strength>r.strength)&&(r=a)}return r}function K1(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 Fo({color:n,thickness:a,pulse:s})}var X1=new Set(["floor","pedestal","ground","table","grid","pad"]);function Y1(e){return e.replace(/([a-z\d])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z]+/).some(t=>X1.has(t))}function Q1(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=Fo(n);if(a)return a;let s=typeof r?.getAttribute=="function"&&r.getAttribute("outline-color")||"#38bdf8",o=K1(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?Fo({color:s,thickness:3,pulse:!1}):null);if(o){let f=t.name||"";return Y1(f)?null:o}return null}var ac={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=Q1(t,h);p&&a.push({mesh:h,trait:p})}let s=a.length>0?Nm(e):null;if(s){let h=s,p=lt(),g=lt(),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]=nc(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):ft(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 I=P.length>>4,F=lt();for(let V=0;V<I;V++)ft(F,p,P.subarray(V*16,V*16+16)),ft(g,r,F),rr(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 ft(g,r,p),rr(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=W1(t);if(!o||o.strength<=0)return;let l=Nm(e);if(!l||!q1(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<zs;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=zs-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=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)}}},Jn=4,sc=9,Z1=32*1024*1024,Vs=lt(),Cm=new Int32Array([-1,-1]);function oc(e,t,r,i){let n=Number(e);return Number.isFinite(n)?Math.max(t,Math.min(r,n)):i}var Em=new WeakMap,ri=new WeakMap,ea=new WeakMap,nn=lt(),Us=lt(),ii=lt(),an=lt(),Lm=new Float32Array(1),J1=new Uint32Array(Lm.buffer);function lc(e){if(typeof e!="string")return"auto";let t=e.trim().toLowerCase();return t==="pcf"||t==="off"?t:"auto"}function eg(e){let t=Em.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 Em.set(e,l),l}function sn(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 uc(e){let t=e||{},r=t.modelRootMatrix??Vs,i=[1/0,1/0,1/0],n=[-1/0,-1/0,-1/0];for(let m of t.meshes??[]){if(!hc(m))continue;m.worldSpace===!0?ii.set(m.transform):ft(ii,r,m.transform);let h=m.instanceMatrices;for(let p of m.primitives??[]){if(!p.positions||p.positions.length<3)continue;let g=eg(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)ft(an,ii,h.subarray(y*16,y*16+16)),sn(g,an,i,n);if(v>1){let y=x-1;ft(an,ii,h.subarray(y*16,y*16+16)),sn(g,an,i,n)}}else sn(g,ii,i,n)}}if(!Number.isFinite(i[0])){let m=t.bounds;m&&Array.isArray(m.min)&&Array.isArray(m.max)&&sn([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 cc(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];_n(nn,h,r.center,p);let g=[1/0,1/0,1/0],x=[-1/0,-1/0,-1/0];sn([...r.min,...r.max],nn,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 q0(Us,g[0]-v,Math.max(g[0]+.05,x[0])+v,g[1]-v,Math.max(g[1]+.05,x[1])+v,y,A),ft(e,Us,nn)}function Os(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];_n(nn,[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];sn([...a.min,...a.max],nn,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 uo(Us,C,1,N,Math.max(N+.1,S)),ft(e,Us,nn)}function Rm(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??Vs,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 hc(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 on(e,t){if(!hc(e))return!1;let r=e.castShadow??e.extras?.shadow?.cast;return r===!1?!1:t?!0:r===!0}function js(e,t){if(!e||typeof e!="object")return!1;let r=e;if(!hc(r))return!1;let i=r.receiveShadow??r.extras?.shadow?.receive;return i!==void 0?!!i:t}function fc(e){return!(e.isTransmissive||e.alphaMode==="BLEND"||(e.baseColor?.[3]??1)<.98)}function ni(e,t){return Math.imul((e^t>>>0)>>>0,16777619)>>>0}function ai(e,t){return Lm[0]=t||0,ni(e,J1[0])}function ta(e,t,r=64){let i=t.length;if(e=ni(e,i),i<=r)for(let n=0;n<i;n++)e=ai(e,t[n]);else{let n=Math.max(1,Math.floor(i/r));for(let a=0;a<i;a+=n)e=ai(e,t[a]);e=ai(e,t[i-1])}return e}function Gs(e){let t=e||{},r=t.shadowMaps??t.container?.getAttribute?.("shadow-maps")??"auto",i=lc(r),n=[-1,-1],a=[-1,-1],s=(I=!1)=>({mode:i,mapSize:0,slices:[],dirSlots:n,ptSlots:a,promoteAllCasters:I,promoteAllReceivers:I,digest:0,sectionPlane:null});if(i==="off")return s();let o=[],l=null,c=null,f=!1,m=0,h=0;for(let I of t.lights??[])I.type==="hemisphere"?f=!0:I.type==="directional"&&m<2?(l||(l=I),I.shadow?.cast&&o.length<Jn&&o.push({kind:"directional",subIdx:m,light:I}),m++):(I.type==="spot"||I.type==="point")&&h<2&&(c||(c={kind:I.type,light:I}),I.shadow?.cast&&o.length<Jn&&o.push({kind:I.type,subIdx:h,light:I}),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 I of p)if(I.castShadow!==void 0||I.receiveShadow!==void 0||I.extras?.shadow!==void 0){g=!0;break}let x=i==="pcf"||!g,v=x,y=!1;for(let I of p)if(on(I,x)){for(let F of I.primitives??[])if(fc(F)&&F.indexCount>0){y=!0;break}if(y)break}if(!y)return s(x);let A=1024;for(let I of o){let F=I.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>Z1;)b=Math.max(256,b>>1);let S=uc(t),E=S.radius*2.2/b,N=[];for(let I=0;I<o.length;I++){let F=o[I],V=F.light,Y=V.shadow,J=lt(),re;if(F.kind==="directional"){n[F.subIdx]=I;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],cc(J,G,S)}else{a[F.subIdx]=I;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));Os(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],Os(J,G,re,Math.PI/3,V.range,S)}}let Q=oc(Y?.bias,-.05,.05,-5e-4),ee=oc(Y?.normalBias,0,.5,.015),k=oc(Y?.radius,0,16,1.5);N.push({slot:I,viewProj:J,rayDir:re,depthBias:Q,normalBiasWorld:ee/.015*1.75*E,uvRadius:k*1.35/b})}let C=Rm(t),_=2166136261;_=ni(_,i==="pcf"?2:1),_=ni(_,b),_=ni(_,N.length);for(let I of N)_=ta(_,I.viewProj,16),_=ai(_,I.depthBias),_=ai(_,I.normalBiasWorld);C?.enabled?(_=ni(_,1),_=ai(_,C.normal[0]),_=ai(_,C.normal[1]),_=ai(_,C.normal[2]),_=ai(_,C.constant)):_=ni(_,0);let P=t.modelRootMatrix??Vs;_=ta(_,P,16);let R=0;for(let I of p){if(!on(I,x)){R++;continue}_=ni(_,R++),_=ta(_,I.transform,16),I.instanceMatrices&&(_=ta(_,I.instanceMatrices,64));for(let F of I.primitives??[])fc(F)&&(_=ni(_,F.indexCount),F.translations&&(_=ta(_,F.translations,48)))}return _===0&&(_=1),{mode:i,mapSize:b,slices:N,dirSlots:n,ptSlots:a,promoteAllCasters:x,promoteAllReceivers:v,digest:_,sectionPlane:C}}function Im(e){let t=ri.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 tg=`#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
|
+
}`,rg=`#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
|
+
}`,ig=`
|
|
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
|
+
}`,ng=["uShadowMap","uShadowVP","uShadowParams","uDirShdSlot","uPtShdSlot","uReceiveShadow"];function ag(e){let t=ri.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},ri.set(e,t)),t}function $m(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 Dm(e){let t=ea.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,tg),e.compileShader(i),e.shaderSource(n,rg),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:$m(e,1,1)},ea.set(e,t),t}var km={uniformsGLSL:ig,dirGLSL:"*shdEval(uDirShdSlot[i],vWorldPos,N,normalize(uDirLightDir[i]))",ptGLSL:"*shdEval(uPtShdSlot[i],vWorldPos,N,L)",uniformNames:ng,bind(e,t,r,i){let n=t.uShadowMap;if(n===void 0)return;let a=r&&typeof r=="object"?ri.get(r):void 0,s=Dm(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,sc);let c=t.uDirShdSlot,f=t.uPtShdSlot,m=t.uReceiveShadow;if(!o){c&&e.uniform1iv?.(c,Cm),f&&e.uniform1iv?.(f,Cm),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,js(i,a.promoteAllReceivers)?1:0)}};function Fm(e,t){t.indices?e.drawElements(4,t.indexCount,t.indexType,0):e.drawArrays(4,0,t.indexCount)}var mc={name:"shadow-maps",onRegister(){We().shadowMapShader=km},onLoadModel(e){if(e&&typeof e=="object"){let t=ri.get(e);t&&(t.lastDigest=0)}},onClearScene(e){if(e&&typeof e=="object"){let t=ri.get(e);t&&(t.lastDigest=0,t.activeLights=0)}},onContextRestored(e,t){if(ea.delete(e),t&&typeof t=="object"){let r=ri.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=ri.get(t);r&&(r.texArray&&e.deleteTexture?.(r.texArray),r.fbo&&e.deleteFramebuffer?.(r.fbo),ri.delete(t))}else if(e){let r=ea.get(e);r&&(r.prog&&e.deleteProgram?.(r.prog),r.dummyArrayTex&&e.deleteTexture?.(r.dummyArrayTex),ea.delete(e))}},onBeforeDrawScene(e,t){if(!e||typeof e!="object")return;let r=e,i=We();if(i.shadowMapShader||(i.shadowMapShader=km),r.uRender&&!("uShadowMap"in r.uRender)&&r.recompileRenderProgram?.(),i.gpuSceneAccelerator?.willRenderScene?.(e))return;let n=ag(e),a=Gs(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=Dm(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=$m(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??Vs,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(!on(g,a.promoteAllCasters))continue;g.worldSpace===!0?ii.set(g.transform):ft(ii,m,g.transform);let x=g.instanceMatrices;for(let v of g.primitives??[])if(!(!v.vao||v.indexCount<=0||!fc(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,ii),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++)ft(an,ii,x.subarray(A*16,A*16+16)),s.uModel&&t.uniformMatrix4fv(s.uModel,!1,an),Fm(t,v)}else Fm(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 pc(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 Bm(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 zm(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=pc(a).indexOf(o);if(l<0)return i;for(let c of s)if(c.variants.includes(l))return c.material;return i}var dc={name:"variants",onLoadModel(e,t){let r=e.getVariantName?.();r&&e.selectVariant(r)}},Vm=new WeakMap,gc={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=Vm.get(t);if(n||(n={lightProbe:null},Vm.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&&ju(e.gl,a.sphericalHarmonicsCoefficients)}}}};Rt(Ps),Rt(mc),Rt(Ku),Rt(Hu),Rt(ec),Rt(gc),Rt(Ju),Rt(ic),Rt(dc),Rt(ac),Rt(Mo);var Um=272,sg=["x","y","z","w"],Om=[[2,"vec2<f32>"],[3,"vec3<f32>"],[4,"vec4<f32>"]];function ln(e,t){return Om.map(([r,i])=>{let n=sg.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 jm(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);}",...ln("_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);}",...ln("_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);}",...ln("_tslPow",2)),e.clamp&&r.push("fn _tslClamp1(a:f32,b:f32,c:f32)->f32{return clamp(a,min(b,c),max(b,c));}",...ln("_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);}",...ln("_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);}",...ln("_tslAtan",2)),e.norm&&r.push("fn _tslNorm1(v:f32)->f32{return select(0.0,sign(v),abs(v)>1e-6);}",...Om.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 og={positionLocal:"_tslPL",positionWorld:"_tslPW",normalLocal:"_tslNL",normalWorld:"_tslNW",viewDirection:"_tslVD",uv:"_tslUV",vertexColor:"_tslVC",instanceIndex:"_tslII"};function yc(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=nr(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(Xr);v=l==="float"?y[0]:`${l}<f32>(${y.join(",")})`;break}case"builtin":v=o.builtin==="time"?`_tslMod1(tslU.timeAndPad.x,${Xr(3600)})`:og[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 bc(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=jm(Na(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
|
+
${yc(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
|
+
${yc(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=jm(Na(e.nodes,e.vertexReachable,e.usesTime),!1),f=yc(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 ra=new WeakMap,un=new WeakMap,Gm=new WeakMap,ia=new Map,lg=128;function ug(e,t){let r=Gm.get(t);return r||(r={paramsLoc:e.getUniformLocation(t,"uTslParams[0]")??e.getUniformLocation(t,"uTslParams"),timeLoc:e.getUniformLocation(t,"uTslTime")},Gm.set(t,r)),r}function cg(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 na(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?.[Ui];if(!f)continue;let m=typeof c.name=="string"&&c.name.length>0?c.name:`Material_${l}`,h=Oi(f,m);if(!h.ok){console.warn(`[three-live] [${h.issue.code}] ${h.issue.message} Falling back to base PBR material.`);continue}let p=cg(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};ra.set(e,s);let o=e.gl;return o&&typeof o=="object"&&un.set(o,s),s}function Hm(e,t){let r=ra.get(e);if(!r){let i=t??e.gltf;if(!i)return null;r=na(e,i)}return r}function hg(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 xc(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=Hm(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=hg(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=Pa(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 Hs(e){if(!e||typeof e!="object")return;let t=e;typeof t.setMaterialUniform!="function"&&(t.setMaterialUniform=(r,i,n)=>xc(e,r,i,n))}function fg(){let e=We();Mn(Ta);let t=e.threeNamespace??(typeof globalThis<"u"?globalThis.THREE:void 0);t?Ta(t,e):e.authorNamespace||(e.authorNamespace={}),e.tslWgslCompiler=(r,i,n)=>!r||typeof r!="object"?null:bc(r,i,n),e.tslMaterialResolver=(r,i)=>i===void 0||i<0?null:Hm(r)?.materialsByIndex.get(i)??null,e.tslUsdzSerializer=Do}var vc={name:"tsl",onRegister(){fg()},onElementConnected(e){Hs(e),e?.viewer&&(Hs(e.viewer),e.viewer.gltf&&(na(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?.[Ui];if(!a)return null;let s=Oi(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?.[Ui];if(!n)return null;let a=Oi(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=ia.get(s);if(!o){if(ia.size>=lg){let l=ia.keys().next().value;l!==void 0&&ia.delete(l)}o=$o(a.graph,r,i),ia.set(s,o)}return o},onLoadModel(e,t){Hs(e),e?.container&&Hs(e.container),na(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=ra.get(e);if(!r||!r.hasAnimatedTsl)return;let i=Number.isFinite(t)&&t>0?Math.min(t,.25):0;r.elapsedSec=Lo(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?.[Ui])return;let o=ug(e,t);if(!o.paramsLoc&&!o.timeLoc)return;let l=un.get(e);l||(l=na(e,a),un.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){ra.delete(e),e?.gl&&typeof e.gl=="object"&&un.delete(e.gl)},onContextRestored(e,t){if(t?.gltf){let r=na(t,t.gltf);e&&typeof e=="object"&&un.set(e,r)}},onDestroy(e,t){ra.delete(t),e&&typeof e=="object"&&un.delete(e)}};Rt(vc);var qm=800,Wm=32,Km=128,Xm=8,Ym=32;function aa(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 qs(e,t){let r=new Float32Array(e,0,200),i=new Uint32Array(e,0,200),n=new Int32Array(e,0,200);r.fill(0),aa(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;aa(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 mg(e,t,r,i,n,a){let s=new Float32Array(e,0,44),o=new Uint32Array(e,0,44);s.fill(0),aa(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 wc=`
|
|
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
|
+
`,Ws=wc+`
|
|
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
|
+
`,Mc=wc+`
|
|
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
|
+
`,_c=wc+`
|
|
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
|
+
`,Qm=`
|
|
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
|
+
`,Zm=1,si=8,pg=16,dg=32,Ks=64,gg=128,yg=1,Jm=2,Xs=4,gi=16,bg=1,sa=1,jr=2,Sc=4,yi=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),jt=null,Wt=null,Gr=!1,Kt="bgra8unorm",Ys=null,Qs=new WeakMap;function xt(e){try{e()}catch{}}function e0(e){return Math.max(16,e+3&-4)}function Zs(){let e=globalThis.navigator?.gpu;return e&&typeof e.requestAdapter=="function"?e:null}function t0(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 Ri(){if(jt)return Promise.resolve(jt);let e=We(),t=e.webgpuDeviceProvider?.peekDevice?.();return t0(t)?(jt=t,Kt=e.webgpuDeviceProvider?.getCanvasFormat?.()||Kt,Promise.resolve(t)):Gr?Promise.resolve(null):Wt||(e.webgpuDeviceProvider&&e.webgpuDeviceProvider!==r0?(Wt=e.webgpuDeviceProvider.acquireDevice().then(r=>(Wt=null,t0(r)?(jt=r,Kt=e.webgpuDeviceProvider?.getCanvasFormat?.()||Kt,r):Ac())).catch(()=>(Wt=null,Ac())),Wt):Ac())}function Ac(){let e=Zs();if(!e)return Gr=!0,Promise.resolve(null);try{Kt=e.getPreferredCanvasFormat?.()||"bgra8unorm"}catch{Kt="bgra8unorm"}return Wt=e.requestAdapter({powerPreference:"high-performance"}).then(async t=>{if(!t)return Gr=!0,Wt=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 jt=n,Wt=null,n.lost?.then?.(()=>{jt===n&&(jt=null,Wt=null,Gr=!1,Ys?.onDeviceLost(n))}),n}).catch(()=>(Gr=!0,Wt=null,null)),Wt}var r0={acquireDevice:()=>Ri(),peekDevice:()=>jt,getCanvasFormat:()=>Kt};function i0(e,t="bgra8unorm"){jt=e,Wt=null,Gr=e===null,Kt=t}function n0(){jt=null,Wt=null,Gr=!1,Kt="bgra8unorm"}function Tc(e){let t=String(e??"").trim().toLowerCase();return t==="webgpu"||t==="webgl2"?t:"auto"}function xg(e){let t=e.container?.getAttribute?.("renderer")??e.renderer??"auto";return Tc(t)}function vg(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&&!(We().tslWgslCompiler&&We().tslMaterialResolver?.(e,c.materialIndex))||c.pluginData?.morph||c.pluginData?.skinning||c.instanceCount!==void 0)return!0}return!1}function Js(e,t=!!(jt||Zs())){let r=e;if(!r||r.xrSessionActive)return"webgl2";let i=xg(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"&&vg(r)?"webgl2":"webgpu"}function a0(e){let t=Qs.get(e);if(t)return t;let r=e.createBindGroupLayout({entries:[{binding:0,visibility:sa|jr,buffer:{type:"uniform"}},{binding:1,visibility:sa|jr,buffer:{type:"read-only-storage"}},{binding:2,visibility:jr,sampler:{type:"filtering"}},{binding:3,visibility:jr,texture:{sampleType:"float"}},{binding:4,visibility:jr,sampler:{type:"comparison"}},{binding:5,visibility:jr,texture:{sampleType:"depth",viewDimension:"2d-array"}}]}),i=e.createBindGroupLayout({entries:[0,1,2,3,4].map(C=>({binding:C,visibility:jr,texture:{sampleType:"float"}}))}),n=e.createBindGroupLayout({entries:[{binding:0,visibility:sa|jr,buffer:{type:"uniform"}}]}),a=e.createBindGroupLayout({entries:[{binding:0,visibility:sa|jr,buffer:{type:"uniform"}},{binding:1,visibility:sa|jr,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:Ws}),h=e.createShaderModule({code:Mc}),p=e.createShaderModule({code:Qm}),g=e.createShaderModule({code:_c}),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:Xs|Jm|gi});xt(()=>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:Xs|gi}),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])},Qs.set(e,t),t}function wg(e,t,r,i){let n=t.tslShaders.get(r);if(n)return n;let a=We().tslWgslCompiler;if(!a)return null;let s=a(i,Ws,Qm);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 Mg=[{arrayStride:32,attributes:[{shaderLocation:0,offset:0,format:"float32x3"},{shaderLocation:1,offset:12,format:"float32x3"},{shaderLocation:2,offset:24,format:"float32x2"}]}];function s0(e,t,r,i,n){let a=s=>e.createRenderPipeline({layout:t,vertex:{module:r,entryPoint:"vsMain",buffers:Mg},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 _g(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=s0(e,t.tslScenePipeLayout,s.pbrMod,i,n),t.tslPipelinesByFormat.set(o,l)),a?l.blend:l.opaque}function o0(e,t,r,i){let n=`${r}:${i}`,a=t.byFormat.get(n);if(a)return a;let{opaque:s,blend:o}=s0(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 l0(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 bi(e){return!e||typeof e!="object"?null:e.__gpuImageSource||(l0(e)?e:null)}function Ii(e,t,r){if(!r)return{view:t.whiteView,src:null,valid:!1};let i=bi(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=l0(i);if(!a)return{view:t.whiteView,src:null,valid:!1};n&&(t.ownedTextures.delete(n.tex),xt(()=>n.tex.destroy()));let[s,o]=a,l=e.createTexture({size:{width:s,height:o,depthOrArrayLayers:1},format:"rgba8unorm",usage:Xs|Jm|gi}),c=!1;if(typeof e.queue.copyExternalImageToTexture=="function"&&xt(()=>{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);xt(()=>{e.queue.writeTexture({texture:l},p,{bytesPerRow:h,rowsPerImage:o},{width:s,height:o,depthOrArrayLayers:1}),c=!0})}if(!c)return xt(()=>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 u0(e,t,r){let i=Ii(e,t,r.texture),n=Ii(e,t,r.metallicRoughnessTexture),a=Ii(e,t,r.normalTexture),s=Ii(e,t,r.occlusionTexture),o=Ii(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 Sg(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 c0(e){return Rm(e)}function Ag(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??yi,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 h0(e){return e.environmentTexture&&typeof e.environmentTexture=="object"?e.environmentTexture:e.environmentSource&&typeof e.environmentSource=="object"?e.environmentSource:null}function cn(e){if(e){xt(()=>e.vertexBuf.destroy()),xt(()=>e.indexBuf?.destroy()),xt(()=>e.partBuf.destroy()),xt(()=>e.uniformBuf.destroy()),xt(()=>e.pickUniformBuf?.destroy());for(let t of e.shadowSliceBufs)xt(()=>t?.destroy());for(let t of e.tslSlots.values())xt(()=>t.buf.destroy())}}function f0(e,t,r,i,n){let a=We().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=wg(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){xt(()=>l?.buf.destroy());let c=e.createBuffer({size:s.buf68.byteLength,usage:Ks|si});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 Pc(e){xt(()=>e.shadowTex?.destroy()),e.shadowTex=null,e.shadowArrayView=null,e.shadowLayerViews=[],e.shadowSize=0,e.shadowLayers=0,e.lastShadowDigest=0}function eo(e){xt(()=>e.msaaTex?.destroy()),xt(()=>e.depthTex?.destroy()),e.msaaTex=null,e.msaaView=null,e.depthTex=null,e.depthView=null,e.width=0,e.height=0}function to(e){xt(()=>e.pickColorTex?.destroy()),xt(()=>e.pickDepthTex?.destroy()),xt(()=>e.pickReadBuf?.destroy()),e.pickColorTex=null,e.pickColorView=null,e.pickDepthTex=null,e.pickDepthView=null,e.pickReadBuf=null,e.pickBusy=!1}function m0(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 p0(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,I=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=I&&I.length>=16?I.length>>4:F.instanceCount!==void 0&&F.translations?Math.max(1,F.instanceCount|0):1,k=u0(e,t,F),G=f0(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,I=N.firstVertex*8;for(let F=0;F<R;F++){let V=F*3,Y=F*2;h[I]=C[V],h[I+1]=C[V+1],h[I+2]=C[V+2],_&&V+2<_.length&&(h[I+3]=_[V],h[I+4]=_[V+1],h[I+5]=_[V+2]),P&&Y+1<P.length&&(h[I+6]=P[Y],h[I+7]=P[Y+1]),I+=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:e0(h.byteLength),usage:dg|si});e.queue.writeBuffer(g,0,h);let x=null;p&&(x=e.createBuffer({size:e0(p.byteLength),usage:pg|si}),e.queue.writeBuffer(x,0,p));let v=Math.max(128,c*128),y=e.createBuffer({size:v,usage:gg|si}),A=e.createBuffer({size:800,usage:Ks|si}),b=h0(r),w=Ii(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:bi(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 Tg(e,t,r,i,n){let a=o0(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?_g(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 Pg(e,t,r){if(r.pickUniformBuf||(r.pickUniformBuf=e.createBuffer({size:800,usage:Ks|si})),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 Ng(e,t,r,i){if(i<0||i>=Jn)return null;if(r.shadowSliceBufs[i]||(r.shadowSliceBufs[i]=e.createBuffer({size:176,usage:Ks|si})),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 Nc=lt(),$i=lt();function d0(e,t,r,i,n,a,s){let o=h0(r),l=bi(o),c=i.envView;if(l!==i.envSourceRef){let b=Ii(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??yi,v=n.eye==="none"&&!r.stereoSBS;i.tslVertexDirty=!1;let y=We().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=f0(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||bi(E)!==b.src0||bi(N)!==b.src1||bi(C)!==b.src2||bi(_)!==b.src3||bi(P)!==b.src4){let D=u0(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],I=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&&on(w,a.promoteAllCasters)&&(re|=1024),a&&a.slices.length>0&&!b.isBackdrop&&js(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__"?Nc.set(w.transform):ft(Nc,x,w.transform);let D=Nc,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,ke=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)ft($i,G,ne.subarray(D*16,D*16+16)),O=$i;else if(W&&W.length>=(D+1)*3){$i.set(G);let X=W[D*3],se=W[D*3+1],ce=W[D*3+2];$i[12]+=G[0]*X+G[4]*se+G[8]*ce,$i[13]+=G[1]*X+G[5]*se+G[9]*ce,$i[14]+=G[2]*X+G[6]*se+G[10]*ce,O=$i}for(let X=0;X<16;X++)m[z+X]=O[X];Re&&Re.length>=(D+1)*3?(m[z+16]=I*Re[D*3],m[z+17]=F*Re[D*3+1],m[z+18]=V*Re[D*3+2]):(m[z+16]=I,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]=ke,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 Cg(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 Cc=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:Sc,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 xt(()=>l.remove?.()),null;t.canvas=l,t.ctx=c,t.visible=!0,t.unhookSnapshot=Sg(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!==Kt||s)&&(t.ctx.configure({device:r,format:Kt,alphaMode:"premultiplied"}),t.dev=r,t.configuredFormat=Kt),t.width!==n||t.height!==a||!t.depthTex){eo(t),t.width=n,t.height=a;let o=Sc,l=null;xt(()=>{l=r.createTexture({size:{width:n,height:a,depthOrArrayLayers:1},format:Kt,sampleCount:Sc,usage:gi})}),l||(o=1);let c=r.createTexture({size:{width:n,height:a,depthOrArrayLayers:1},format:"depth24plus",sampleCount:o,usage:gi});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(!jt){if(!Gr&&!Wt){let G=h.gen;Ri().then(q=>{q&&h.gen===G&&this.trackedViewers.has(f.viewer)&&xt(()=>f.viewer.render?.())})}return this.hideLayer(f.viewer),!1}let p=jt;if(Js(m,!0)!=="webgpu")return this.hideLayer(f.viewer),!1;h.dev&&h.dev!==p&&(cn(h.scene),h.scene=null,eo(h),Pc(h),to(h));let g=this.ensureCanvas(m,h,p);if(!g)return!1;let x=a0(p),v=!f.isAR,y=v?m.backdropMeshes??[]:[],A=m.meshes??[];if((!h.scene||!m0(h.scene,y,A))&&(cn(h.scene),h.scene=p0(p,x,m,v),h.lastShadowDigest=0,!h.scene))return this.hideLayer(f.viewer),!1;let b=h.scene,w=Gs(m),S=x.dummyShadowView,E=w.slices.length;if(E>0){if(!h.shadowTex||h.shadowSize!==w.mapSize||h.shadowLayers<E){xt(()=>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:gi|Xs});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}d0(p,x,m,b,f,w,S),(b.bundlesDirty||b.bundleFormat!==Kt||b.bundleSamples!==h.sampleCount)&&(Tg(p,x,b,Kt,h.sampleCount),this.bundleRecordCount++);let N=w.sectionPlane??c0(m),C=Ag(m,f.isAR);qs(h.uniformScratch,{vp:f.vp,modelRoot:m.modelRootMatrix??yi,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,I={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??yi;for(let q of w.slices){let H=Ng(p,x,b,q.slot),te=b.shadowSliceBufs[q.slot],Z=h.shadowLayerViews[q.slot];if(!te||!Z)continue;mg(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:I}:{view:_,loadOp:f.clear?"clear":"load",storeOp:"store",clearValue:I}],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=o0(p,x,Kt,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=jt??await Ri();if(!s||typeof s.createCommandEncoder!="function")return-1;let o=this.getState(e),l=o.gen,c=a0(s),f=n.backdropMeshes??[];if((!o.scene||!m0(o.scene,f,a))&&(cn(o.scene),o.scene=p0(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=lt();i?y.set(i):n.projMatrix&&n.viewMatrix?ft(y,n.projMatrix,n.viewMatrix):y.set(yi),d0(s,c,n,m,{viewer:e,vp:y,proj:n.projMatrix??yi,view:n.viewMatrix??yi,eyePos:[0,0,3],toneMappingIndex:0,viewport:[0,0,h,p],eye:"none",clear:!0,isAR:!1}),(!o.pickColorTex||!o.pickDepthTex)&&(to(o),o.pickColorTex=s.createTexture({size:{width:1,height:1,depthOrArrayLayers:1},format:"rgba8unorm",usage:gi|yg}),o.pickColorView=o.pickColorTex.createView(),o.pickDepthTex=s.createTexture({size:{width:1,height:1,depthOrArrayLayers:1},format:"depth24plus",usage:gi}),o.pickDepthView=o.pickDepthTex.createView(),o.pickReadBuf=s.createBuffer({size:256,usage:si|Zm}));let A=Cg(lt(),y,x,v,h,p),b=Pg(s,c,m),w=new ArrayBuffer(800);qs(w,{vp:A,modelRoot:n.modelRootMatrix??yi,eyePos:[0,0,0],exposure:1,envIntensity:1,toneMappingIndex:2,lights:[],hasEnvMap:!1,sectionPlane:c0(n)}),s.queue.writeBuffer(m.pickUniformBuf,0,w);let S=!!(o.pickReadBuf&&!o.pickBusy),E=S?o.pickReadBuf:s.createBuffer({size:256,usage:si|Zm});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(bg,0,4),o.gen!==l)return xt(()=>E.unmap()),-1;let _=new Uint8Array(E.getMappedRange(0,4)),P=_[0],R=_[1],I=_[2];E.unmap();let F=P+(R<<8)+(I<<16);return F>0&&F<=a.length?F-1:-1}finally{S?o.pickBusy=!1:xt(()=>E.destroy())}}willRenderScene(e){if(!jt)return!1;let t=e;if(t.xrSessionActive||Js(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++,cn(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,cn(t.scene),t.scene=null,eo(t),Pc(t),to(t),xt(()=>t.ctx?.unconfigure?.()),xt(()=>t.canvas?.remove?.()),t.ctx=null,t.canvas=null,t.dev=null,t.visible=!1)}onDeviceLost(e){let t=Qs.get(e);if(t){for(let r of t.ownedTextures)xt(()=>r.destroy());t.ownedTextures.clear(),Qs.delete(e)}for(let r of this.trackedViewers){let i=this.states.get(r);i&&i.dev===e&&(i.gen++,cn(i.scene),i.scene=null,eo(i),Pc(i),to(i),i.dev=null,i.configuredFormat="")}}};function hn(){return Ys||(Ys=new Cc),Ys}var Ec={name:"three-live-webgpu-scene",onRegister(){let e=We();e.gpuSceneAccelerator=hn(),e.webgpuDeviceProvider||(e.webgpuDeviceProvider=r0),!jt&&!Gr&&!Wt&&Zs()&&Ri()},onElementConnected(e){let t=e;!jt&&!Gr&&!Wt&&Zs()&&Ri().then(r=>{r&&t?.viewer&&xt(()=>t.viewer.render?.())})},onAttributeChanged(e,t){(t==="renderer"||t==="section-plane"||t==="shadow-maps")&&e?.viewer?.render?.()},onLoadModel(e){e&&typeof e=="object"&&hn().clearViewerScene(e)},onClearScene(e){e&&typeof e=="object"&&hn().clearViewerScene(e)},onXRSessionEnd(e){e&&typeof e=="object"&&xt(()=>e.render?.())},onDestroy(e,t){t&&typeof t=="object"&&hn().disposeViewer(t)}};Rt(Ec),di.registerScriptRunner(Bn),typeof window<"u"&&(window.ThreeLiveBundle=Gc);export{vu as AIVoiceSession,Fa as AmbientLight,La as BoxGeometry,zt as BufferAttribute,$t as BufferGeometry,za as Camera,Tl as CapsuleGeometry,Jo as CatmullRomCurve3,Pl as CircleGeometry,ml as Clock,Br as Color,Wo as ConeGeometry,Zo as CubicBezierCurve3,hi as Curve3,Ra as CylinderGeometry,tl as DataTexture,ul as DirectionalLight,Al as DodecahedronGeometry,El as EdgesGeometry,Ca as Euler,Oo as Float32BufferAttribute,ll as Group,Za as HemisphereLight,eh as IKSolver,eu as IMAGE_SYSTEM_PROMPT,Sl as IcosahedronGeometry,Da as InstancedMesh,Qu as InteractivityVM,ah as LOD,Ia as LatheGeometry,fi as Light,ka as LightShadow,Pi as Line,zn as LineBasicMaterial,Yo as LineCurve3,Nl as LineDashedMaterial,Ll as LineLoop,Rl as LineSegments,wo as LodController,Xc as MAX_BSP_DEPTH,Kc as MAX_CSG_TRIANGLES,Hi as MAX_INSTANCES_PER_MESH,Jn as MAX_SHADOW_LIGHTS,Qc as MAX_SHAPE_POINTS,Yc as MAX_TEXT_GEOMETRY_CHARS,Ah as MAX_TSL_NODES,Th as MAX_TSL_UNIFORMS,_r as Material,Uo as MathUtils,zo as Matrix3,Ai as Matrix4,Yr as Mesh,nl as MeshBasicMaterial,al as MeshLambertMaterial,sl as MeshPhongMaterial,ol as MeshPhysicalMaterial,Gi as MeshStandardMaterial,zr as Object3D,_l as OctahedronGeometry,Km as PART_STRIDE_BYTES,Wm as PART_STRIDE_WORDS,cl as PerspectiveCamera,Ho as PlaneGeometry,Ba as PointLight,Il as Points,Qa as PointsMaterial,Qh as PolyhedronFallbackGeometry,pi as PolyhedronGeometry,Qo as QuadraticBezierCurve3,Dn as Quaternion,vl as RawShaderMaterial,Dl as RectAreaLight,Ya as RingGeometry,Ws as SCENE_PBR_WGSL,_c as SCENE_PICK_WGSL,Mc as SCENE_SHADOW_WGSL,qm as SCENE_UNIFORM_BYTES,sc as SHADOW_MAP_TEXTURE_UNIT,Va as Scene,Qr as SceneQuotaValidator,Ka as ShaderMaterial,qo as SphereGeometry,$l as SpotLight,lu as TEXTURE_PROMPT_SUFFIX,Ni as THREE,Ui as TSL_EXTENSION_NAME,Ph as TSL_TIME_PERIOD_SEC,Um as TSL_WGSL_UNIFORM_BYTES,wl as TetrahedronGeometry,kn as Texture,rl as TextureLoader,di as ThreeLiveElement,ir as ThreeView,Ko as TorusGeometry,Xo as TorusKnotGeometry,el as TubeGeometry,jo as Uint16BufferAttribute,Go as Uint32BufferAttribute,Ym as VERTEX_STRIDE_BYTES,Xm as VERTEX_STRIDE_FLOATS,ar as Vector2,Ze as Vector3,Bo as Vector4,fl as WebGLRenderer,Cc as WebGPUSceneAccelerator,Cl as WireframeGeometry,Ri as acquireSceneWebGPUDevice,Uu as activateAR,Ts as aiPlugin,tc as applyMeshoptFilter,Bn as authorScriptRunner,On as browserImageCodec,ru as buildImageMessages,tu as buildImageUserText,Ha as buildSandboxWorkerSource,ns as buildSelectIndex,lo as cadPlugin,xl as clearAuthorWarnings,au as compileFromImage,$o as compileTslToGlsl,bc as compileTslToWgsl,Tm as computeOutlineClipOffset,uc as computeWorldSceneBounds,xs as connectVoice,Ps as contactShadowPlugin,_u as createAIChatProvider,uu as createAIImageProvider,Aa as createUSDZBlob,wu as createWebSpeechRecognizer,Eu as crossFadeTo,nh as decimateGeometry,rc as decodeMeshoptBuffer,Fs as decodeMeshoptGLB,rf as defineModelViewer,Ms as describeEditResult,ss as describeSelection,Ji as describeVoiceSelection,nu as detectImageMime,on as doesMeshCastShadow,js as doesMeshReceiveShadow,Tu as editScene,_m as encodeMeshoptBuffer,Hu as environmentMapPlugin,Am as evaluateKawaseBloom,fh as evaluateToneMapping,Ua as exportSceneToCanvas3D,Oa as exportSceneToGLB,hl as exportSceneToUSDZ,pc as extractMaterialVariants,Bm as extractPrimitiveVariantMappings,As as extractScript,cc as fitDirectionalShadowMatrix,Os as fitSpotShadowMatrix,Xr as fmtShaderFloat,us as formatSpatialPriors,xu as geminiLiveAdapter,Sa as generateUSDZ,Ns as getARCapabilities,yl as getAllowClientScripts,bl as getAuthorWarnings,Qf as getBestARMode,em as getEnvironmentSH,$s as getInteractivityVM,sh as getLodController,Ga as getSandboxEngineSrc,gl as getSandboxIframeSrc,yr as getSelection,Im as getShadowMapStats,hn as getWebGPUSceneAccelerator,_a as glbToUSDZ,Hn as hideSelectionChips,Ku as hotspotPlugin,vo as ikPlugin,iu as imageRepairMessage,mu as indexedDbTextureCache,ha as installCadExtension,Tn as installLodExtension,ga as installProceduralExtension,Ta as installTslExtension,Ju as interactivityPlugin,$r as isAllowedImageUrl,Ti as isAllowedSandboxEngineUrl,Bu as isQuickLookSupported,zu as isSceneViewerSupported,Vu as isWebXRSupported,Iu as keyframeAnimationPlugin,Mo as lodPlugin,Ol as matchSelection,ec as materialsPlugin,Bs as meshoptDecoder,ic as meshoptPlugin,$u as morphPlugin,qi as noopProxy,hs as normalizeImageInput,Tc as normalizeRendererPreference,lc as normalizeShadowMapsMode,Pa as packUniformVec4,Cu as parseAnimations,nc as parseHexRgb,da as parseLod,Yn as parseSafeGltfPointer,Zl as parseSelectReply,hu as parseTexturePack,Wl as parseVoiceCommand,ac as postprocessingPlugin,cu as prepareAlbedo,_o as proceduralPlugin,fa as quatFromUnitVectors,bu as realtimeAdapter,cm as registerMaterialShader,aa as remapClipDepthToZeroOne,n0 as resetSceneWebGPUDevice,Gs as resolveActiveShadowLights,Js as resolveSceneRenderBackend,Yl as resolveSelection,Jl as resolveSelectionWithModel,en as sampleChannel,Vn as sceneSelectEntries,Vi as sceneToCanvas3D,En as sceneToGLB,In as sceneToUSDZ,qn as selectByVoice,os as selectCamera,pa as selectLodLevelIndex,zm as selectMaterialVariant,Ql as selectMessages,Mu as selectNamesByVoice,Zu as sendInteractivityEvent,fu as serializeTexturePack,Do as serializeTslToUsda,jh as setAllowClientScripts,ju as setEnvironmentSH,xc as setMaterialUniform,Xf as setMorphTargetWeight,Uh as setSandboxEngineSrc,Oh as setSandboxIframeSrc,i0 as setSceneWebGPUDeviceForTests,Ss as setSelectOnTap,Ar as setSelection,mc as shadowMapsPlugin,gu as showSelectionChips,ku as skinningPlugin,mo as solveFABRIK,fo as solveTwoBoneIK,ws as speakableName,_s as startVoiceEdit,ps as textureRequests,Wi as threeAuthorPlugin,tf as threeMicroPlugin,zi as toGLBData,pl as toTrustedWorkerScriptURL,vc as tslPlugin,Lo as tslSafeMod,nr as tslTypeArity,Ro as tslTypeFromArity,Pu as undoEdit,qa as validateSandboxWorkerMessage,Oi as validateTslGraph,dc as variantsPlugin,Zr as warnUnsupported,Ec as webgpuScenePlugin,gc as webxrPlugin,qs as writeSceneUniforms};
|