1const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/babylon-core-D3-mfcAc.js","assets/rolldown-runtime-B0Z9INg1.js"])))=>i.map(i=>d[i]); 2import{r as e}from"./rolldown-runtime-B0Z9INg1.js";import{C as t,S as n,_ as r,a as i,b as a,i as o,n as s,o as c,r as l,t as u,v as d,w as f,x as p,y as m}from"./babylon-inspector-0uPFKmPh.js";import{$d as h,$f as g,$m as _,$n as v,$o as y,$p as b,$s as x,Ad as S,Af as C,An as w,Au as T,Bf as E,Bm as D,Bo as ee,Bs as te,Ca as O,Cm as ne,Cn as re,Cu as ie,Dh as ae,Dr as oe,Du as se,Eh as ce,Fp as le,Fs as ue,Fu as de,Gm as fe,Gs as pe,Hf as me,Hl as he,Ho as ge,Hs as _e,Ic as k,If as ve,Is as ye,Jf as be,Jm as A,Ks as xe,Lc as Se,Lf as Ce,Ln as we,Ls as Te,Md as Ee,Mf as De,Ml as Oe,Mn as ke,Mp as j,Ms as Ae,Mu as je,Nd as Me,Nf as Ne,Nn as Pe,Np as Fe,Ns as Ie,Nu as Le,Oc as Re,On as ze,Pd as Be,Pp as Ve,Ps as He,Pu as Ue,Qd as We,Qf as Ge,Qi as Ke,Qn as qe,Qo as Je,Qp as Ye,Qs as Xe,Qt as Ze,Rn as Qe,Ro as $e,Rp as et,Rs as tt,Sm as M,Su as nt,Tn as rt,Uf as it,Ul as at,Uo as ot,Us as st,Vf as ct,Vm as lt,Vo as ut,Vs as dt,Wf as ft,Ws as pt,Xd as mt,Xf as ht,Xi as gt,Xm as N,Xp as P,Xs as _t,Yf as vt,Ym as yt,Zd as bt,Zf as xt,Zm as F,Zn as St,Zo as Ct,Zp as wt,Zs as Tt,_d as I,_p as Et,_r as Dt,_s as Ot,aa as kt,af as At,ah as jt,am as Mt,an as Nt,ap as Pt,ar as Ft,ba as It,bt as Lt,cf as Rt,cm as zt,cn as Bt,cr as Vt,dn as Ht,dt as Ut,du as Wt,ec as Gt,ef as Kt,eh as L,em as qt,er as Jt,fd as Yt,fm as Xt,fn as Zt,ft as Qt,ga as $t,gd as en,gp as tn,gr as nn,gu as rn,ha as an,hd as on,hn as sn,hp as cn,hr as ln,hu as un,ia as dn,ic as fn,ih as R,il as pn,ip as mn,ir as hn,jf as gn,jn as _n,jp as vn,js as yn,ju as bn,kc as xn,kd as Sn,kn as Cn,la as wn,lf as Tn,ln as En,lp as Dn,lr as On,md as kn,mn as An,n as jn,nc as Mn,nf as Nn,nh as Pn,nm as Fn,nr as In,oa as Ln,of as Rn,oh as zn,on as Bn,op as Vn,or as Hn,pd as Un,pn as Wn,qf as Gn,qs as Kn,ra as qn,rc as Jn,rf as Yn,rh as Xn,rl as Zn,rm as Qn,rr as $n,sf as er,sn as tr,sr as nr,t as rr,tc as ir,th as z,tm as ar,tp as or,tr as sr,ud as cr,uf as lr,um as ur,un as dr,uu as fr,vd as pr,vm as mr,vp as hr,vr as gr,vs as _r,wa as vr,wh as yr,wu as br,xh as xr,xt as Sr,xu as Cr,ya as wr,ym as Tr,yu as Er,zp as Dr,zs as Or}from"./babylon-core-D3-mfcAc.js";zn(),_(),b(),fn(),Mn(),x(),Tt(),Kn(),te();var kr;(function(e){e[e.BYTE=5120]=`BYTE`,e[e.UNSIGNED_BYTE=5121]=`UNSIGNED_BYTE`,e[e.SHORT=5122]=`SHORT`,e[e.UNSIGNED_SHORT=5123]=`UNSIGNED_SHORT`,e[e.FLOAT=5126]=`FLOAT`})(kr||={});var Ar;(function(e){e[e.FRAGMENT=35632]=`FRAGMENT`,e[e.VERTEX=35633]=`VERTEX`})(Ar||={});var jr;(function(e){e[e.BYTE=5120]=`BYTE`,e[e.UNSIGNED_BYTE=5121]=`UNSIGNED_BYTE`,e[e.SHORT=5122]=`SHORT`,e[e.UNSIGNED_SHORT=5123]=`UNSIGNED_SHORT`,e[e.INT=5124]=`INT`,e[e.UNSIGNED_INT=5125]=`UNSIGNED_INT`,e[e.FLOAT=5126]=`FLOAT`,e[e.FLOAT_VEC2=35664]=`FLOAT_VEC2`,e[e.FLOAT_VEC3=35665]=`FLOAT_VEC3`,e[e.FLOAT_VEC4=35666]=`FLOAT_VEC4`,e[e.INT_VEC2=35667]=`INT_VEC2`,e[e.INT_VEC3=35668]=`INT_VEC3`,e[e.INT_VEC4=35669]=`INT_VEC4`,e[e.BOOL=35670]=`BOOL`,e[e.BOOL_VEC2=35671]=`BOOL_VEC2`,e[e.BOOL_VEC3=35672]=`BOOL_VEC3`,e[e.BOOL_VEC4=35673]=`BOOL_VEC4`,e[e.FLOAT_MAT2=35674]=`FLOAT_MAT2`,e[e.FLOAT_MAT3=35675]=`FLOAT_MAT3`,e[e.FLOAT_MAT4=35676]=`FLOAT_MAT4`,e[e.SAMPLER_2D=35678]=`SAMPLER_2D`})(jr||={});var Mr;(function(e){e[e.CLAMP_TO_EDGE=33071]=`CLAMP_TO_EDGE`,e[e.MIRRORED_REPEAT=33648]=`MIRRORED_REPEAT`,e[e.REPEAT=10497]=`REPEAT`})(Mr||={});var Nr;(function(e){e[e.NEAREST=9728]=`NEAREST`,e[e.LINEAR=9728]=`LINEAR`,e[e.NEAREST_MIPMAP_NEAREST=9984]=`NEAREST_MIPMAP_NEAREST`,e[e.LINEAR_MIPMAP_NEAREST=9985]=`LINEAR_MIPMAP_NEAREST`,e[e.NEAREST_MIPMAP_LINEAR=9986]=`NEAREST_MIPMAP_LINEAR`,e[e.LINEAR_MIPMAP_LINEAR=9987]=`LINEAR_MIPMAP_LINEAR`})(Nr||={});var Pr;(function(e){e[e.ALPHA=6406]=`ALPHA`,e[e.RGB=6407]=`RGB`,e[e.RGBA=6408]=`RGBA`,e[e.LUMINANCE=6409]=`LUMINANCE`,e[e.LUMINANCE_ALPHA=6410]=`LUMINANCE_ALPHA`})(Pr||={});var Fr;(function(e){e[e.FRONT=1028]=`FRONT`,e[e.BACK=1029]=`BACK`,e[e.FRONT_AND_BACK=1032]=`FRONT_AND_BACK`})(Fr||={});var Ir;(function(e){e[e.ZERO=0]=`ZERO`,e[e.ONE=1]=`ONE`,e[e.SRC_COLOR=768]=`SRC_COLOR`,e[e.ONE_MINUS_SRC_COLOR=769]=`ONE_MINUS_SRC_COLOR`,e[e.DST_COLOR=774]=`DST_COLOR`,e[e.ONE_MINUS_DST_COLOR=775]=`ONE_MINUS_DST_COLOR`,e[e.SRC_ALPHA=770]=`SRC_ALPHA`,e[e.ONE_MINUS_SRC_ALPHA=771]=`ONE_MINUS_SRC_ALPHA`,e[e.DST_ALPHA=772]=`DST_ALPHA`,e[e.ONE_MINUS_DST_ALPHA=773]=`ONE_MINUS_DST_ALPHA`,e[e.CONSTANT_COLOR=32769]=`CONSTANT_COLOR`,e[e.ONE_MINUS_CONSTANT_COLOR=32770]=`ONE_MINUS_CONSTANT_COLOR`,e[e.CONSTANT_ALPHA=32771]=`CONSTANT_ALPHA`,e[e.ONE_MINUS_CONSTANT_ALPHA=32772]=`ONE_MINUS_CONSTANT_ALPHA`,e[e.SRC_ALPHA_SATURATE=776]=`SRC_ALPHA_SATURATE`})(Ir||={}),ae(),xr(),yt(),fe(),ne(),Tr(),Xt(),Mt(),wt(),le(),hr(),tn(),g(),ht(),be(),ft(),me(),ct(),
2Ce(),Ne(),gn(),lr(),Rt(),Rn(),Kt(),en(),kn(),Un(),Wt(),at(),pn(),_r(),Je(),vr(),Dr(),br(),pr();var Lr=class e{static SetMatrix(e,t,n,r,i){let a=null;if(n.semantic===`MODEL`?a=t.getWorldMatrix():n.semantic===`PROJECTION`?a=e.getProjectionMatrix():n.semantic===`VIEW`?a=e.getViewMatrix():n.semantic===`MODELVIEWINVERSETRANSPOSE`?a=L.Transpose(t.getWorldMatrix().multiply(e.getViewMatrix()).invert()):n.semantic===`MODELVIEW`?a=t.getWorldMatrix().multiply(e.getViewMatrix()):n.semantic===`MODELVIEWPROJECTION`?a=t.getWorldMatrix().multiply(e.getTransformMatrix()):n.semantic===`MODELINVERSE`?a=t.getWorldMatrix().invert():n.semantic===`VIEWINVERSE`?a=e.getViewMatrix().invert():n.semantic===`PROJECTIONINVERSE`?a=e.getProjectionMatrix().invert():n.semantic===`MODELVIEWINVERSE`?a=t.getWorldMatrix().multiply(e.getViewMatrix()).invert():n.semantic===`MODELVIEWPROJECTIONINVERSE`?a=t.getWorldMatrix().multiply(e.getTransformMatrix()).invert():n.semantic===`MODELINVERSETRANSPOSE`&&(a=L.Transpose(t.getWorldMatrix().invert())),a)switch(n.type){case jr.FLOAT_MAT2:i.setMatrix2x2(r,L.GetAsMatrix2x2(a));break;case jr.FLOAT_MAT3:i.setMatrix3x3(r,L.GetAsMatrix3x3(a));break;case jr.FLOAT_MAT4:i.setMatrix(r,a)}}static SetUniform(e,t,n,r){switch(r){case jr.FLOAT:return e.setFloat(t,n),!0;case jr.FLOAT_VEC2:return e.setVector2(t,Xn.FromArray(n)),!0;case jr.FLOAT_VEC3:return e.setVector3(t,R.FromArray(n)),!0;case jr.FLOAT_VEC4:return e.setVector4(t,jt.FromArray(n)),!0;default:return!1}}static GetWrapMode(e){switch(e){case Mr.CLAMP_TO_EDGE:return I.CLAMP_ADDRESSMODE;case Mr.MIRRORED_REPEAT:return I.MIRROR_ADDRESSMODE;case Mr.REPEAT:return I.WRAP_ADDRESSMODE;default:return I.WRAP_ADDRESSMODE}}static GetByteStrideFromType(e){switch(e.type){case`VEC2`:return 2;case`VEC3`:return 3;case`VEC4`:return 4;case`MAT2`:return 4;case`MAT3`:return 9;case`MAT4`:return 16;default:return 1}}static GetTextureFilterMode(e){switch(e){case Nr.LINEAR:case Nr.LINEAR_MIPMAP_NEAREST:case Nr.LINEAR_MIPMAP_LINEAR:return I.TRILINEAR_SAMPLINGMODE;case Nr.NEAREST:case Nr.NEAREST_MIPMAP_NEAREST:return I.NEAREST_SAMPLINGMODE;default:return I.BILINEAR_SAMPLINGMODE}}static GetBufferFromBufferView(e,t,n,r,i){n=t.byteOffset+n;let a=e.loadedBufferViews[t.buffer];if(n+r>a.byteLength)throw Error(`Buffer access is out of range`);let o=a.buffer;switch(n+=a.byteOffset,i){case kr.BYTE:return new Int8Array(o,n,r);case kr.UNSIGNED_BYTE:return new Uint8Array(o,n,r);case kr.SHORT:return new Int16Array(o,n,r);case kr.UNSIGNED_SHORT:return new Uint16Array(o,n,r);default:return new Float32Array(o,n,r)}}static GetBufferFromAccessor(t,n){let r=t.bufferViews[n.bufferView],i=n.count*e.GetByteStrideFromType(n);return e.GetBufferFromBufferView(t,r,n.byteOffset,i,n.componentType)}static DecodeBufferToText(e){let t=``,n=e.byteLength;for(let r=0;r<n;++r)t+=String.fromCharCode(e[r]);return t}static GetDefaultMaterial(t){return e._DefaultMaterial||(et.ShadersStore.GLTFDefaultMaterialVertexShader=[`precision highp float;`,``,`uniform mat4 worldView;`,`uniform mat4 projection;`,``,`attribute vec3 position;`,``,`void main(void)`,`{`,` gl_Position = projection * worldView * vec4(position, 1.0);`,`}`].join(` 3`),et.ShadersStore.GLTFDefaultMaterialPixelShader=[`precision highp float;`,``,`uniform vec4 u_emission;`,``,`void main(void)`,`{`,` gl_FragColor = u_emission;`,`}`].join(` 4`),e._DefaultMaterial=new ie(`GLTFDefaultMaterial`,t,{vertex:`GLTFDefaultMaterial`,fragment:`GLTFDefaultMaterial`},{attributes:[`position`],uniforms:[`worldView`,`projection`,`u_emission`],samplers:[],needAlphaBlending:!1}),e._DefaultMaterial.setColor4(`u_emission`,new F(.5,.5,.5,1))),e._DefaultMaterial}};Lr._DefaultMaterial=null,zn(),_(),Dr(),br(),pr(),Se();var Rr;(function(e){e[e.IDENTIFIER=1]=`IDENTIFIER`,e[e.UNKNOWN=2]=`UNKNOWN`,e[e.END_OF_INPUT=3]=`END_OF_INPUT`})(Rr||={});var zr=class{constructor(e){this._pos=0,this.currentToken=Rr.UNKNOWN,this.currentIdentifier=``,this.currentString=``,this.isLetterOrDigitPattern=/^[a-zA-Z0-9]+$/,this._toParse=e,this._maxPos=e.length}getNextToken(){if(this.isEnd())return Rr.END_OF_INPUT;if(this.currentString=this.read(),this.currentToken=Rr.UNKNOWN,this.currentString===`_`||this.isLetterOrDigitPattern.test(this.currentString))for(this.currentToken=Rr.IDENTIFIER,this.currentIdentifier=this.currentString;!this.isEnd()&&(this.isLetterOrDigitPattern.test(this.currentString=this.peek())||this.currentString===`_`);)this.currentIdentifier+=this.currentString,this.forward();return this.currentToken}peek(){return this._toParse[this._pos]}read(){return this._toParse[this._pos++]}forward(){this._pos++}isEnd(){return this._pos>=this._maxPos}},Br=[`MODEL`,`VIEW`,`PROJECTION`,`MODELVIEW`,`MODELVIEWPROJECTION`,`JOINTMATRIX`],Vr=[`world`,`view`,`projection`,`worldView`,`worldViewProjection`,`mBones`],Hr=[`translation`,`rotation`,`scale`],Ur=[`position`,`rotationQuaternion`,`scaling`],Wr=(e,t)=>{for(let n in e){let r=e[n];t.buffers[n]=r,t.buffersCount++}},Gr=(e,t)=>{for(let n in e){let r=e[n];t.shaders[n]=r,t.shaderscount++}}
4,Kr=(e,t,n)=>{for(let r in e){let i=e[r];n[t][r]=i}},qr=e=>{if(e)for(let t=0;t<e.length/2;t++)e[t*2+1]=1-e[t*2+1]},Jr=e=>{if(e.semantic===`NORMAL`)return`normal`;if(e.semantic===`POSITION`)return`position`;if(e.semantic===`JOINT`)return`matricesIndices`;if(e.semantic===`WEIGHT`)return`matricesWeights`;if(e.semantic===`COLOR`)return`color`;if(e.semantic&&e.semantic.indexOf(`TEXCOORD_`)!==-1){let t=Number(e.semantic.split(`_`)[1]);return`uv`+(t===0?``:t+1)}return null},Yr=e=>{for(let t in e.animations){let n=e.animations[t];if(!n.channels||!n.samplers)continue;let r=null;for(let i=0;i<n.channels.length;i++){let a=n.channels[i],o=n.samplers[a.sampler];if(!o)continue;let s,c;n.parameters?(s=n.parameters[o.input],c=n.parameters[o.output]):(s=o.input,c=o.output);let l=Lr.GetBufferFromAccessor(e,e.accessors[s]),u=Lr.GetBufferFromAccessor(e,e.accessors[c]),d=a.target.id,f=e.scene.getNodeById(d);if(f===null&&(f=e.scene.getNodeByName(d)),f===null){P.Warn(`Creating animation named `+t+`. But cannot find node named `+d+` to attach to`);continue}let p=f instanceof mr,m=a.target.path,h=Hr.indexOf(m);h!==-1&&(m=Ur[h]);let g=M.ANIMATIONTYPE_MATRIX;p||(m===`rotationQuaternion`?(g=M.ANIMATIONTYPE_QUATERNION,f.rotationQuaternion=new z):g=M.ANIMATIONTYPE_VECTOR3);let _=null,v=[],y=0,b=!1;p&&r&&r.getKeys().length===l.length&&(_=r,b=!0),b||(e.scene._blockEntityCollection=!!e.assetContainer,_=new M(t,p?`_matrix`:m,1,g,M.ANIMATIONLOOPMODE_CYCLE),e.scene._blockEntityCollection=!1);for(let e=0;e<l.length;e++){let t;if(m===`rotationQuaternion`?(t=z.FromArray([u[y],u[y+1],u[y+2],u[y+3]]),y+=4):(t=R.FromArray([u[y],u[y+1],u[y+2]]),y+=3),p){let n=f,i=R.Zero(),a=new z,o=R.Zero(),s=n.getBaseMatrix();b&&r&&(s=r.getKeys()[e].value),s.decompose(o,a,i),m===`position`?i=t:m===`rotationQuaternion`?a=t:o=t,t=L.Compose(o,a,i)}b?r&&(r.getKeys()[e].value=t):v.push({frame:l[e],value:t})}!b&&_&&(_.setKeys(v),f.animations.push(_)),r=_,e.scene.stopAnimation(f),e.scene.beginAnimation(f,0,l[l.length-1],!0,1)}}},Xr=e=>{let t;if(e.translation||e.rotation||e.scale){let n=R.FromArray(e.scale||[1,1,1]),r=z.FromArray(e.rotation||[0,0,0,1]),i=R.FromArray(e.translation||[0,0,0]);t=L.Compose(n,r,i)}else t=L.FromArray(e.matrix);return t},Zr=(e,t,n,r)=>{for(let e=0;e<r.bones.length;e++)if(r.bones[e].name===n)return r.bones[e];let i=e.nodes;for(let a in i){let o=i[a];if(!o.jointName)continue;let s=o.children;for(let i=0;i<s.length;i++){let c=e.nodes[s[i]];if(c.jointName&&c.jointName===n){let n=Xr(o),i=new mr(o.name||``,r,Zr(e,t,o.jointName,r),n);return i.id=a,i}}}return null},Qr=(e,t)=>{for(let n=0;n<e.length;n++){let r=e[n];for(let e=0;e<r.node.children.length;e++)if(r.node.children[e]===t)return r.bone}return null},$r=(e,t)=>{let n=e.nodes,r=n[t];if(r)return{node:r,id:t};for(let e in n)if(r=n[e],r.jointName===t)return{node:r,id:e};return null},ei=(e,t)=>{for(let n=0;n<e.jointNames.length;n++)if(e.jointNames[n]===t)return!0;return!1},ti=(e,t,n,r)=>{for(let i in e.nodes){let a=e.nodes[i],o=i;if(!a.jointName||ei(n,a.jointName))continue;let s=Xr(a),c=new mr(a.name||``,t,null,s);c.id=o,r.push({bone:c,node:a,id:o})}for(let e=0;e<r.length;e++){let t=r[e],n=t.node.children;for(let e=0;e<n.length;e++){let i=null;for(let t=0;t<r.length;t++)if(r[t].id===n[e]){i=r[t];break}i&&(i.bone._parent=t.bone,t.bone.children.push(i.bone))}}},ni=(e,t,n,r)=>{if(r||=new Yt(t.name||``,``,e.scene),!t.babylonSkeleton)return r;let i=[],a=[];ti(e,r,t,i),r.bones=[];for(let n=0;n<t.jointNames.length;n++){let o=$r(e,t.jointNames[n]);if(!o)continue;let s=o.node;if(!s){P.Warn(`Joint named `+t.jointNames[n]+` does not exist`);continue}let c=o.id,l=e.scene.getBoneById(c);if(l){r.bones.push(l);continue}let u,d=null;for(let i=0;i<n;i++){let n=$r(e,t.jointNames[i]);if(!n)continue;let a=n.node;if(!a){P.Warn(`Joint named `+t.jointNames[i]+` does not exist when looking for parent`);continue}let o=a.children;if(o){u=!1;for(let n=0;n<o.length;n++)if(o[n]===c){d=Zr(e,t,t.jointNames[i],r),u=!0;break}if(u)break}}let f=Xr(s);!d&&i.length>0&&(d=Qr(i,c),d&&a.indexOf(d)===-1&&a.push(d));let p=new mr(s.jointName||``,r,d,f);p.id=c}let o=r.bones;r.bones=[];for(let n=0;n<t.jointNames.length;n++){let i=$r(e,t.jointNames[n]);if(i){for(let e=0;e<o.length;
4e++)if(o[e].id===i.id){r.bones.push(o[e]);break}}}r.prepare();for(let e=0;e<a.length;e++)r.bones.push(a[e]);return r},ri=(e,t,n,r,i)=>{if(i||(e.scene._blockEntityCollection=!!e.assetContainer,i=new At(t.name||``,e.scene),i._parentContainer=e.assetContainer,e.scene._blockEntityCollection=!1,i.id=r),!t.babylonNode)return i;let o=[],s=null,c=[],l=[],u=[],d=[];for(let t=0;t<n.length;t++){let r=n[t],i=e.meshes[r];if(i)for(let t=0;t<i.primitives.length;t++){let n=new E,r=i.primitives[t];r.mode;let f=r.attributes,p,m;for(let t in f)if(p=e.accessors[f[t]],m=Lr.GetBufferFromAccessor(e,p),t===`NORMAL`)n.normals=new Float32Array(m.length),n.normals.set(m);else if(t===`POSITION`){if(a.HomogeneousCoordinates){n.positions=new Float32Array(m.length-m.length/4);for(let e=0;e<m.length;e+=4)n.positions[e]=m[e],n.positions[e+1]=m[e+1],n.positions[e+2]=m[e+2]}else n.positions=new Float32Array(m.length),n.positions.set(m);l.push(n.positions.length)}else if(t.indexOf(`TEXCOORD_`)!==-1){let e=Number(t.split(`_`)[1]),r=j.UVKind+(e===0?``:e+1),i=new Float32Array(m.length);i.set(m),qr(i),n.set(i,r)}else t===`JOINT`?(n.matricesIndices=new Float32Array(m.length),n.matricesIndices.set(m)):t===`WEIGHT`?(n.matricesWeights=new Float32Array(m.length),n.matricesWeights.set(m)):t===`COLOR`&&(n.colors=new Float32Array(m.length),n.colors.set(m));if(p=e.accessors[r.indices],p)m=Lr.GetBufferFromAccessor(e,p),n.indices=new Int32Array(m.length),n.indices.set(m),d.push(n.indices.length);else{let e=[];for(let t=0;t<n.positions.length/3;t++)e.push(t);n.indices=new Int32Array(e),d.push(n.indices.length)}s?s.merge(n):s=n;let h=e.scene.getMaterialById(r.material);o.push(h===null?Lr.GetDefaultMaterial(e.scene):h),c.push(c.length===0?0:c[c.length-1]+l[l.length-2]),u.push(u.length===0?0:u[u.length-1]+d[d.length-2])}}let f;e.scene._blockEntityCollection=!!e.assetContainer,o.length>1?(f=new er(`multimat`+r,e.scene),f.subMaterials=o):f=new he(`multimat`+r,e.scene),o.length===1&&(f=o[0]),f._parentContainer=e.assetContainer,i.material||(i.material=f),new C(r,e.scene,s,!1,i),i.computeWorldMatrix(!0),e.scene._blockEntityCollection=!1,i.subMeshes=[];let p=0;for(let t=0;t<n.length;t++){let r=n[t],a=e.meshes[r];if(a)for(let e=0;e<a.primitives.length;e++)a.primitives[e].mode,it.AddToMesh(p,c[p],l[p],u[p],d[p],i,i,!0),p++}return i},ii=(e,t,n,r)=>{e.position&&=t,(e.rotationQuaternion||e.rotation)&&(e.rotationQuaternion=n),e.scaling&&=r},ai=(e,t)=>{if(t.matrix){let n=new R(0,0,0),r=new z,i=new R(0,0,0);L.FromArray(t.matrix).decompose(i,r,n),ii(e,n,r,i)}else t.translation&&t.rotation&&t.scale&&ii(e,R.FromArray(t.translation),z.FromArray(t.rotation),R.FromArray(t.scale));e.computeWorldMatrix(!0)},oi=(e,t,n)=>{let r=null;if(e.importOnlyMeshes&&(t.skin||t.meshes)&&e.importMeshesNames&&e.importMeshesNames.length>0&&e.importMeshesNames.indexOf(t.name||``)===-1)return null;if(t.skin){if(t.meshes){let i=e.skins[t.skin],a=ri(e,t,t.meshes,n,t.babylonNode);a.skeleton=e.scene.getLastSkeletonById(t.skin),a.skeleton===null&&(a.skeleton=ni(e,i,a,i.babylonSkeleton),i.babylonSkeleton||=a.skeleton),r=a}}else if(t.meshes)r=ri(e,t,t.mesh?[t.mesh]:t.meshes,n,t.babylonNode);else if(t.light&&!t.babylonNode&&!e.importOnlyMeshes){let n=e.lights[t.light];if(n){if(n.type===`ambient`){let i=n[n.type],a=new Zn(t.light,R.Zero(),e.scene);a.name=t.name||``,i.color&&(a.diffuse=N.FromArray(i.color)),r=a}else if(n.type===`directional`){let i=n[n.type],a=new Ot(t.light,R.Zero(),e.scene);a.name=t.name||``,i.color&&(a.diffuse=N.FromArray(i.color)),r=a}else if(n.type===`point`){let i=n[n.type],a=new O(t.light,R.Zero(),e.scene);a.name=t.name||``,i.color&&(a.diffuse=N.FromArray(i.color)),r=a}else if(n.type===`spot`){let i=n[n.type],a=new Ct(t.light,R.Zero(),R.Zero(),0,0,e.scene);a.name=t.name||``,i.color&&(a.diffuse=N.FromArray(i.color)),i.fallOfAngle&&(a.angle=i.fallOfAngle),i.fallOffExponent&&(a.exponent=i.fallOffExponent),r=a}}}else if(t.camera&&!t.babylonNode&&!e.importOnlyMeshes){let n=e.cameras[t.camera];if(n){if(e.scene._blockEntityCollection=!!e.assetContainer,n.type===`orthographic`){let n=new fr(t.camera,R.Zero(),e.scene,!1);n.name=t.name||``,n.mode=De.ORTHOGRAPHIC_CAMERA,n.attachControl(),r=n,n._parentContainer=e.assetContainer}else if(n.type===`perspective`){let i=n[n.type],a=new fr(t.camera,R.Zero(),e.scene,!1);a.name=t.name||``,a.attachControl(),i.aspectRatio||=e.scene.getEngine().getRenderWidth()/e.scene.getEngine().getRenderHeight(),i.znear&&i.zfar&&(a.maxZ=i.zfar,a.minZ=i.znear),r=a,a._parentContainer=e.assetContainer}e.scene._blockEntityCollection=!1}}if(!t.jointName){if(t.babylonNode)return t.babylonNode;
4if(r===null){e.scene._blockEntityCollection=!!e.assetContainer;let n=new At(t.name||``,e.scene);n._parentContainer=e.assetContainer,e.scene._blockEntityCollection=!1,t.babylonNode=n,r=n}}if(r!==null){if(t.matrix&&r instanceof At)ai(r,t);else{let e=t.translation||[0,0,0],n=t.rotation||[0,0,0,1],i=t.scale||[1,1,1];ii(r,R.FromArray(e),z.FromArray(n),R.FromArray(i))}r.updateCache(!0),t.babylonNode=r}return r},si=(e,t,n,r=!1)=>{let i=e.nodes[t],a=null;if(r=e.importOnlyMeshes&&!r&&e.importMeshesNames?e.importMeshesNames.indexOf(i.name||``)!==-1||e.importMeshesNames.length===0:!0,!i.jointName&&r&&(a=oi(e,i,t),a!==null&&(a.id=t,a.parent=n)),i.children)for(let t=0;t<i.children.length;t++)si(e,i.children[t],a,r)},ci=e=>{let t=e.currentScene;if(t)for(let n=0;n<t.nodes.length;n++)si(e,t.nodes[n],null);else for(let n in e.scenes){t=e.scenes[n];for(let n=0;n<t.nodes.length;n++)si(e,t.nodes[n],null)}Yr(e);for(let t=0;t<e.scene.skeletons.length;t++){let n=e.scene.skeletons[t];e.scene.beginAnimation(n,0,Number.MAX_VALUE,!0,1)}},li=(e,t,n,r,i,a,o)=>{let s=a.values||i.parameters;for(let o in n){let c=n[o],l=c.type;if(l===jr.FLOAT_MAT2||l===jr.FLOAT_MAT3||l===jr.FLOAT_MAT4){if(c.semantic&&!c.source&&!c.node)Lr.SetMatrix(t.scene,e,c,o,r.getEffect());else if(c.semantic&&(c.source||c.node)){let e=t.scene.getNodeByName(c.source||c.node||``);if(e===null&&(e=t.scene.getNodeById(c.source||c.node||``)),e===null)continue;Lr.SetMatrix(t.scene,e,c,o,r.getEffect())}}else{let e=s[i.uniforms[o]];if(!e)continue;if(l===jr.SAMPLER_2D){let n=t.textures[a.values?e:c.value].babylonTexture;if(n==null)continue;r.getEffect().setTexture(o,n)}else Lr.SetUniform(r.getEffect(),o,e,l)}}o(r)},ui=(e,t,n,r,i)=>{let a=r.values||n.parameters,o=n.uniforms;for(let n in i){let s=i[n],c=s.type,l=a[o[n]];if(l===void 0&&(l=s.value),!l)continue;let u=e=>n=>{s.value&&e&&(t.setTexture(e,n),delete i[e])};c===jr.SAMPLER_2D?_i.LoadTextureAsync(e,r.values?l:s.value,u(n),()=>u(null)):s.value&&Lr.SetUniform(t,n,r.values?l:s.value,c)&&delete i[n]}},di=(e,t,n)=>(r,i)=>{t.dispose(!0),n(`Cannot compile program named `+e.name+`. Error: `+i+`. Default material will be applied`)},fi=(e,t,n,r,i,a)=>o=>{ui(e,t,n,r,i),t.onBind=o=>{li(o,e,i,t,n,r,a)}},pi=(e,t,n)=>{for(let r in t.uniforms){let i=t.uniforms[r],a=t.parameters[i];if(e.currentIdentifier===r&&a.semantic&&!a.source&&!a.node){let e=Br.indexOf(a.semantic);if(e!==-1)return delete n[r],Vr[e]}}return e.currentIdentifier},mi=e=>{for(let t in e.materials)_i.LoadMaterialAsync(e,t,()=>{},()=>{})},hi=class{static CreateRuntime(e,t,n){let r={extensions:{},accessors:{},buffers:{},bufferViews:{},meshes:{},lights:{},cameras:{},nodes:{},images:{},textures:{},shaders:{},programs:{},samplers:{},techniques:{},materials:{},animations:{},skins:{},extensionsUsed:[],scenes:{},buffersCount:0,shaderscount:0,scene:t,rootUrl:n,loadedBufferCount:0,loadedBufferViews:{},loadedShaderCount:0,importOnlyMeshes:!1,dummyNodes:[],assetContainer:null};return e.extensions&&Kr(e.extensions,`extensions`,r),e.extensionsUsed&&Kr(e.extensionsUsed,`extensionsUsed`,r),e.buffers&&Wr(e.buffers,r),e.bufferViews&&Kr(e.bufferViews,`bufferViews`,r),e.accessors&&Kr(e.accessors,`accessors`,r),e.meshes&&Kr(e.meshes,`meshes`,r),e.lights&&Kr(e.lights,`lights`,r),e.cameras&&Kr(e.cameras,`cameras`,r),e.nodes&&Kr(e.nodes,`nodes`,r),e.images&&Kr(e.images,`images`,r),e.textures&&Kr(e.textures,`textures`,r),e.shaders&&Gr(e.shaders,r),e.programs&&Kr(e.programs,`programs`,r),e.samplers&&Kr(e.samplers,`samplers`,r),e.techniques&&Kr(e.techniques,`techniques`,r),e.materials&&Kr(e.materials,`materials`,r),e.animations&&Kr(e.animations,`animations`,r),e.skins&&Kr(e.skins,`skins`,r),e.scenes&&(r.scenes=e.scenes),e.scene&&e.scenes&&(r.currentScene=e.scenes[e.scene]),r}static LoadBufferAsync(e,t,n,r,i){let a=e.buffers[t];P.IsBase64(a.uri)?setTimeout(()=>n(new Uint8Array(P.DecodeBase64(a.uri)))):P.LoadFile(e.rootUrl+a.uri,e=>n(new Uint8Array(e)),i,void 0,!0,e=>{e&&r(e.status+` `+e.statusText)})}static LoadTextureBufferAsync(e,t,n,r){let i=e.textures[t];if(!i||!i.source){r(``);return}if(i.babylonTexture){n(null);return}let a=e.images[i.source];P.IsBase64(a.uri)?setTimeout(()=>n(new Uint8Array(P.DecodeBase64(a.uri)))):P.LoadFile(e.rootUrl+a.uri,e=>n(new Uint8Array(e)),void 0,void 0,!0,e=>{e&&r(e.status+` `+e.statusText)})}static CreateTextureAsync(e,t,n,r){let i=e.textures[t];if(i.babylonTexture){r(i.babylonTexture);return}let a=e.samplers[i.sampler],o=a.minFilter===Nr.NEAREST_MIPMAP_NEAREST||a.minFilter===Nr.NEAREST_MIPMAP_LINEAR||a.minFilter===Nr.LINEAR_MIPMAP_NEAREST||a.minFilter===Nr.LINEAR_MIPMAP_LINEAR,s=I.BILINEAR_SAMPLINGMODE,c=n==null?new Blob:new Blob([zt(n)]),l=URL.createObjectURL(c),u=()=>
4URL.revokeObjectURL(l),d=new I(l,e.scene,!o,!0,s,u,u);a.wrapS!==void 0&&(d.wrapU=Lr.GetWrapMode(a.wrapS)),a.wrapT!==void 0&&(d.wrapV=Lr.GetWrapMode(a.wrapT)),d.name=t,i.babylonTexture=d,r(d)}static LoadShaderStringAsync(e,t,n,r){let i=e.shaders[t];if(P.IsBase64(i.uri)){let e=atob(i.uri.split(`,`)[1]);n&&n(e)}else P.LoadFile(e.rootUrl+i.uri,n,void 0,void 0,!1,e=>{e&&r&&r(e.status+` `+e.statusText)})}static LoadMaterialAsync(e,t,n,r){let i=e.materials[t];if(!i.technique){r&&r(`No technique found.`);return}let a=e.techniques[i.technique];if(!a){e.scene._blockEntityCollection=!!e.assetContainer;let r=new he(t,e.scene);r._parentContainer=e.assetContainer,e.scene._blockEntityCollection=!1,r.diffuseColor=new N(.5,.5,.5),r.sideOrientation=Tn.CounterClockWiseSideOrientation,n(r);return}let o=e.programs[a.program],s=a.states,c=et.ShadersStore[o.vertexShader+`VertexShader`],l=et.ShadersStore[o.fragmentShader+`PixelShader`],u=``,d=``,f=new zr(c),p=new zr(l),m={},h=[],g=[],_=[];for(let e in a.uniforms){let t=a.uniforms[e],n=a.parameters[t];if(m[e]=n,n.semantic&&!n.node&&!n.source){let t=Br.indexOf(n.semantic);t===-1?h.push(e):(h.push(Vr[t]),delete m[e])}else n.type===jr.SAMPLER_2D?_.push(e):h.push(e)}for(let e in a.attributes){let t=a.attributes[e],n=a.parameters[t];if(n.semantic){let e=Jr(n);e&&g.push(e)}}for(;!f.isEnd()&&f.getNextToken();){if(f.currentToken!==Rr.IDENTIFIER){u+=f.currentString;continue}let e=!1;for(let t in a.attributes){let n=a.attributes[t],r=a.parameters[n];if(f.currentIdentifier===t&&r.semantic){u+=Jr(r),e=!0;break}}e||(u+=pi(f,a,m))}for(;!p.isEnd()&&p.getNextToken();){if(p.currentToken!==Rr.IDENTIFIER){d+=p.currentString;continue}d+=pi(p,a,m)}let v={vertex:o.vertexShader+t,fragment:o.fragmentShader+t},y={attributes:g,uniforms:h,samplers:_,needAlphaBlending:s&&s.enable&&s.enable.indexOf(3042)!==-1};et.ShadersStore[o.vertexShader+t+`VertexShader`]=u,et.ShadersStore[o.fragmentShader+t+`PixelShader`]=d;let b=new ie(t,e.scene,v,y);if(b.onError=di(o,b,r),b.onCompiled=fi(e,b,a,i,m,n),b.sideOrientation=Tn.CounterClockWiseSideOrientation,s&&s.functions){let e=s.functions;e.cullFace&&e.cullFace[0]!==Fr.BACK&&(b.backFaceCulling=!1);let t=e.blendFuncSeparate;t&&(t[0]===Ir.SRC_ALPHA&&t[1]===Ir.ONE_MINUS_SRC_ALPHA&&t[2]===Ir.ONE&&t[3]===Ir.ONE?b.alphaMode=k.ALPHA_COMBINE:t[0]===Ir.ONE&&t[1]===Ir.ONE&&t[2]===Ir.ZERO&&t[3]===Ir.ONE?b.alphaMode=k.ALPHA_ONEONE:t[0]===Ir.SRC_ALPHA&&t[1]===Ir.ONE&&t[2]===Ir.ZERO&&t[3]===Ir.ONE?b.alphaMode=k.ALPHA_ADD:t[0]===Ir.ZERO&&t[1]===Ir.ONE_MINUS_SRC_COLOR&&t[2]===Ir.ONE&&t[3]===Ir.ONE?b.alphaMode=k.ALPHA_SUBTRACT:t[0]===Ir.DST_COLOR&&t[1]===Ir.ZERO&&t[2]===Ir.ONE&&t[3]===Ir.ONE?b.alphaMode=k.ALPHA_MULTIPLY:t[0]===Ir.SRC_ALPHA&&t[1]===Ir.ONE_MINUS_SRC_COLOR&&t[2]===Ir.ONE&&t[3]===Ir.ONE&&(b.alphaMode=k.ALPHA_MAXIMIZED))}}},gi=class e{static RegisterExtension(t){if(e.Extensions[t.name]){P.Error(`Tool with the same name "`+t.name+`" already exists`);return}e.Extensions[t.name]=t}dispose(){}_importMeshAsync(e,t,n,r,i,o,s,c){return t.useRightHandedSystem=!0,_i.LoadRuntimeAsync(t,n,r,t=>{t.assetContainer=i,t.importOnlyMeshes=!0,e===``?t.importMeshesNames=[]:typeof e==`string`||e&&!(e instanceof Array)?t.importMeshesNames=[e]:(t.importMeshesNames=[],P.Warn(`Argument meshesNames must be of type string or string[]`)),this._createNodes(t);let n=[],r=[];for(let e in t.nodes){let r=t.nodes[e];r.babylonNode instanceof ve&&n.push(r.babylonNode)}for(let e in t.skins){let n=t.skins[e];n.babylonSkeleton instanceof Yt&&r.push(n.babylonSkeleton)}this._loadBuffersAsync(t,()=>{this._loadShadersAsync(t,()=>{mi(t),ci(t),!a.IncrementalLoading&&o&&o(n,r)})}),a.IncrementalLoading&&o&&o(n,r)},c),!0}importMeshAsync(e,t,n,r,i,a){return new Promise((o,s)=>{this._importMeshAsync(e,t,r,i,n,(e,t)=>{o({meshes:e,particleSystems:[],skeletons:t,animationGroups:[],lights:[],transformNodes:[],geometries:[],spriteManagers:[]})},a,e=>{s(Error(e))})})}_loadAsync(e,t,n,r,i,o){e.useRightHandedSystem=!0,_i.LoadRuntimeAsync(e,t,n,e=>{_i.LoadRuntimeExtensionsAsync(e,()=>{this._createNodes(e),this._loadBuffersAsync(e,()=>{this._loadShadersAsync(e,()=>{mi(e),ci(e),a.IncrementalLoading||r()})}),a.IncrementalLoading&&r()},o)},o)}async loadAsync(e,t,n,r){return await new Promise((i,a)=>{this._loadAsync(e,t,n,()=>{i()},r,e=>{a(Error(e))})})}_loadShadersAsync(e,t){let n=!1,r=(n,r)=>{_i.LoadShaderStringAsync(e,n,i=>{i instanceof ArrayBuffer||(e.loadedShaderCount++,i&&(et.ShadersStore[n+(r.type===Ar.VERTEX?`VertexShader`:`PixelShader`)]=i),e.loadedShaderCount===e.shaderscount&&t())},()=>{P.Error(`Error when loading shader program named `+n+` located at `+r.uri)})};for(let t in e.shaders){n=!0;let i=e.shaders[t];i?r.bind(this,t,i)():P.Error(`No shader named: `+t)}n||t()}_loadBuffersAsync(e,t){let n=!1,r=(n,r)=>{_i.LoadBufferAsync(e,n,i=>{e.loadedBufferCount++,i&&(i.byteLength!=e.buffers[n].byteLength&&P.Error(`Buffer named `+n+` is length `+i.byteLength+`. Expected: `+r.byteLength),e.loadedBufferViews[n]=i),e.loadedBufferCount===e.buffersCount&&t()},()=>{P.Error(`Error when loading buffer named `+n+` located at `+r.uri)})};for(let t in e.buffers){n=!0;let i=e.buffers[t];i?r.bind(this,t,i)():P.Error(`No buffer named: `+t)}n||t()}_createNodes(e){let t=e.currentScene;if(t)for(let n=0;n<t.nodes.length;n++)si(e,t.nodes[n],null);else for(let n in e.scenes){t=e.scenes[n];for(let n=0;n<t.nodes.length;n++)si(e,t.nodes[n],null)}}};gi.Extensions={};var _i=class e{constructor(e){this._name=e}get name(){return this._name}loadRuntimeAsync(e,t,n,r,i){return!1}loadRuntimeExtensionsAsync(e,t,n){return!1}loadBufferAsync(e,t,n,r,i){return!1}loadTextureBufferAsync(e,t,n,r){return!1}createTextureAsync(e,t,n,r,i){return!1}loadShaderStringAsync(e,t,n,r){return!1}loadMaterialAsync(e,t,n,r){return!1}static LoadRuntimeAsync(t,n,r,i,a){e._ApplyExtensions(e=>e.loadRuntimeAsync(t,n,r,i,a),()=>{setTimeout(()=>
4{i&&i(hi.CreateRuntime(n.json,t,r))})})}static LoadRuntimeExtensionsAsync(t,n,r){e._ApplyExtensions(e=>e.loadRuntimeExtensionsAsync(t,n,r),()=>{setTimeout(()=>{n()})})}static LoadBufferAsync(t,n,r,i,a){e._ApplyExtensions(e=>e.loadBufferAsync(t,n,r,i,a),()=>{hi.LoadBufferAsync(t,n,r,i,a)})}static LoadTextureAsync(t,n,r,i){e._LoadTextureBufferAsync(t,n,a=>{a&&e._CreateTextureAsync(t,n,a,r,i)},i)}static LoadShaderStringAsync(t,n,r,i){e._ApplyExtensions(e=>e.loadShaderStringAsync(t,n,r,i),()=>{hi.LoadShaderStringAsync(t,n,r,i)})}static LoadMaterialAsync(t,n,r,i){e._ApplyExtensions(e=>e.loadMaterialAsync(t,n,r,i),()=>{hi.LoadMaterialAsync(t,n,r,i)})}static _LoadTextureBufferAsync(t,n,r,i){e._ApplyExtensions(e=>e.loadTextureBufferAsync(t,n,r,i),()=>{hi.LoadTextureBufferAsync(t,n,r,i)})}static _CreateTextureAsync(t,n,r,i,a){e._ApplyExtensions(e=>e.createTextureAsync(t,n,r,i,a),()=>{hi.CreateTextureAsync(t,n,r,i)})}static _ApplyExtensions(e,t){for(let t in gi.Extensions){let n=gi.Extensions[t];if(e(n))return}t()}},vi=!1;function yi(){vi||(vi=!0,a._CreateGLTF1Loader=()=>new gi)}var bi=`binary_glTF`,xi=class extends _i{constructor(){super(`KHR_binary_glTF`)}loadRuntimeAsync(e,t,n,r){let i=t.json.extensionsUsed;return!i||i.indexOf(this.name)===-1||!t.bin?!1:(this._bin=t.bin,r(hi.CreateRu
4ntime(t.json,e,n)),!0)}loadBufferAsync(e,t,n,r){return e.extensionsUsed.indexOf(this.name)===-1||t!==bi?!1:(this._bin.readAsync(0,this._bin.byteLength).then(n,e=>r(e.message)),!0)}loadTextureBufferAsync(e,t,n){let r=e.textures[t],i=e.images[r.source];if(!i.extensions||!(this.name in i.extensions))return!1;let a=i.extensions[this.name],o=e.bufferViews[a.bufferView];return n(Lr.GetBufferFromBufferView(e,o,0,o.byteLength,kr.UNSIGNED_BYTE)),!0}loadShaderStringAsync(e,t,n){let r=e.shaders[t];if(!r.extensions||!(this.name in r.extensions))return!1;let i=r.extensions[this.name],a=e.bufferViews[i.bufferView],o=Lr.GetBufferFromBufferView(e,a,0,a.byteLength,kr.UNSIGNED_BYTE);return setTimeout(()=>{n(Lr.DecodeBufferToText(o))}),!0}},Si=!1;function Ci(){Si||(Si=!0,gi.RegisterExtension(new xi))}yi(),f(),Ci(),zn(),_(),wt(),lr(),at(),pn(),_r(),vr(),Je();var wi=class extends _i{constructor(){super(`KHR_materials_common`)}loadRuntimeExtensionsAsync(e){if(!e.extensions)return!1;let t=e.extensions[this.name];if(!t)return!1;let n=t.lights;if(n)for(let t in n){let r=n[t];switch(r.type){case`ambient`:{let t=new Zn(r.name,new R(0,1,0),e.scene),n=r.ambient;n&&(t.diffuse=N.FromArray(n.color||[1,1,1]));break}case`point`:{let t=new O(r.name,new R(10,10,10),e.scene),n=r.point;n&&(t.diffuse=N.FromArray(n.color||[1,1,1]));break}case`directional`:{let t=new Ot(r.name,new R(0,-1,0),e.scene),n=r.directional;n&&(t.diffuse=N.FromArray(n.color||[1,1,1]));break}case`spot`:{let t=r.spot;if(t){let n=new Ct(r.name,new R(0,10,0),new R(0,-1,0),t.fallOffAngle||Math.PI,t.fallOffExponent||0,e.scene);n.diffuse=N.FromArray(t.color||[1,1,1])}break}default:P.Warn(`GLTF Material Common extension: light type "`+r.type+`â not supported`)}}return!1}loadMaterialAsync(e,t,n,r){let i=e.materials[t];if(!i||!i.extensions)return!1;let a=i.extensions[this.name];if(!a)return!1;let o=new he(t,e.scene);return o.sideOrientation=Tn.CounterClockWiseSideOrientation,a.technique===`CONSTANT`&&(o.disableLighting=!0),o.backFaceCulling=a.doubleSided!==void 0&&!a.doubleSided,o.alpha=a.values.transparency===void 0?1:a.values.transparency,o.specularPower=a.values.shininess===void 0?0:a.values.shininess,typeof a.values.ambient==`string`?this._loadTexture(e,a.values.ambient,o,`ambientTexture`,r):o.ambientColor=N.FromArray(a.values.ambient||[0,0,0]),typeof a.values.diffuse==`string`?this._loadTexture(e,a.values.diffuse,o,`diffuseTexture`,r):o.diffuseColor=N.FromArray(a.values.diffuse||[0,0,0]),typeof a.values.emission==`string`?this._loadTexture(e,a.values.emission,o,`emissiveTexture`,r):o.emissiveColor=N.FromArray(a.values.emission||[0,0,0]),typeof a.values.specular==`string`?this._loadTexture(e,a.values.specular,o,`specularTexture`,r):o.specularColor=N.FromArray(a.values.specular||[0,0,0]),!0}_loadTexture(e,t,n,r,i){hi.LoadTextureBufferAsync(e,t,i=>{hi.CreateTextureAsync(e,t,i,e=>n[r]=e)},i)}},Ti=!1;function Ei(){Ti||(Ti=!0,gi.RegisterExtension(new wi))}Ei(),se(),Ln(),dn(),Bn();var Di=[{regex:RegExp(`^/nodes/\\d+/extensions/`)},{regex:RegExp(`^/animations/\\d+/extensions/`)},{regex:RegExp(`^/nodes/\\d+/weights`)},{regex:RegExp(`^/meshes/\\d+/weights`)},{regex:RegExp(`/extensions/KHR_texture_transform/`)}],Oi=class{constructor(e,t){this._gltf=e,this._infoTree=t}convert(e){let t=this._gltf,n=this._infoTree,r;if(!e.startsWith(`/`))throw Error(`Path must start with a /`);let i=e.split(`/`);if(i.shift(),i[i.length-1].includes(`.length`)){let e=i[i.length-1].split(`.`);i.pop(),i.push(...e)}let a=!1;for(let o of i){if(o===`length`){if(n.length)n=n.length;else if(n.__array__)throw Error(`Path ${e} is invalid - no length accessor`);else throw Error(`Path ${e} is invalid`);t!==void 0&&(r=t);continue}if(n.__ignoreObjectTree__&&(a=!0),n.__array__)n=n.__array__;else if(n=n[o],!n)throw Error(`Path ${e} is invalid`);if(n.__passThroughTarget__)a=!0;else if(a){let e=/^\d+$/.test(o)?parseInt(o,10):NaN;if(!isNaN(e)&&typeof n.get==`function`){let t=n;n={...t},n.get=(n,r,...i)=>t.get(n,e,...i),typeof t.set==`function`&&(n.set=(n,r,i,...a)=>t.set(n,r,e,...a)),typeof t.getTarget==`function`&&(n.getTarget=(n,r,...i)=>t.getTarget(n,e,...i))}}else if(t===void 0){if(!Di.find(t=>t.regex.test(e)))throw Error(`Path ${e}
4 is invalid`)}else t=t?.[o];n.__target__&&t!==void 0&&(r=t)}return{object:r,info:n}}};zn(),Se(),_(),Je();function ki(e,t){return{type:`FlowGraphInteger`,get:t=>{let n=e(t);return n===void 0?void 0:Jn.FromValue(n)},getTarget:t,getPropertyName:[()=>`length`]}}var Ai={length:ki(e=>e.length,e=>e.map(e=>e._babylonTransformNode)),__array__:{__target__:!0,translation:{type:`Vector3`,get:e=>e._babylonTransformNode?.position,set:(e,t)=>t._babylonTransformNode?.position.copyFrom(e),getTarget:e=>e._babylonTransformNode,getPropertyName:[()=>`position`]},rotation:{type:`Quaternion`,get:e=>e._babylonTransformNode?.rotationQuaternion,set:(e,t)=>t._babylonTransformNode?.rotationQuaternion?.copyFrom(e),getTarget:e=>e._babylonTransformNode,getPropertyName:[()=>`rotationQuaternion`]},scale:{type:`Vector3`,get:e=>e._babylonTransformNode?.scaling,set:(e,t)=>t._babylonTransformNode?.scaling.copyFrom(e),getTarget:e=>e._babylonTransformNode,getPropertyName:[()=>`scaling`]},weights:{__passThroughTarget__:!0,length:ki(e=>{let t=Ri(e);return t?t.mtm.numTargets:e?.mesh===void 0?void 0:0},e=>e?._babylonTransformNode),__array__:{__target__:!0,type:`number`,get:(e,t)=>{let n=Ri(e);if(n&&t!==void 0&&t>=0&&t<n.mtm.numTargets)return zi(n.mtm.getTarget(t).influence)},set:(e,t,n)=>{let r=typeof e==`number`?e:typeof e?.value==`number`?e.value:e,i=Ri(t);if(!(!i||n===void 0||n<0||n>=i.mtm.numTargets))for(let e of i.meshes){let t=e.morphTargetManager?.getTarget(n);t&&(t.influence=r)}},getTarget:(e,t)=>{let n=Ri(e);return n&&t!==void 0&&t>=0&&t<n.mtm.numTargets?n.mtm.getTarget(t):e?._babylonTransformNode},getPropertyName:[()=>`influence`]},type:`number[]`,get:e=>{let t=Ri(e);if(!t)return[];let n=[];for(let e=0;e<t.mtm.numTargets;e++)n.push(zi(t.mtm.getTarget(e).influence));return n},getTarget:e=>e?._babylonTransformNode,getPropertyName:[()=>`influence`]},matrix:{type:`Matrix`,get:e=>L.Compose(e._babylonTransformNode?.scaling,e._babylonTransformNode?.rotationQuaternion,e._babylonTransformNode?.position),getTarget:e=>e._babylonTransformNode,isReadOnly:!0},globalMatrix:{type:`Matrix`,get:e=>{let t=L.Identity(),n=e.parent;for(;n&&n.parent;)n=n.parent;let r=e._babylonTransformNode?.position._isDirty||e._babylonTransformNode?.rotationQuaternion?._isDirty||e._babylonTransformNode?.scaling._isDirty;if(n){let i=n._babylonTransformNode?.computeWorldMatrix(!0).invert();i&&e._babylonTransformNode?.computeWorldMatrix(r)?.multiplyToRef(i,t)}else e._babylonTransformNode&&t.copyFrom(e._babylonTransformNode.computeWorldMatrix(r));return t},getTarget:e=>e._babylonTransformNode,isReadOnly:!0},camera:{type:`string`,get:e=>e.camera===void 0?``:`/cameras/${e.camera}`,getTarget:e=>e,isReadOnly:!0},mesh:{type:`string`,get:e=>e.mesh===void 0?``:`/meshes/${e.mesh}`,getTarget:e=>e,isReadOnly:!0},skin:{type:`string`,get:e=>e.skin===void 0?``:`/skins/${e.skin}`,getTarget:e=>e,isReadOnly:!0},parent:{type:`string`,get:e=>e.parent&&e.parent.index!==void 0?`/nodes/${e.parent.index}`:``,getTarget:e=>e,isReadOnly:!0},children:{length:ki(e=>e?.length??0,e=>e??[]),__array__:{__target__:!0,type:`string`,get:e=>typeof e==`number`?`/nodes/${e}`:``,getTarget:()=>({__nodeIndex:!0}),isReadOnly:!0}},extensions:{EXT_lights_ies:{multiplier:{type:`number`,get:e=>e._babylonTransformNode?.getChildren(e=>e instanceof Ct,!0)[0]?.intensity,getTarget:e=>e._babylonTransformNode?.getChildren(e=>e instanceof Ct,!0)[0],set:(e,t)=>{if(t._babylonTransformNode){let n=t._babylonTransformNode.getChildren(e=>e instanceof Ct,!0)[0];n&&(n.intensity=e)}}},color:{type:`Color3`,get:e=>e._babylonTransformNode?.getChildren(e=>e instanceof Ct,!0)[0]?.diffuse,getTarget:e=>e._babylonTransformNode?.getChildren(e=>e instanceof Ct,!0)[0],set:(e,t)=>{if(t._babylonTransformNode){let n=t._babylonTransformNode.getChildren(e=>e instanceof Ct,!0)[0];n&&(n.diffuse=e)}}}},KHR_node_visibility:{visible:{type:`boolean`,get:e=>e._primitiveBabylonMeshes?e._primitiveBabylonMeshes[0].isVisible:!1,getTarget:()=>void 0,set:(e,t)=>{t._primitiveBabylonMeshes&&t._primitiveBabylonMeshes.forEach(t=>t.isVisible=e)}}}}}},ji={length:ki(e=>e.length,e=>e.map(e=>e._babylonAnimationGroup)),__array__:{__target__:!0,type:`string`,get:e=>e&&typeof e.index==`number`?`/animations/${e.index}`:``,getTarget:e=>e._babylonAnimationGroup,isReadOnly:!0}},Mi={length:ki(e=>e.length,e=>e.map(e=>
vendor: 11,932 bytes, line 4
4e.primitives[0]._instanceData?.babylonSourceMesh)),__array__:{__target__:!0,primitives:{length:ki(e=>e?.length??0,e=>e??[]),__array__:{__target__:!0,material:{type:`string`,get:e=>e.material===void 0?``:`/materials/${e.material}`,getTarget:e=>e,isReadOnly:!0}}},weights:{length:ki(e=>e?.length??0,e=>e??[]),__array__:{__target__:!0,type:`number`,get:e=>e,getTarget:()=>({__weightValue:!0}),isReadOnly:!0}}}},Ni={length:ki(e=>e.length,e=>e.map(e=>e._babylonCamera)),__array__:{__target__:!0,orthographic:{xmag:{componentsCount:2,type:`Vector2`,get:e=>new Xn(e._babylonCamera?.orthoLeft??0,e._babylonCamera?.orthoRight??0),set:(e,t)=>{t._babylonCamera&&(t._babylonCamera.orthoLeft=e.x,t._babylonCamera.orthoRight=e.y)},getTarget:e=>e,getPropertyName:[()=>`orthoLeft`,()=>`orthoRight`]},ymag:{componentsCount:2,type:`Vector2`,get:e=>new Xn(e._babylonCamera?.orthoBottom??0,e._babylonCamera?.orthoTop??0),set:(e,t)=>{t._babylonCamera&&(t._babylonCamera.orthoBottom=e.x,t._babylonCamera.orthoTop=e.y)},getTarget:e=>e,getPropertyName:[()=>`orthoBottom`,()=>`orthoTop`]},zfar:{type:`number`,get:e=>e._babylonCamera?.maxZ,set:(e,t)=>{t._babylonCamera&&(t._babylonCamera.maxZ=e)},getTarget:e=>e,getPropertyName:[()=>`maxZ`]},znear:{type:`number`,get:e=>e._babylonCamera?.minZ,set:(e,t)=>{t._babylonCamera&&(t._babylonCamera.minZ=e)},getTarget:e=>e,getPropertyName:[()=>`minZ`]}},perspective:{aspectRatio:{type:`number`,get:e=>e._babylonCamera?.getEngine().getAspectRatio(e._babylonCamera),getTarget:e=>e,getPropertyName:[()=>`aspectRatio`],isReadOnly:!0},yfov:{type:`number`,get:e=>e._babylonCamera?.fov,set:(e,t)=>{t._babylonCamera&&(t._babylonCamera.fov=e)},getTarget:e=>e,getPropertyName:[()=>`fov`]},zfar:{type:`number`,get:e=>e._babylonCamera?.maxZ,set:(e,t)=>{t._babylonCamera&&(t._babylonCamera.maxZ=e)},getTarget:e=>e,getPropertyName:[()=>`maxZ`]},znear:{type:`number`,get:e=>e._babylonCamera?.minZ,set:(e,t)=>{t._babylonCamera&&(t._babylonCamera.minZ=e)},getTarget:e=>e,getPropertyName:[()=>`minZ`]}}}},Pi={length:ki(e=>e.length,e=>e.map(e=>e._data?.[k.MATERIAL_TriangleFillMode]?.babylonMaterial)),__array__:{__target__:!0,doubleSided:{type:`boolean`,get:(e,t,n)=>!B(e,t,n)?.backFaceCulling,set:(e,t,n,r)=>{let i=B(t,n,r);i&&(i.backFaceCulling=!e)},getTarget:(e,t,n)=>B(e,t,n),getPropertyName:[()=>`backFaceCulling`]},alphaCutoff:{type:`number`,get:(e,t,n)=>B(e,t,n)?.alphaCutOff,set:(e,t,n,r)=>{let i=B(t,n,r);i&&(i.alphaCutOff=e)},getTarget:(e,t,n)=>B(e,t,n),getPropertyName:[()=>`alphaCutOff`]},emissiveFactor:{type:`Color3`,get:(e,t,n)=>B(e,t,n).emissiveColor,set:(e,t,n,r)=>B(t,n,r).emissiveColor.copyFrom(e),getTarget:(e,t,n)=>B(e,t,n),getPropertyName:[()=>`emissiveColor`]},emissiveTexture:{extensions:{KHR_texture_transform:Vi(`emissiveTexture`)}},normalTexture:{scale:{type:`number`,get:(e,t,n)=>Ii(e,n,`bumpTexture`)?.level,set:(e,t,n,r)=>{let i=Ii(t,r,`bumpTexture`);i&&(i.level=e)},getTarget:(e,t,n)=>B(e,t,n),getPropertyName:[()=>`level`]},extensions:{KHR_texture_transform:Vi(`bumpTexture`)}},occlusionTexture:{strength:{type:`number`,get:(e,t,n)=>B(e,t,n).ambientTextureStrength,set:(e,t,n,r)=>{let i=B(t,n,r);i&&(i.ambientTextureStrength=e)},getTarget:(e,t,n)=>B(e,t,n),getPropertyName:[()=>`ambientTextureStrength`]},extensions:{KHR_texture_transform:Vi(`ambientTexture`)}},pbrMetallicRoughness:{baseColorFactor:{type:`Color4`,get:(e,t,n)=>{let r=B(e,t,n);return F.FromColor3(r.albedoColor,r.alpha)},set:(e,t,n,r)=>{let i=B(t,n,r);i.albedoColor.set(e.r,e.g,e.b),i.alpha=e.a},getTarget:(e,t,n)=>B(e,t,n),getPropertyName:[()=>`albedoColor`,()=>`alpha`]},baseColorTexture:{extensions:{KHR_texture_transform:Vi(`albedoTexture`)}},metallicFactor:{type:`number`,get:(e,t,n)=>B(e,t,n).metallic,set:(e,t,n,r)=>{let i=B(t,n,r);i&&(i.metallic=e)},getTarget:(e,t,n)=>B(e,t,n),getPropertyName:[()=>`metallic`]},roughnessFactor:{type:`number`,get:(e,t,n)=>B(e,t,n).roughness,set:(e,t,n,r)=>{let i=B(t,n,r);i&&(i.roughness=e)},getTarget:(e,t,n)=>B(e,t,n),getPropertyName:[()=>`roughness`]},metallicRoughnessTexture:{extensions:{KHR_texture_transform:Vi(`metallicTexture`)}}},extensions:{KHR_materials_anisotropy:{anisotropyStrength:{type:`number`,get:(e,t,n)=>B(e,t,n)?.anisotropy?.intensity,set:(e,t,n,r)=>{let i=B(t,n,r);i&&(i.anisotropy.intensity=e)},getTarget:(e,t,n)=>B(e,t,n),getPropertyName:[()=>`anisotropy.intensity`]},anisotropyRotation:{type:`number`,get:(e,t,n)=>B(e,t,n)?.anisotropy?.angle,set:(e,t,n,r)=>{let i=B(t,n,r);i&&(i.anisotropy.angle=e)},getTarget:(e,t,n)=>B(e,t,n),getPropertyName:[()=>`anisotropy.angle`]},anisotropyTexture:{extensions:{KHR_texture_transform:Vi(`anisotropy`,`texture`)}}},KHR_materials_clearcoat:{clearcoatFactor:{type:`number`,get:(e,t,n)=>B(e,t,n).clearCoat.intensity,set:(e,t,n,r)=>{B(t,n,r).clearCoat.intensity=e},getTarget:(e,t,n)=>B(e,t,n),getPropertyName:[()=>`clearCoat.intensity`]},clearcoatRoughnessFactor:{type:`number`,get:(e,t,n)=>B(e,t,n).clearCoat.roughness,set:(e,t,n,r)=>{B(t,n,r).clearCoat.roughness=e},getTarget:(e,t,n)=>B(e,t,n),getPropertyName:[()=>`clearCoat.roughness`]},clearcoatTexture:{extensions:{KHR_texture_transform:Vi(`clearCoat`,`texture`)}},clearcoatNormalTexture:{scale:{type:`number`,get:(e,t,n)=>B(e,t,n).clearCoat.bumpTexture?.level,getTarget:B,set:(e,t,n,r)=>B(t,n,r).clearCoat.bumpTexture.level=e},extensions:{KHR_texture_transform:Vi(`clearCoat`,`bumpTexture`)}},clearcoatRoughnessTexture:{extensions:{KHR_texture_transform:Vi(`clearCoat`,`textureRoughness`)}}},KHR_materials_dispersion:{dispersion:{type:`number`,get:(e,t,n)=>B(e,t,n).subSurface.dispersion,getTarget:B,set:(e,t,n,r)=>B(t,n,r).subSurface.dispersion=e}},KHR_materials_emissive_strength:{emissiveStrength:{type:`number`,get:(e,t,n)=>B(e,t,n).emissiveIntensity,getTarget:B,set:(e,t,n,r)=>B(t,n,r).emissiveIntensity=e}},KHR_materials_ior:{ior:{type:`number`,get:(e,t,n)=>B(e,t,n).indexOfRefraction,getTarget:B,set:(e,t,n,r)=>B(t,n,r).indexOfRefraction=e}},KHR_materials_iridescence:{iridescenceFactor:{type:`number`,get:(e,t,n)=>B(e,t,n).iridescence.intensity,getTarget:B,set:(e,t,n,r)=>B(t,n,r).iridescence.intensity=e},iridescenceIor:{type:`number`,get:(e,t,n)=>B(e,t,n).iridescence.indexOfRefraction,getTarget:B,set:(e,t,n,r)=>B(t,n,r).iridescence.indexOfRefraction=e},iridescenceTexture:{extensions:{KHR_texture_transform:Vi(`iridescence`,`texture`)}},iridescenceThicknessMaximum:{type:`number`,get:(e,t,n)=>B(e,t,n).iridescence.maximumThickness,getTarget:B,set:(e,t,n,r)=>B(t,n,r).iridescence.maximumThickness=e},iridescenceThicknessMinimum:{type:`number`,get:(e,t,n)=>B(e,t,n).iridescence.minimumThickness,getTarget:B,set:(e,t,n,r)=>B(t,n,r).iridescence.minimumThickness=e},iridescenceThicknessTexture:{extensions:{KHR_texture_transform:Vi(`iridescence`,`thicknessTexture`)}}},KHR_materials_sheen:{sheenColorFactor:{type:`Color3`,get:(e,t,n)=>B(e,t,n).sheen.color,getTarget:B,set:(e,t,n,r)=>B(t,n,r).sheen.color.copyFrom(e)},sheenColorTexture:{extensions:{KHR_texture_transform:Vi(`sheen`,`texture`)}},sheenRoughnessFactor:{type:`number`,get:(e,t,n)=>B(e,t,n).sheen.intensity,getTarget:B,set:(e,t,n,r)=>B(t,n,r).sheen.intensity=e},sheenRoughnessTexture:{extensions:{KHR_texture_transform:Vi(`sheen`,`textureRoughness`)}}},KHR_materials_specular:{specularFactor:{type:`number`,get:(e,t,n)=>B(e,t,n).metallicF0Factor,getTarget:B,set:(e,t,n,r)=>B(t,n,r).metallicF0Factor=e,getPropertyName:[()=>`metallicF0Factor`]},specularColorFactor:{type:`Color3`,get:(e,t,n)=>B(e,t,n).metallicReflectanceColor,getTarget:B,set:(e,t,n,r)=>B(t,n,r).metallicReflectanceColor.copyFrom(e),getPropertyName:[()=>`metallicReflectanceColor`]},specularTexture:{extensions:{KHR_texture_transform:Vi(`metallicReflectanceTexture`)}},specularColorTexture:{extensions:{KHR_texture_transform:Vi(`reflectanceTexture`)}}},KHR_materials_transmission:{transmissionFactor:{type:`number`,get:(e,t,n)=>B(e,t,n).subSurface.refractionIntensity,getTarget:B,set:(e,t,n,r)=>B(t,n,r).subSurface.refractionIntensity=e,getPropertyName:[()=>`subSurface.refractionIntensity`]},transmissionTexture:{extensions:{KHR_texture_transform:Vi(`subSurface`,`refractionIntensityTexture`,{extensionKey:`KHR_materials_transmission`,texturePath:[`transmissionTexture`]})}}},KHR_materials_diffuse_transmission:{diffuseTransmissionFactor:{type:`number`,get:(e,t,n)=>B(e,t,n).subSurface.translucencyIntensity,getTarget:B,set:(e,t,n,r)=>B(t,n,r).subSurface.translucencyIntensity=e},diffuseTransmissionTexture:{extensions:{KHR_texture_transform:Vi(`subSurface`,`translucencyIntensityTexture`,{extensionKey:`KHR_materials_diffuse_transmission`,texturePath:[`diffuseTransmissionTexture`]})}},diffuseTransmissionColorFactor:{type:`Color3`,get:(e,t,n)=>B(e,t,n).subSurface.translucencyColor,getTarget:B,set:(e,t,n,r)=>e&&B(t,n,r).subSurface.translucencyColor?.copyFrom(e)},diffuseTransmissionColorTexture:{extensions:{KHR_texture_transform:Vi(`subSurface`,`translucencyColorTexture`,{extensionKey:`KHR_materials_diffuse_transmission`,texturePath:[`diffuseTransmissionColorTexture`]})}}},KHR_materials_volume:{attenuationColor:{type:`Color3`,get:(e,t,n)=>B(e,t,n).subSurface.tintColor,getTarget:B,set:(e,t,n,r)=>B(t,n,r).subSurface.tintColor.copyFrom(e)},attenuationDistance:{type:`number`,get:(e,t,n)=>B(e,t,n).subSurface.tintColorAtDistance,getTarget:B,set:(e,t,n,r)=>B(t,n,r).subSurface.tintColorAtDistance=e},thicknessFactor:{type:`number`,get:(e,t,n)=>B(e,t,n).subSurface.maximumThickness,getTarget:B,set:(e,t,n,r)=>B(t,n,r).subSurface.maximumThickness=e},thicknessTexture:{extensions:{KHR_texture_transform:Vi(`subSurface`,`thicknessTexture`,{extensionKey:`KHR_materials_volume`,texturePath:[`thicknessTexture`]})}}}}}},Fi={KHR_lights_punctual:{lights:{length:ki(e=>e.length,e=>e.map(e=>e._babylonLight)),__array__:{__target__:!0,color:{type:`Color3`,get:e=>e._babylonLight?.diffuse,set:(e,t)=>t._babylonLight?.diffuse.copyFrom(e),getTarget:e=>e._babylonLight,getPropertyName:[e=>`diffuse`]},intensity:{type:`number`,get:e=>e._babylonLight?.intensity,set:(e,t)=>t._babylonLight?t._babylonLight.intensity=e:void 0,getTarget:e=>e._babylonLight,getPropertyName:[e=>`intensity`]},range:{type:`number`,get:e=>e._babylonLight?.range,set:(e,t)=>t._babylonLight?t._babylonLight.range=e:void 0,getTarget:e=>e._babylonLight,getPropertyName:[e=>`range`]},spot:{innerConeAngle:{type:`number`,get:e=>e._babylonLight?.innerAngle,set:(e,t)=>t._babylonLight?t._babylonLight.innerAngle=e:void 0,getTarget:e=>e._babylonLight,getPropertyName:[e=>`innerConeAngle`]},outerConeAngle:{type:`number`,get:e=>e._babylonLight?.angle,set:(e,t)=>t._babylonLight?t._babylonLight.angle=e:void 0,getTarget:e=>e._babylonLight,getPropertyName:[e=>`outerConeAngle`]}}}}},EXT_lights_area:{lights:{length:ki(e=>e.length,e=>e.map(e=>e._babylonLight)),__array__:{__target__:!0,color:{type:`Color3`,get:e=>e._babylonLight?.diffuse,set:(e,t)=>t._babylonLight?.diffuse.copyFrom(e),getTarget:e=>e._babylonLight,getPropertyName:[e=>`diffuse`]},intensity:{type:`number`,get:e=>e._babylonLight?.intensity,set:(e,t)=>t._babylonLight?t._babylonLight.intensity=e:void 0,getTarget:e=>e._babylonLight,getPropertyName:[e=>`intensity`]},size:{type:`number`,get:e=>e._babylonLight?.height,set:(e,t)=>t._babylonLight?t._babylonLight.height=e:void 0,getTarget:e=>e._babylonLight,getPropertyName:[e=>`size`]},rect:{aspect:{type:`number`,get:e=>e._babylonLight?.width/e._babylonLight?.height,set:(e,t)=>t._babylonLight?t._babylonLight.width=e*t._babylonLight.height:void 0,getTarget:e=>e._babylonLight,getPropertyName:[e=>`aspect`]}}}}},EXT_lights_ies:{lights:{length:ki(e=>e.length,e=>e.map(e=>e._babylonLight))}},EXT_lights_image_based:{lights:{length:ki(e=>e.length,e=>e.map(e=>e._babylonTexture)),__array__:{__target__:!0,intensity:{type:`number`,get:e=>e._babylonTexture?.level,set:(e,t)=>{t._babylonTexture&&(t._babylonTexture.level=e)},getTarget:e=>e._babylonTexture},rotation:{type:`Quaternion`,get:e=>e._babylonTexture&&z.FromRotationMatrix(e._babylonTexture?.getReflectionTextureMatrix()),set
4:(e,t)=>{t._babylonTexture&&(t._babylonTexture.getScene()?.useRightHandedSystem||(e=z.Inverse(e)),L.FromQuaternionToRef(e,t._babylonTexture.getReflectionTextureMatrix()))},getTarget:e=>e._babylonTexture}}}}};function Ii(e,t,n,r){let i=B(e,t);return r?i[n][r]:i[n]}function B(e,t,n){return e._data?.[n?.fillMode??k.MATERIAL_TriangleFillMode]?.babylonMaterial}function Li(e){let t=e?._babylonTransformNode;if(!t)return;if(t.morphTargetManager)return t.morphTargetManager;let n=e._primitiveBabylonMeshes;if(n)for(let e of n){if(e?.morphTargetManager)return e.morphTargetManager;if(e?.sourceMesh?.morphTargetManager)return e.sourceMesh.morphTargetManager}}function Ri(e){let t=e?._babylonTransformNode;if(!t)return;let n=Li(e);if(n&&e._primitiveBabylonMeshes&&e._primitiveBabylonMeshes.length>0)return{mtm:n,meshes:e._primitiveBabylonMeshes};let r=t.getDescendants(!1);for(let e of r){let t=e,n=t.morphTargetManager??t.sourceMesh?.morphTargetManager;if(!n)continue;let r=[],i=t.parent;if(i)for(let e of i.getChildMeshes(!0))(e.morphTargetManager??e.sourceMesh?.morphTargetManager)===n&&r.push(e);return r.length===0&&r.push(t),{mtm:n,meshes:r}}}function zi(e){return Number.isFinite(e)?parseFloat(e.toPrecision(7)):e}function Bi(e,t,n){if(!e)return;let r=e.extensions;if(!r){if(!n)return;r={},e.extensions=r}let i=r[t.extensionKey];if(!i){if(!n)return;i={},r[t.extensionKey]=i}for(let e of t.texturePath){let t=i[e];if(!t){if(!n)return;t={},i[e]=t}i=t}if(!i.extensions){if(!n)return;i.extensions={}}let a=i.extensions.KHR_texture_transform;if(!a){if(!n)return;a={},i.extensions.KHR_texture_transform=a}return a}function Vi(e,t,n){return{offset:{componentsCount:2,type:`Vector2`,get:(r,i,a)=>{let o=Ii(r,a,e,t);if(o)return new Xn(o.uOffset,o.vOffset);if(n){let e=Bi(r,n,!1)?.offset;return new Xn(e?.[0]??0,e?.[1]??0)}return new Xn(0,0)},getTarget:B,set:(r,i,a,o)=>{let s=Ii(i,o,e,t);if(s&&(s.uOffset=r.x,s.vOffset=r.y),n){let e=Bi(i,n,!0);e&&(e.offset=[r.x,r.y])}},getPropertyName:[()=>`${e}${t?`.`+t:``}.uOffset`,()=>`${e}${t?`.`+t:``}.vOffset`]},rotation:{type:`number`,get:(r,i,a)=>{let o=Ii(r,a,e,t);return o?o.wAng:n?Bi(r,n,!1)?.rotation??0:0},getTarget:B,set:(r,i,a,o)=>{let s=Ii(i,o,e,t);if(s&&(s.wAng=r),n){let e=Bi(i,n,!0);e&&(e.rotation=r)}},getPropertyName:[()=>`${e}${t?`.`+t:``}.wAng`]},scale:{componentsCount:2,type:`Vector2`,get:(r,i,a)=>{let o=Ii(r,a,e,t);if(o)return new Xn(o.uScale,o.vScale);if(n){let e=Bi(r,n,!1)?.scale;return new Xn(e?.[0]??1,e?.[1]??1)}return new Xn(1,1)},getTarget:B,set:(r,i,a,o)=>{let s=Ii(i,o,e,t);if(s&&(s.uScale=r.x,s.vScale=r.y),n){let e=Bi(i,n,!0);e&&(e.scale=[r.x,r.y])}},getPropertyName:[()=>`${e}${t?`.`+t:``}.uScale`,()=>`${e}${t?`.`+t:``}.vScale`]}}}var Hi={scene:{__target__:!0,type:`number`,get:e=>e??0,getTarget:()=>({__gltfRoot:!0}),isReadOnly:!0,getPropertyName:[()=>`scene`]},cameras:Ni,nodes:Ai,materials:Pi,extensions:Fi,animations:ji,meshes:Mi,scenes:{length:ki(e=>e.length,e=>e),__array__:{__target__:!0,nodes:{length:ki(e=>e?.length??0,e=>e??[]),__array__:{__target__:!0,type:`string`,get:e=>typeof e==`number`?`/nodes/${e}`:``,getTarget:()=>({__nodeIndex:!0}),isReadOnly:!0}}}},skins:{length:ki(e=>e.length,e=>e.map(e=>e._data?.babylonSkeleton)),__array__:{__target__:!0,joints:{length:ki(e=>e?.length??0,e=>e??[]),__array__:{__target__:!0,type:`string`,get:e=>typeof e==`number`?`/nodes/${e}`:``,getTarget:()=>({__nodeIndex:!0}),isReadOnly:!0}},skeleton:{type:`string`,get:e=>{let t=e.skeleton;return typeof t==`number`?`/nodes/${t}`:``},getTarget:e=>e,isReadOnly:!0}}}};function Ui(e){if(Array.isArray(e))return e.map(e=>Ui(e));if(typeof e==`object`&&e){let t=Object.getPrototypeOf(e);if(t!==Object.prototype&&t!==null)return e;let n={};for(let[t,r]of Object.entries(e))n[t]=Ui(r);return n}return e}function Wi(e,t){if(!t)return new Oi(e,Hi);let n=Ui(Hi);return t(n),new Oi(e,n)}function Gi(e){let t=e.split(`/`).map(e=>e.replace(/{}/g,`__array__`)),n=Hi;for(let e of t)e&&(n=n[e]);if(n&&n.type&&n.get)return n}function V(e,t){let n=e.split(`/`).map(e=>e.replace(/{}/g,`__array__`)),r=Hi;for(let e of n)e&&(r=r[e]);r&&r.type&&r.get&&(r.interpolation=t)}function Ki(e,t,n=Hi){let r=e.split(`/`).map(e=>e.replace(/{}/g,`__array__`)),i=n;
4for(let e of r)if(e){if(!i[e]){if(e===`?`){i.__ignoreObjectTree__=!0;continue}i[e]={},e===`__array__`&&(i[e].__target__=!0)}i=i[e]}Object.assign(i,t)}var qi=e({ArrayItem:()=>H,GLTFFileLoader:()=>a,GLTFLoader:()=>U,LoadBoundingInfoFromPositionAccessor:()=>Xi,RegisterGLTF2Loader:()=>Qi});zn(),_(),wt(),Ne(),Wt(),Un(),pr(),le(),gn(),Ce(),Rn(),Cn(),Xt(),Sr();var Ji=new Lt(()=>ce(()=>import(`./babylon-core-D3-mfcAc.js`).then(e=>(e.ip(),e.rp)),__vite__mapDeps([0,1]))),Yi=new Lt(()=>ce(()=>Promise.resolve().then(()=>$i),void 0)),H=class{static Get(e,t,n){if(!t||n==null||!t[n])throw Error(`${e}: Failed to find index (${n})`);return t[n]}static TryGet(e,t){return!e||t==null||!e[t]?null:e[t]}static Assign(e){if(e)for(let t=0;t<e.length;t++)e[t].index=t}};function Xi(e){if(e.min&&e.max){let t=e.min,n=e.max,r=Pn.Vector3[0].copyFromFloats(t[0],t[1],t[2]),i=Pn.Vector3[1].copyFromFloats(n[0],n[1],n[2]);if(e.normalized&&e.componentType!==5126){let t=1;switch(e.componentType){case 5120:t=127;break;case 5121:t=255;break;case 5122:t=32767;break;case 5123:t=65535}let n=1/t;r.scaleInPlace(n),i.scaleInPlace(n)}return new Gn(r,i)}return null}var U=class e{isMatchingMaterialType(e){if(!e)return!1;let t=Array.from(this._pbrMaterialImpls.values());for(let n of t)if(e instanceof n.materialClass)return!0;return!1}static RegisterExtension(e,t){r(e,!1,t)}static UnregisterExtension(e){return m(e)}get gltf(){if(!this._gltf)throw Error(`glTF JSON is not available`);return this._gltf}get bin(){return this._bin}get parent(){return this._parent}get babylonScene(){if(!this._babylonScene)throw Error(`Scene is not available`);return this._babylonScene}get rootBabylonMesh(){return this._rootBabylonMesh}get rootUrl(){return this._rootUrl}constructor(e){this._completePromises=[],this._assetContainer=null,this._babylonLights=[],this._disableInstancedMesh=0,this._allMaterialsDirtyRequired=!1,this._skipStartAnimationStep=!1,this._extensions=[],this._disposed=!1,this._rootUrl=null,this._fileName=null,this._uniqueRootUrl=null,this._bin=null,this._rootBabylonMesh=null,this._defaultBabylonMaterialData={},this._postSceneLoadActions=[],this._materialAdapterCache=new WeakMap,this._materialAdapters=new Set,this._pbrMaterialImpls=new Map,this._parent=e}_getOrCreateMaterialAdapter(e){let t=this._materialAdapterCache.get(e);if(!t){let n=Array.from(this._pbrMaterialImpls.values());for(let r of n)if(e instanceof r.materialClass){t=new r.adapterClass(e);break}if(!t)throw Error(`Appropriate material adapter class not found`);let r=t;this._materialAdapterCache.set(e,r),this._materialAdapters.add(r)}return t}dispose(){this._disposed||(this._disposed=!0,this._completePromises.length=0,this._extensions.forEach(e=>e.dispose&&e.dispose()),this._extensions.length=0,this._materialAdapters.clear(),this._gltf=null,this._bin=null,this._babylonScene=null,this._rootBabylonMesh=null,this._defaultBabylonMaterialData={},this._postSceneLoadActions.length=0,this._parent.dispose())}async importMeshAsync(e,t,n,r,i,a,o=``){return await Promise.resolve().then(async()=>{this._babylonScene=t,this._assetContainer=n,this._loadData(r);let a=null;if(e){let t={};if(this._gltf.nodes)for(let e of this._gltf.nodes)e.name&&(t[e.name]=e.index);a=(e instanceof Array?e:[e]).map(e=>{let n=t[e];if(n===void 0)throw Error(`Failed to find node '${e}'`);return n})}return await this._loadAsync(i,o,a,()=>({meshes:this._getMeshes(),particleSystems:[],skeletons:this._getSkeletons(),animationGroups:this._getAnimationGroups(),lights:this._babylonLights,transformNodes:this._getTransformNodes(),geometries:this._getGeometries(),spriteManagers:[]}))})}async loadAsync(e,t,n,r,i=``){return this._babylonScene=e,this._loadData(t),await this._loadAsync(n,i,null,()=>void 0)}async _loadAsync(e,n,r,i){return await Promise.resolve().then(async()=>{if(this._rootUrl=e,this._uniqueRootUrl=!e.startsWith(`file:`)&&n?e:`${e}${Ye()}/`,this._fileName=n,this._allMaterialsDirtyRequired=!1,await this._loadExtensionsAsync(),!this.parent.skipMaterials){let e=this.parent.useOpenPBR||this.isExtensionUsed(`KHR_materials_openpbr`),t=!1;this.parent.useOpenPBR?this._gltf.materials?.length&&this._gltf.materials.some(e=>!e.extensions?.KHR_materials_openpbr)&&(t=!0):t=!0;let n=[];
4e&&!this._pbrMaterialImpls.has(`openpbr`)&&n.push(Promise.all([ce(()=>import(`./babylon-core-D3-mfcAc.js`).then(e=>(e.as(),e.os)),__vite__mapDeps([0,1])),ce(()=>Promise.resolve().then(()=>ca),void 0)]).then(([{OpenPBRMaterial:e,RegisterOpenpbrMaterial:t},{OpenPBRMaterialLoadingAdapter:n}])=>{t(),this._pbrMaterialImpls.set(`openpbr`,{materialClass:e,adapterClass:n})})),t&&!this._pbrMaterialImpls.has(`pbr`)&&n.push(Promise.all([ce(()=>import(`./babylon-core-D3-mfcAc.js`).then(e=>(e.Uo(),e.Wo)),__vite__mapDeps([0,1])),ce(()=>Promise.resolve().then(()=>ua),void 0)]).then(([{PBRMaterial:e,RegisterPbrMaterial:t},{PBRMaterialLoadingAdapter:n}])=>{t(),this._pbrMaterialImpls.set(`pbr`,{materialClass:e,adapterClass:n})})),await Promise.all(n)}let a=`${t[t.LOADING]} => ${t[t.READY]}`,o=`${t[t.LOADING]} => ${t[t.COMPLETE]}`;this._parent._startPerformanceCounter(a),this._parent._startPerformanceCounter(o),this._parent._setState(t.LOADING),this._extensionsOnLoading();let s=[],c=this._babylonScene.blockMaterialDirtyMechanism;if(this._babylonScene.blockMaterialDirtyMechanism=!0,!this.parent.loadOnlyMaterials){if(r)s.push(this.loadSceneAsync(`/nodes`,{nodes:r,index:-1}));else if(this._gltf.scene!=null||this._gltf.scenes&&this._gltf.scenes[0]){let e=H.Get(`/scene`,this._gltf.scenes,this._gltf.scene||0);s.push(this.loadSceneAsync(`/scenes/${e.index}`,e))}}if(!this.parent.skipMaterials&&this.parent.loadAllMaterials&&this._gltf.materials)for(let e=0;e<this._gltf.materials.length;++e){let t=this._gltf.materials[e],n=`/materials/`+e,r=Tn.TriangleFillMode;s.push(this._loadMaterialAsync(n,t,null,r,()=>{}))}return this._allMaterialsDirtyRequired?this._babylonScene.blockMaterialDirtyMechanism=c:this._babylonScene._forceBlockMaterialDirtyMechanism(c),this._parent.compileMaterials&&s.push(this._compileMaterialsAsync()),this._parent.compileShadowGenerators&&s.push(this._compileShadowGeneratorsAsync()),await Promise.all(s).then(async()=>{this._rootBabylonMesh&&this._rootBabylonMesh!==this._parent.customRootNode&&this._rootBabylonMesh.setEnabled(!0);for(let e of this._babylonScene.materials){let t=e;t.maxSimultaneousLights!==void 0&&(t.maxSimultaneousLights=Math.max(t.maxSimultaneousLights,this._babylonScene.lights.length))}for(let e of Array.from(this._materialAdapters))this._completePromises.push(e.finalizeAsync(this));return await this._extensionsOnReadyAsync(),this._parent._setState(t.READY),this._skipStartAnimationStep||this._startAnimations(),i()}).then(e=>(this._parent._endPerformanceCounter(a),P.SetImmediate(()=>{this._disposed||Promise.all(this._completePromises).then(()=>{this._parent._endPerformanceCounter(o),this._parent._setState(t.COMPLETE),this._parent.onCompleteObservable.notifyObservers(void 0),this._parent.onCompleteObservable.clear(),this.dispose()},e=>{this._parent.onErrorObservable.notifyObservers(e),this._parent.onErrorObservable.clear(),this.dispose()})}),e))}).catch(e=>{throw this._disposed||(this._parent.onErrorObservable.notifyObservers(e),this._parent.onErrorObservable.clear(),this.dispose()),e})}_loadData(e){if(this._gltf=e.json,this._setupData(),e.bin){let t=this._gltf.buffers;if(t&&t[0]&&!t[0].uri){let n=t[0];(n.byteLength<e.bin.byteLength-3||n.byteLength>e.bin.byteLength)&&A.Warn(`Binary buffer length (${n.byteLength}) from JSON does not match chunk length (${e.bin.byteLength})`),this._bin=e.bin}else A.Warn(`Unexpected BIN chunk`)}}_setupData(){if(H.Assign(this._gltf.accessors),H.Assign(this._gltf.animations),H.Assign(this._gltf.buffers),H.Assign(this._gltf.bufferViews),H.Assign(this._gltf.cameras),H.Assign(this._gltf.images),H.Assign(this._gltf.materials),H.Assign(this._gltf.meshes),H.Assign(this._gltf.nodes),H.Assign(this._gltf.samplers),H.Assign(this._gltf.scenes),H.Assign(this._gltf.skins),H.Assign(this._gltf.textures),this._gltf.nodes){let e={};for(let t of this._gltf.nodes)if(t.children)for(let n of t.children)e[n]=t.index;let t=this._createRootNode();for(let n of this._gltf.nodes){let r=e[n.index];n.parent=r===void 0?t:this._gltf.nodes[r]}}}async _loadExtensionsAsync(){let e=[];
4if(d.forEach((t,n)=>{this.parent.extensionOptions[n]?.enabled===!1?t.isGLTFExtension&&this.isExtensionUsed(n)&&A.Warn(`Extension ${n} is used but has been explicitly disabled.`):(!t.isGLTFExtension||this.isExtensionUsed(n))&&e.push((async()=>{let e=await t.factory(this);return e.name!==n&&A.Warn(`The name of the glTF loader extension instance does not match the registered name: ${e.name} !== ${n}`),this._parent.onExtensionLoadedObservable.notifyObservers(e),e})())}),this._extensions.push(...await Promise.all(e)),this._extensions.sort((e,t)=>(e.order||Number.MAX_VALUE)-(t.order||Number.MAX_VALUE)),this._parent.onExtensionLoadedObservable.clear(),this._gltf.extensionsRequired){for(let e of this._gltf.extensionsRequired)if(!this._extensions.some(t=>t.name===e&&t.enabled))throw this.parent.extensionOptions[e]?.enabled===!1?Error(`Required extension ${e} is disabled`):Error(`Required extension ${e} is not available`)}}_createRootNode(){if(this._parent.customRootNode!==void 0)return this._rootBabylonMesh=this._parent.customRootNode,{_babylonTransformNode:this._rootBabylonMesh===null?void 0:this._rootBabylonMesh,index:-1};this._babylonScene._blockEntityCollection=!!this._assetContainer;let t=new At(`__root__`,this._babylonScene);this._rootBabylonMesh=t,this._rootBabylonMesh._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,this._rootBabylonMesh.setEnabled(!1);let r={_babylonTransformNode:this._rootBabylonMesh,index:-1};switch(this._parent.coordinateSystemMode){case n.AUTO:this._babylonScene.useRightHandedSystem||(r.rotation=[0,1,0,0],r.scale=[1,1,-1],e._LoadTransform(r,this._rootBabylonMesh));break;case n.FORCE_RIGHT_HANDED:this._babylonScene.useRightHandedSystem=!0;break;default:throw Error(`Invalid coordinate system mode (${this._parent.coordinateSystemMode})`)}return this._parent.onMeshLoadedObservable.notifyObservers(t),r}loadSceneAsync(e,t){let n=this._extensionsLoadSceneAsync(e,t);if(n)return n;let r=[];if(this.logOpen(`${e} ${t.name||``}`),t.nodes)for(let n of t.nodes){let t=H.Get(`${e}/nodes/${n}`,this._gltf.nodes,n);r.push(this.loadNodeAsync(`/nodes/${t.index}`,t,e=>{e.parent=this._rootBabylonMesh}))}for(let e of this._postSceneLoadActions)e();return r.push(this._loadAnimationsAsync()),this.logClose(),Promise.all(r).then(()=>{})}_forEachPrimitive(e,t){if(e._primitiveBabylonMeshes)for(let n of e._primitiveBabylonMeshes)t(n)}_getGeometries(){let e=[],t=this._gltf.nodes;if(t)for(let n of t)this._forEachPrimitive(n,t=>{let n=t.geometry;n&&e.indexOf(n)===-1&&e.push(n)});return e}_getMeshes(){let e=[];this._rootBabylonMesh instanceof ve&&e.push(this._rootBabylonMesh);let t=this._gltf.nodes;if(t)for(let n of t)this._forEachPrimitive(n,t=>{e.push(t)});return e}_getTransformNodes(){let e=[],t=this._gltf.nodes;if(t)for(let n of t)n._babylonTransformNode&&n._babylonTransformNode.getClassName()===`TransformNode`&&e.push(n._babylonTransformNode),n._babylonTransformNodeForSkin&&e.push(n._babylonTransformNodeForSkin);return e}_getSkeletons(){let e=[],t=this._gltf.skins;if(t)for(let n of t)n._data&&e.push(n._data.babylonSkeleton);return e}_getAnimationGroups(){let e=[],t=this._gltf.animations;if(t)for(let n of t)n._babylonAnimationGroup&&e.push(n._babylonAnimationGroup);return e}_startAnimations(){switch(this._parent.animationStartMode){case p.NONE:break;case p.FIRST:{let e=this._getAnimationGroups();e.length!==0&&e[0].start(!0);break}case p.ALL:{let e=this._getAnimationGroups();for(let t of e)t.start(!0);break}default:A.Error(`Invalid animation start mode (${this._parent.animationStartMode})`);return}}loadNodeAsync(t,n,r=()=>{}){let i=this._extensionsLoadNodeAsync(t,n,r);if(i)return i;if(n._babylonTransformNode)throw Error(`${t}: Invalid recursive node hierarchy`);let a=[];this.logOpen(`${t} ${n.name||``}`);let o=i=>{if(e.AddPointerMetadata(i,t),e._LoadTransform(n,i),n.camera!=null){let e=H.Get(`${t}/camera`,this._gltf.cameras,n.camera);a.push(this.loadCameraAsync(`/cameras/${e.index}`,e,e=>{e.parent=i,this._babylonScene.useRightHandedSystem||(i.scaling.x=-1)}))}if(n.children)for(let e of n.children){let n=H.Get(`${t}/children/${e}`,this._gltf.nodes,e);a.push(this.loadNodeAsync(`/nodes/${n.index}`,n,e=>{e.parent=i}))}r(i)},s=n.mesh!=null,c=this._parent.loadSkins&&n.skin!=null;if(!s||c){let e=n.name||`node${n.index}`;this._babylonScene._blockEntityCollection=!!this._assetContainer;let t=new Ge(e,this._babylonScene);t._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,n.mesh==null?n._babylonTransformNode=t:n._babylonTransformNodeForSkin=t,o(t)}if(s){if(c){let e=H.Get(`${t}/mesh`,this._gltf.meshes,n.mesh);a.push(this._loadMeshAsync(`/meshes/${e.index}`,n,e,e=>{let r=n._babylonTransformNodeForSkin;e.metadata=ze(r.metadata,e.metadata||{});let i=H.Get(`${t}/skin`,this._gltf.skins,n.skin);a.push(this._loadSkinAsync(`/skins/${i.index}`,n,i,t=>
4{this._forEachPrimitive(n,e=>{e.skeleton=t}),this._postSceneLoadActions.push(()=>{if(i.skeleton!=null){let t=H.Get(`/skins/${i.index}/skeleton`,this._gltf.nodes,i.skeleton).parent;e.parent=n.index===t.index?r.parent:t._babylonTransformNode}else e.parent=this._rootBabylonMesh;this._parent.onSkinLoadedObservable.notifyObservers({node:r,skinnedNode:e})})}))}))}else{let e=H.Get(`${t}/mesh`,this._gltf.meshes,n.mesh);a.push(this._loadMeshAsync(`/meshes/${e.index}`,n,e,o))}}return this.logClose(),Promise.all(a).then(()=>(this._forEachPrimitive(n,e=>{let t=e;!t.isAnInstance&&t.geometry&&t.geometry.useBoundingInfoFromGeometry?e._updateBoundingInfo():e.refreshBoundingInfo(!0,!0)}),n._babylonTransformNode))}_loadMeshAsync(e,t,n,r){let i=n.primitives;if(!i||!i.length)throw Error(`${e}: Primitives are missing`);i[0].index??H.Assign(i);let a=[];this.logOpen(`${e} ${n.name||``}`);let o=t.name||`node${t.index}`;if(i.length===1){let r=n.primitives[0];a.push(this._loadMeshPrimitiveAsync(`${e}/primitives/${r.index}`,o,t,n,r,e=>{t._babylonTransformNode=e,t._primitiveBabylonMeshes=[e]}))}else{this._babylonScene._blockEntityCollection=!!this._assetContainer,t._babylonTransformNode=new Ge(o,this._babylonScene),t._babylonTransformNode._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,t._primitiveBabylonMeshes=[];for(let r of i)a.push(this._loadMeshPrimitiveAsync(`${e}/primitives/${r.index}`,`${o}_primitive${r.index}`,t,n,r,e=>{e.parent=t._babylonTransformNode,t._primitiveBabylonMeshes.push(e)}))}return r(t._babylonTransformNode),this.logClose(),Promise.all(a).then(()=>t._babylonTransformNode)}_loadMeshPrimitiveAsync(t,n,r,i,a,o){let s=this._extensionsLoadMeshPrimitiveAsync(t,n,r,i,a,o);if(s)return s;this.logOpen(`${t}`);let c=this._disableInstancedMesh===0&&this._parent.createInstances&&r.skin==null&&!i.primitives[0].targets,l,u;if(c&&a._instanceData)this._babylonScene._blockEntityCollection=!!this._assetContainer,l=a._instanceData.babylonSourceMesh.createInstance(n),l._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,u=a._instanceData.promise;else{let o=[];this._babylonScene._blockEntityCollection=!!this._assetContainer;let s=new At(n,this._babylonScene);if(s._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,s.sideOrientation=this._babylonScene.useRightHandedSystem?Tn.CounterClockWiseSideOrientation:Tn.ClockWiseSideOrientation,this._createMorphTargets(t,r,i,a,s),o.push(this._loadVertexDataAsync(t,a,s).then(async e=>await this._loadMorphTargetsAsync(t,a,s,e).then(()=>{this._disposed||(this._babylonScene._blockEntityCollection=!!this._assetContainer,e.applyToMesh(s),e._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1)}))),!this.parent.skipMaterials){let n=e._GetDrawMode(t,a.mode);if(a.material==null){let e=this._defaultBabylonMaterialData[n];e||(e=this._createDefaultMaterial(`__GLTFLoader._default`,n,this._getDefaultImpl()),this._parent.onMaterialLoadedObservable.notifyObservers(e),this._defaultBabylonMaterialData[n]=e),s.material=e}else{let e=H.Get(`${t}/material`,this._gltf.materials,a.material);o.push(this._loadMaterialAsync(`/materials/${e.index}`,e,s,n,e=>{s.material=e}))}}u=Promise.all(o),c&&(a._instanceData={babylonSourceMesh:s,promise:u}),l=s}return e.AddPointerMetadata(l,t),this._parent.onMeshLoadedObservable.notifyObservers(l),o(l),this.logClose(),u.then(()=>l)}_loadVertexDataAsync(e,t,n){let r=this._extensionsLoadVertexDataAsync(e,t,n);if(r)return r;let i=t.attributes;if(!i)throw Error(`${e}: Attributes are missing`);let a=[],o=new C(n.name,this._babylonScene);if(t.indices==null)n.isUnIndexed=!0;else{let n=H.Get(`${e}/indices`,this._gltf.accessors,t.indices);a.push(this._loadIndicesAccessorAsync(`/accessors/${n.index}`,n).then(e=>{o.setIndices(e)}))}let s=(t,r,s)=>{if(i[t]==null)return;n._delayInfo=n._delayInfo||[],n._delayInfo.indexOf(r)===-1&&n._delayInfo.push(r);let c=H.Get(`${e}/attributes/${t}`,this._gltf.accessors,i[t]);a.push(this._loadVertexAccessorAsync(`/accessors/${c.index}`,c,r).then(e=>{if(e.getKind()===j.PositionKind&&!this.parent.alwaysComputeBoundingBox&&!n.skeleton){let e=Xi(c);e&&(o._boundingInfo=e,o.useBoundingInfoFromGeometry=!0)}o.setVerticesBuffer(e,c.count)}
4)),r==j.MatricesIndicesExtraKind&&(n.numBoneInfluencers=8),s&&s(c)};return s(`POSITION`,j.PositionKind),s(`NORMAL`,j.NormalKind),s(`TANGENT`,j.TangentKind),s(`TEXCOORD_0`,j.UVKind),s(`TEXCOORD_1`,j.UV2Kind),s(`TEXCOORD_2`,j.UV3Kind),s(`TEXCOORD_3`,j.UV4Kind),s(`TEXCOORD_4`,j.UV5Kind),s(`TEXCOORD_5`,j.UV6Kind),s(`JOINTS_0`,j.MatricesIndicesKind),s(`WEIGHTS_0`,j.MatricesWeightsKind),s(`JOINTS_1`,j.MatricesIndicesExtraKind),s(`WEIGHTS_1`,j.MatricesWeightsExtraKind),s(`COLOR_0`,j.ColorKind,e=>{e.type===`VEC4`&&(n.hasVertexAlpha=!0)}),Promise.all(a).then(()=>o)}_createMorphTargets(e,t,n,r,i){if(!r.targets||!this._parent.loadMorphTargets)return;if(t._numMorphTargets==null)t._numMorphTargets=r.targets.length;else if(r.targets.length!==t._numMorphTargets)throw Error(`${e}: Primitives do not have the same number of targets`);let a=n.extras?n.extras.targetNames:null;this._babylonScene._blockEntityCollection=!!this._assetContainer,i.morphTargetManager=new qn(this._babylonScene),i.morphTargetManager._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,i.morphTargetManager.areUpdatesFrozen=!0;for(let e=0;e<r.targets.length;e++){let r=t.weights?t.weights[e]:n.weights?n.weights[e]:0,o=a?a[e]:`morphTarget${e}`;i.morphTargetManager.addTarget(new kt(o,r,i.getScene()))}}_loadMorphTargetsAsync(e,t,n,r){if(!t.targets||!this._parent.loadMorphTargets)return Promise.resolve();let i=[],a=n.morphTargetManager;for(let n=0;n<a.numTargets;n++){let o=a.getTarget(n);i.push(this._loadMorphTargetVertexDataAsync(`${e}/targets/${n}`,r,t.targets[n],o))}return Promise.all(i).then(()=>{a.areUpdatesFrozen=!1,this._parent.useMaxMorphTargetInfluencers&&(a.isUsingTextureForTargets||a.numTargets<=qn.MaxActiveMorphTargetsInVertexAttributeMode)&&(a.optimizeInfluencers=!1,a.numMaxInfluencers=a.numTargets)})}async _loadMorphTargetVertexDataAsync(e,t,n,r){let i=[],a=(r,a,o)=>
4{if(n[r]==null)return;let s=t.getVertexBuffer(a);if(!s)return;let c=H.Get(`${e}/${r}`,this._gltf.accessors,n[r]);i.push(this._loadFloatAccessorAsync(`/accessors/${c.index}`,c).then(e=>{o(s,e)}))};return a(`POSITION`,j.PositionKind,(e,t)=>{let n=new Float32Array(t.length);e.forEach(t.length,(e,r)=>{n[r]=t[r]+e}),r.setPositions(n)}),a(`NORMAL`,j.NormalKind,(e,t)=>{let n=new Float32Array(t.length);e.forEach(n.length,(e,r)=>{n[r]=t[r]+e}),r.setNormals(n)}),a(`TANGENT`,j.TangentKind,(e,t)=>{let n=new Float32Array(t.length/3*4),i=0;e.forEach(t.length/3*4,(e,r)=>{(r+1)%4!=0&&(n[i]=t[i]+e,i++)}),r.setTangents(n)}),a(`TEXCOORD_0`,j.UVKind,(e,t)=>{let n=new Float32Array(t.length);e.forEach(t.length,(e,r)=>{n[r]=t[r]+e}),r.setUVs(n)}),a(`TEXCOORD_1`,j.UV2Kind,(e,t)=>{let n=new Float32Array(t.length);e.forEach(t.length,(e,r)=>{n[r]=t[r]+e}),r.setUV2s(n)}),a(`COLOR_0`,j.ColorKind,(t,n)=>{let i=null,a=t.getSize();if(a===3){i=new Float32Array(n.length/3*4),t.forEach(n.length,(e,t)=>{let r=Math.floor(t/3),a=t%3;i[4*r+a]=n[3*r+a]+e});for(let e=0;e<n.length/3;++e)i[4*e+3]=1}else if(a===4)i=new Float32Array(n.length),t.forEach(n.length,(e,t)=>{i[t]=n[t]+e});else throw Error(`${e}: Invalid number of components (${a}) for COLOR_0 attribute`);r.setColors(i)}),await Promise.all(i).then(()=>{})}static _LoadTransform(e,t){if(e.skin!=null)return;let n=R.Zero(),r=z.Identity(),i=R.One();e.matrix?L.FromArray(e.matrix).decompose(i,r,n):(e.translation&&(n=R.FromArray(e.translation)),e.rotation&&(r=z.FromArray(e.rotation)),e.scale&&(i=R.FromArray(e.scale))),t.position=n,t.rotationQuaternion=r,t.scaling=i}_loadSkinAsync(e,t,n,r){if(!this._parent.loadSkins)return Promise.resolve();let i=this._extensionsLoadSkinAsync(e,t,n);if(i)return i;if(n._data)return r(n._data.babylonSkeleton),n._data.promise;let a=`skeleton${n.index}`;this._babylonScene._blockEntityCollection=!!this._assetContainer;let o=new Yt(n.name||a,a,this._babylonScene);o._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,this._loadBones(e,n,o);let s=this._loadSkinInverseBindMatricesDataAsync(e,n).then(e=>{this._updateBoneMatrices(o,e)});return n._data={babylonSkeleton:o,promise:s},r(o),s}_loadBones(e,t,n){if(t.skeleton==null||this._parent.alwaysComputeSkeletonRootNode){let n=this._findSkeletonRootNode(`${e}/joints`,t.joints);if(n){if(t.skeleton===void 0)t.skeleton=n.index;else{let r=(e,t)=>{for(;t.parent;t=t.parent)if(t.parent===e)return!0;return!1},i=H.Get(`${e}/skeleton`,this._gltf.nodes,t.skeleton);i!==n&&!r(i,n)&&(A.Warn(`${e}/skeleton: Overriding with nearest common ancestor as skeleton node is not a common root`),t.skeleton=n.index)}}else A.Warn(`${e}: Failed to find common root`)}let r={};for(let i of t.joints){let a=H.Get(`${e}/joints/${i}`,this._gltf.nodes,i);this._loadBone(a,t,n,r)}}_findSkeletonRootNode(e,t){if(t.length===0)return null;let n={};for(let r of t){let t=[],i=H.Get(`${e}/${r}`,this._gltf.nodes,r);for(;i.index!==-1;)t.unshift(i),i=i.parent;n[r]=t}let r=null;for(let e=0;;++e){let i=n[t[0]];if(e>=i.length)return r;let a=i[e];for(let o=1;o<t.length;++o)if(i=n[t[o]],e>=i.length||a!==i[e])return r;r=a}}_loadBone(e,t,n,r){e._isJoint=!0;let i=r[e.index];if(i)return i;let a=null;e.index!==t.skeleton&&(e.parent&&e.parent.index!==-1?a=this._loadBone(e.parent,t,n,r):t.skeleton!==void 0&&A.Warn(`/skins/${t.index}/skeleton: Skeleton node is not a common root`));let o=t.joints.indexOf(e.index);return i=new mr(e.name||`joint${e.index}`,n,a,this._getNodeMatrix(e),null,null,o),r[e.index]=i,this._postSceneLoadActions.push(()=>{i.linkTransformNode(e._babylonTransformNode)}),i}_loadSkinInverseBindMatricesDataAsync(e,t){if(t.inverseBindMatrices==null)return Promise.resolve(null);let n=H.Get(`${e}/inverseBindMatrices`,this._gltf.accessors,t.inverseBindMatrices);return this._loadFloatAccessorAsync(`/accessors/${n.index}`,n)}_updateBoneMatrices(e,t){for(let n of e.bones){let e=L.Identity(),r=n._index;t&&r!==-1&&(L.FromArrayToRef(t,r*16,e),e.invertToRef(e));let i=n.getParent();i&&e.multiplyToRef(i.getAbsoluteInverseBindMatrix(),e),n.updateMatrix(e,!1,!1),n._updateAbsoluteBindMatrices(void 0,!1)}}_getNodeMatrix(e){return e.matrix?L.FromArray(e.matrix):L.Compose(e.scale?R.FromArray(e.scale):R.One(),e.rotation?z.FromArray(e.rotation):z.Identity(),e.translation?R.FromArray(e.translation):R.Zero())}loadCameraAsync(t,n,r=()=>{}){let i=this._extensionsLoadCameraAsync(t,n,r);if(i)return i;let a=[];this.logOpen(`${t} ${n.name||``}`),this._babylonScene._blockEntityCollection=!!this._assetContainer;let o=new fr(n.name||`camera${n.index}`,R.Zero(),this._babylonScene,!1);switch(o._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,n._babylonCamera=o,o.setTarget(new R(0,0,-1)),n.type){case`perspective`:{let e=n.perspective;if(!e)throw Error(`${t}: Camera perspective properties are missing`);o.fov=e.yfov,o.minZ=e.znear,o.maxZ=e.zfar||0;break}case`orthographic`:if(!n.orthographic)throw Error(`${t}: Camera orthographic properties are missing`);o.mode=De.ORTHOGRAPHIC_CAMERA,o.orthoLeft=-n.orthographic.xmag,o.orthoRight=n.orthographic.xmag,o.orthoBottom=-n.orthographic.ymag,o.orthoTop=n.orthographic.ymag,o.minZ=n.orthographic.znear,o.maxZ=n.orthographic.zfar;break;default:throw Error(`${t}: Invalid camera type (${n.type})`)}return e.AddPointerMetadata(o,t),this._parent.onCameraLoadedObservable.notifyObservers(o),r(o),this.logClose(),Promise.all(a).then(()=>o)}_loadAnimationsAsync(){this._parent._startPerformanceCounter(`Load animations`);let e=this._gltf.animations;if(!e)return Promise.resolve();let t=[];for(let n=0;n<e.length;n++){let r=e[n];t.push(this.loadAnimationAsync(`/animations/${r.index}`,r).then(e=>{e.targetedAnimations.length===0&&e.dispose()}))}return Promise.all(t).then(()=>{this._parent._endPerformanceCounter(`Load animations`)})}loadAnimationAsync(e,t){return this._parent._startPerformanceCounter(`Load animation`),this._extensionsLoadAnimationAsync(e,t)||Ji.value.then(({AnimationGroup:n})=>{this._babylonScene._blockEntityCollection=!!this._assetContainer;let r=new n(t.name||`animation${t.index}`,this._babylonScene);r._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,t._babylonAnimationGroup=r;let i=[];H.Assign(t.channels),H.Assign(t.samplers);for(let n of t.channels)i.push(this._loadAnimationChannelAsync(`${e}/channels/${n.index}`,e,t,n,(e,t)=>{e.animations=e.animations||[],e.animations.push(t),r.addTargetedAnimation(t,e)}));return this._parent._endPerformanceCounter(`Load animation`),Promise.all(i).then(()=>(r.normalize(0),r))})}_loadAnimationChannelAsync(e,t,n,r,i){let a=this._extensionsLoadAnimationChannelAsync(e,t,n,r,i);if(a)return a;
4if(r.target.node==null)return Promise.resolve();let o=H.Get(`${e}/target/node`,this._gltf.nodes,r.target.node),s=r.target.path,c=s===`weights`;return c&&!o._numMorphTargets||!c&&!o._babylonTransformNode||!this._parent.loadNodeAnimations&&!c&&!o._isJoint?Promise.resolve():Yi.value.then(({RegisterGLTFLoaderAnimation:a})=>{a();let c;switch(s){case`translation`:c=Gi(`/nodes/{}/translation`)?.interpolation;break;case`rotation`:c=Gi(`/nodes/{}/rotation`)?.interpolation;break;case`scale`:c=Gi(`/nodes/{}/scale`)?.interpolation;break;case`weights`:c=Gi(`/nodes/{}/weights`)?.interpolation;break;default:throw Error(`${e}/target/path: Invalid value (${r.target.path})`)}if(!c)throw Error(`${e}/target/path: Could not find interpolation properties for target path (${r.target.path})`);let l={object:o,info:c};return this._loadAnimationChannelFromTargetInfoAsync(e,t,n,r,l,i)})}_loadAnimationChannelFromTargetInfoAsync(e,t,n,r,i,a){let o=this.parent.targetFps,s=1/o,c=H.Get(`${e}/sampler`,n.samplers,r.sampler);return this._loadAnimationSamplerAsync(`${t}/samplers/${r.sampler}`,c).then(e=>{let t=0,c=i.object,l=i.info;for(let i of l){let l=i.getStride(c),u=e.input,d=e.output,f=Array(u.length),p=0;switch(e.interpolation){case`STEP`:for(let e=0;e<u.length;e++){let t=i.getValue(c,d,p,1);p+=l,f[e]={frame:u[e]*o,value:t,interpolation:1}}break;case`CUBICSPLINE`:for(let e=0;e<u.length;e++){let t=i.getValue(c,d,p,s);p+=l;let n=i.getValue(c,d,p,1);p+=l;let r=i.getValue(c,d,p,s);p+=l,f[e]={frame:u[e]*o,inTangent:t,value:n,outTangent:r}}break;case`LINEAR`:for(let e=0;e<u.length;e++){let t=i.getValue(c,d,p,1);p+=l,f[e]={frame:u[e]*o,value:t}}}if(p>0){let e=`${n.name||`animation${n.index}`}_channel${r.index}_${t}`,s=i.buildAnimations(c,e,o,f);for(let e of s)t++,a(e.babylonAnimatable,e.babylonAnimation)}}})}_loadAnimationSamplerAsync(e,t){if(t._data)return t._data;let n=t.interpolation||`LINEAR`;switch(n){case`STEP`:case`LINEAR`:case`CUBICSPLINE`:break;default:throw Error(`${e}/interpolation: Invalid value (${t.interpolation})`)}let r=H.Get(`${e}/input`,this._gltf.accessors,t.input),i=H.Get(`${e}/output`,this._gltf.accessors,t.output);return t._data=Promise.all([this._loadFloatAccessorAsync(`/accessors/${r.index}`,r),this._loadFloatAccessorAsync(`/accessors/${i.index}`,i)]).then(([e,t])=>({input:e,interpolation:n,output:t})),t._data}loadBufferAsync(e,t,n,r){let i=this._extensionsLoadBufferAsync(e,t,n,r);if(i)return i;if(!t._data){if(t.uri)t._data=this.loadUriAsync(`${e}/uri`,t,t.uri);else{if(!this._bin)throw Error(`${e}: Uri is missing or the binary glTF is missing its binary chunk`);t._data=this._bin.readAsync(0,t.byteLength)}}return t._data.then(t=>{try{return new Uint8Array(t.buffer,t.byteOffset+n,r)}catch(t){throw Error(`${e}: ${t.message}`,{cause:t})}})}loadBufferViewAsync(e,t){let n=this._extensionsLoadBufferViewAsync(e,t);if(n)return n;if(t._data)return t._data;let r=H.Get(`${e}/buffer`,this._gltf.buffers,t.buffer);return t._data=this.loadBufferAsync(`/buffers/${r.index}`,r,t.byteOffset||0,t.byteLength),t._data}_loadAccessorAsync(t,n,r){if(n._data)return n._data;let i=e._GetNumComponents(t,n.type),a=i*Ve(n.componentType),o=i*n.count;if(n.bufferView==null)n._data=Promise.resolve(new r(o));else{let s=H.Get(`${t}/bufferView`,this._gltf.bufferViews,n.bufferView);n._data=this.loadBufferViewAsync(`/bufferViews/${s.index}`,s).then(c=>{if(n.componentType===5126&&!n.normalized&&(!s.byteStride||s.byteStride===a))return e._GetTypedArray(t,n.componentType,c,n.byteOffset,o);{let e=new r(o);return Fe(c,n.byteOffset||0,s.byteStride||a,i,n.componentType,e.length,n.normalized||!1,(t,n)=>{e[n]=t}),e}})}if(n.sparse){let o=n.sparse;n._data=n._data.then(s=>{let c=s,l=H.Get(`${t}/sparse/indices/bufferView`,this._gltf.bufferViews,o.indices.bufferView),u=H.Get(`${t}/sparse/values/bufferView`,this._gltf.bufferViews,o.values.bufferView);return Promise.all([this.loadBufferViewAsync(`/bufferViews/${l.index}`,l),this.loadBufferViewAsync(`/bufferViews/${u.index}`,u)]).then(([s,l])=>{let u=e._GetTypedArray(`${t}/sparse/indices`,o.indices.componentType,s,o.indices.byteOffset,o.count),d=i*o.count,f;if(n.componentType===5126&&!n.normalized)f=e._GetTypedArray(`${t}/sparse/values`,n.componentType,l,o.values.byteOffset,d);else{let s=e._GetTypedArray(`${t}/sparse/values`,n.componentType,l,o.values.byteOffset,d);f=new r(d),Fe(s,0,a,i,n.componentType,f.length,n.normalized||!1,(e,t)=>{f[t]=e})}let p=0;for(let e=0;e<u.length;e++){let t=u[e]*i;for(let e=0;e<i;e++)c[t++]=f[p++]}return c})})}return n._data}_loadFloatAccessorAsync(e,t){return this._loadAccessorAsync(e,t,Float32Array)}_loadIndicesAccessorAsync(t,n){if(n.type!==`SCALAR`)throw Error(`${t}/type: Invalid value ${n.type}`);if(n.componentType!==5121&&n.componentType!==5123&&n.componentType!==5125)throw Error(`${t}/componentType: Invalid value ${n.componentType}`);if(n._data)return n._data;if(n.sparse){let r=e._GetTypedArrayConstructor(`${t}/componentType`,n.componentType);n._data=this._loadAccessorAsync(t,n,r)}else{let r=H.Get(`${t}/bufferView`,this._gltf.bufferViews,n.bufferView);n._data=this.loadBufferViewAsync(`/bufferViews/${r.index}`,r).then(r=>e._GetTypedArray(t,n.componentType,r,n.byteOffset,n.count))}return n._data}_loadVertexBufferViewAsync(e){if(e._babylonBuffer)return e._babylonBuffer;let t=this._babylonScene.getEngine();return e._babylonBuffer=this.loadBufferViewAsync(`/bufferViews/${e.index}`,e).then(e=>new vn(t,e,!1)),e._babylonBuffer}_loadVertexAccessorAsync(t,n,r){if(n._babylonVertexBuffer?.[r])return n._babylonVertexBuffer[r];n._babylonVertexBuffer||={};let i=this._babylonScene.getEngine();if(n.sparse||n.bufferView==null)n._babylonVertexBuffer[r]=this._loadFloatAccessorAsync(t,n).then(e=>new j(i,e,r,!1));else{let a=H.Get(`${t}/bufferView`,this._gltf.bufferViews,n.bufferView);n._babylonVertexBuffer[r]=this._loadVertexBufferViewAsync(a).then(o=>
4{let s=e._GetNumComponents(t,n.type);return new j(i,o,r,!1,void 0,a.byteStride,void 0,n.byteOffset,s,n.componentType,n.normalized,!0,void 0,!0)})}return n._babylonVertexBuffer[r]}_loadMaterialMetallicRoughnessPropertiesAsync(e,t,n){let r=[],i=this._getOrCreateMaterialAdapter(n);return t&&(t.baseColorFactor?(i.baseColor=N.FromArray(t.baseColorFactor),i.geometryOpacity=t.baseColorFactor[3]):i.baseColor=N.White(),i.baseMetalness=t.metallicFactor==null?1:t.metallicFactor,i.specularRoughness=t.roughnessFactor==null?1:t.roughnessFactor,t.baseColorTexture&&r.push(this.loadTextureInfoAsync(`${e}/baseColorTexture`,t.baseColorTexture,e=>{e.name=`${n.name} (Base Color)`,i.baseColorTexture=e})),t.metallicRoughnessTexture&&(t.metallicRoughnessTexture.nonColorData=!0,r.push(this.loadTextureInfoAsync(`${e}/metallicRoughnessTexture`,t.metallicRoughnessTexture,e=>{e.name=`${n.name} (Metallic Roughness)`,i.baseMetalnessTexture=e,i.specularRoughnessTexture=e})),i.useRoughnessFromMetallicTextureGreen=!0,i.useMetallicFromMetallicTextureBlue=!0)),Promise.all(r).then(()=>{})}_loadMaterialAsync(t,n,r,i,a=()=>{}){let o=this._extensionsLoadMaterialAsync(t,n,r,i,a);if(o)return o;n._data=n._data||{};let s=n._data[i];if(!s){this.logOpen(`${t} ${n.name||``}`);let r=this.createMaterial(t,n,i);s={babylonMaterial:r,babylonMeshes:[],promise:this.loadMaterialPropertiesAsync(t,n,r)},n._data[i]=s,e.AddPointerMetadata(r,t),this._parent.onMaterialLoadedObservable.notifyObservers(r),this.logClose()}return r&&(s.babylonMeshes.push(r),r.onDisposeObservable.addOnce(()=>{let e=s.babylonMeshes.indexOf(r);e!==-1&&s.babylonMeshes.splice(e,1)})),a(s.babylonMaterial),s.promise.then(()=>s.babylonMaterial)}_selectImplForGltfMaterial(e){if(this.parent.useOpenPBR||e.extensions?.KHR_materials_openpbr){let e=this._pbrMaterialImpls.get(`openpbr`);if(e)return e}let t=this._pbrMaterialImpls.get(`pbr`);if(t)return t;throw Error(`No PBR material implementation loaded`)}_getDefaultImpl(){if(this.parent.useOpenPBR){let e=this._pbrMaterialImpls.get(`openpbr`);if(e)return e}let e=this._pbrMaterialImpls.get(`pbr`)??this._pbrMaterialImpls.values().next().value;if(e)return e;throw Error(`No PBR material implementation loaded`)}_createDefaultMaterial(e,t,n){this._babylonScene._blockEntityCollection=!!this._assetContainer;let r=new n.materialClass(e,this._babylonScene);r._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,r.fillMode=t,r.transparencyMode=n.materialClass.MATERIAL_OPAQUE;let i=this._getOrCreateMaterialAdapter(r);return i.transparencyAsAlphaCoverage=this._parent.transparencyAsCoverage,i.baseMetalness=1,i.specularRoughness=1,r}createMaterial(e,t,n){let r=this._extensionsCreateMaterial(e,t,n);if(r)return r;let i=t.name||`material${t.index}`;return this._createDefaultMaterial(i,n,this._selectImplForGltfMaterial(t))}loadMaterialPropertiesAsync(e,t,n){let r=this._extensionsLoadMaterialPropertiesAsync(e,t,n);if(r)return r;let i=[];return i.push(this.loadMaterialBasePropertiesAsync(e,t,n)),t.pbrMetallicRoughness&&i.push(this._loadMaterialMetallicRoughnessPropertiesAsync(`${e}/pbrMetallicRoughness`,t.pbrMetallicRoughness,n)),this.loadMaterialAlphaProperties(e,t,n),Promise.all(i).then(()=>{})}loadMaterialBasePropertiesAsync(e,t,n){let r=[],i=this._getOrCreateMaterialAdapter(n);i.emissionColor=t.emissiveFactor?N.FromArray(t.emissiveFactor):new N(0,0,0),t.doubleSided&&(i.backFaceCulling=!1,i.twoSidedLighting=!0),t.normalTexture&&(t.normalTexture.nonColorData=!0,r.push(this.loadTextureInfoAsync(`${e}/normalTexture`,t.normalTexture,e=>{e.name=`${n.name} (Normal)`,i.geometryNormalTexture=e,t.normalTexture?.scale!=null&&(e.level=t.normalTexture.scale)})),i.setNormalMapInversions(!this._babylonScene.useRightHandedSystem,this._babylonScene.useRightHandedSystem));let a,o=1,s;return t.occlusionTexture&&(t.occlusionTexture.nonColorData=!0,r.push(this.loadTextureInfoAsync(`${e}/occlusionTexture`,t.occlusionTexture,e=>{e.name=`${n.name} (Occlusion)`,a=e})),t.occlusionTexture.strength!=null&&(o=t.occlusionTexture.strength)),t.emissiveTexture&&r.push(this.loadTextureInfoA
4sync(`${e}/emissiveTexture`,t.emissiveTexture,e=>{e.name=`${n.name} (Emissive)`,s=e})),Promise.all(r).then(()=>{a&&(i.ambientOcclusionTexture=a,i.ambientOcclusionTextureStrength=o),s&&(i.emissionColorTexture=s)})}loadMaterialAlphaProperties(e,t,n){if(this._pbrMaterialImpls.size===0)throw Error(`${e}: Material type not supported`);let r=this._getOrCreateMaterialAdapter(n),i=r.baseColorTexture;switch(t.alphaMode||`OPAQUE`){case`OPAQUE`:n.transparencyMode=Tn.MATERIAL_OPAQUE,n.alpha=1;break;case`MASK`:n.transparencyMode=Tn.MATERIAL_ALPHATEST,r.alphaCutOff=t.alphaCutoff==null?.5:t.alphaCutoff,i&&(i.hasAlpha=!0,r.useAlphaFromBaseColorTexture=!0);break;case`BLEND`:n.transparencyMode=Tn.MATERIAL_ALPHABLEND,i&&(i.hasAlpha=!0,r.useAlphaFromBaseColorTexture=!0);break;default:throw Error(`${e}/alphaMode: Invalid value (${t.alphaMode})`)}}loadTextureInfoAsync(t,n,r=()=>{}){let i=this._extensionsLoadTextureInfoAsync(t,n,r);if(i)return i.then(e=>{let t=this._gltf.textures?.[n.index];return t&&this._trackTexture(t,e),e});if(this.logOpen(`${t}`),n.texCoord>=6)throw Error(`${t}/texCoord: Invalid value (${n.texCoord})`);let a=H.Get(`${t}/index`,this._gltf.textures,n.index);a._textureInfo=n;let o=this._loadTextureAsync(`/textures/${n.index}`,a,i=>{i.coordinatesIndex=n.texCoord||0,e.AddPointerMetadata(i,t),this._parent.onTextureLoadedObservable.notifyObservers(i),r(i)});return this.logClose(),o}_loadTextureAsync(t,n,r=()=>{}){let i=e=>{this._trackTexture(n,e),r(e)},a=this._extensionsLoadTextureAsync(t,n,i);if(a)return a;this.logOpen(`${t} ${n.name||``}`);let o=n.sampler==null?e.DefaultSampler:H.Get(`${t}/sampler`,this._gltf.samplers,n.sampler),s=H.Get(`${t}/source`,this._gltf.images,n.source),c=this._createTextureAsync(t,o,s,i,void 0,!n._textureInfo.nonColorData,n);return this.logClose(),c}_trackTexture(e,t,n,r){e._babylonTextures||=[],e._babylonTextures.includes(t)||e._babylonTextures.push(t),e._babylonTextureSources||=[];let i=e._babylonTextureSources.find(e=>e.babylonTexture===t),a=e._babylonTextureSources[e._babylonTextureSources.length-1],o=n??i?.imageIndex??a?.imageIndex;o!==void 0&&(i?(i.imageIndex=o,i.samplerIndex=r??i.samplerIndex??a?.samplerIndex):e._babylonTextureSources.push({babylonTexture:t,imageIndex:o,samplerIndex:r??a?.samplerIndex}))}_createTextureAsync(e,t,n,r=()=>{},i,a,o){let s=this._loadSampler(`/samplers/${t.index}`,t),c=[],l=new Nt;this._babylonScene._blockEntityCollection=!!this._assetContainer;let u={noMipmap:s.noMipMaps,invertY:!1,samplingMode:s.samplingMode,onLoad:()=>{this._disposed||l.resolve()},onError:(t,n)=>{this._disposed||l.reject(Error(`${e}: ${n&&n.message?n.message:t||`Failed to load texture`}`))},mimeType:n.mimeType??ar(n.uri??``),loaderOptions:i,useSRGBBuffer:!!a&&this._parent.useSRGBBuffers},d=new I(null,this._babylonScene,u);o&&this._trackTexture(o,d,n.index,t.index>=0?t.index:void 0),d._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,c.push(l.promise);let f=n.uri&&!Fn(n.uri)?n.uri:void 0,p=f??`${this._fileName}#image${n.index}`;return c.push(this.loadImageAsync(`/images/${n.index}`,n).then(e=>{let t=`data:${this._uniqueRootUrl}${p}`;d.updateURL(t,e);let r=d.getInternalTexture();r&&(r.label=n.name)})),d.wrapU=s.wrapU,d.wrapV=s.wrapV,r(d),this._parent.useGltfTextureNames&&(d.name=n.name||f||`image${n.index}`),Promise.all(c).then(()=>d)}_loadSampler(t,n){return n._data||={noMipMaps:n.minFilter===9728||n.minFilter===9729,samplingMode:e._GetTextureSamplingMode(t,n),wrapU:e._GetTextureWrapMode(`${t}/wrapS`,n.wrapS),wrapV:e._GetTextureWrapMode(`${t}/wrapT`,n.wrapT)},n._data}loadImageAsync(e,t){if(!t._data){if(this.logOpen(`${e} ${t.name||``}`),t.uri)t._data=this.loadUriAsync(`${e}/uri`,t,t.uri);else{let n=H.Get(`${e}/bufferView`,this._gltf.bufferViews,t.bufferView);t._data=this.loadBufferViewAsync(`/bufferViews/${n.index}`,n)}this.logClose()}return t._data}loadUriAsync(t,n,r){let i=this._extensionsLoadUriAsync(t,n,r);if(i)return i;if(!this._parent._isPreprocessUrlAsyncSet&&!e._ValidateUri(r))throw Error(`${t}: '${r}' is invalid`);if(Fn(r)){let e=new Uint8Array(qt(r));return this.log(`${t}: Decoded ${r.substring(0,64)}... (${e.length} bytes)`),Promise.resolve(e)}return this.log(`${t}: Loading ${r}`),this._parent.preprocessUrlAsync(this._rootUrl+r,this._rootUrl??void 0).then(e=>new Promise((n,i)=>{this._parent._loadFile(this._babylonScene,e,e=>{this._disposed||(this.log(`${t}: Loaded ${r} (${e.byteLength} bytes)`),n(new Uint8Array(e)))},!0,e=>{i(new Qn(`${t}: Failed to load '${r}'${e?`: `+e.status+` `+e.statusText:``}`,e))})}))}static AddPointerMetadata(e,t){e.metadata=e.metadata||{};let n=e._internalMetadata=e._internalMetadata||{},r=n.gltf=n.gltf||{};(r.pointers=r.pointers||[]).push(t)}static _GetTextureWrapMode(e,t){switch(t??=10497,t){case 33071:return I.CLAMP_ADDRESSMODE;case 33648:return I.MIRROR_ADDRESSMODE;case 10497:return I.WRAP_ADDRESSMODE;default:return A.Warn(`${e}: Invalid value (${t})`),I.WRAP_ADDRESSMODE}}static _GetTextureSamplingMode(e,t){let n=t.magFilter==null?9729:t.magFilter,r=t.minFilter==null?9987:t.minFilter;if(n===9729)switch(r){case 9728:return I.LINEAR_NEAREST;case 9729:return I.LINEAR_LINEAR;case 9984:return I.LINEAR_NEAREST_MIPNEAREST;case 9985:return I.LINEAR_LINEAR_MIPNEAREST;case 9986:return I.LINEAR_NEAREST_MIPLINEAR;case 9987:return I.LINEAR_LINEAR_MIPLINEAR;default:return A.Warn(`${e}/minFilter: Invalid value (${r})`),I.LINEAR_LINEAR_MIPLINEAR}else switch(n!==9728&&A.Warn(`${e}/magFilter: Invalid value (${n})`),r){case 9728:return I.NEAREST_NEAREST;case 9729:return I.NEAREST_LINEAR;case 9984:return I.NEAREST_NEAREST_MIPNEAREST;case 9985:return I.NEAREST_LINEAR_MIPNEAREST;case 9986:return I.NEAREST_NEAREST_MIPLINEAR;case 9987:return I.NEAREST_LINEAR_MIPLINEAR;default:return A.Warn(`${e}/minFilter: Invalid value (${r})`),I.NEAREST_NEAREST_MIPNEAREST}}static _GetTypedArrayConstructor(e,t){try{return ur(t)}catch(t){throw Error(`${e}: ${t.message}`,{cause:t})}}static _GetTypedArray(t,n,r,i,a){let o=r.buffer;i=r.byteOffset+(i||0);let s=e._GetTypedArrayConstructor(`${t}/componentType`,n),c=Ve(n);return i%c===0?new s(o,i,a):(A.Warn(`${t}: Copying buffer as byte offset (${i}) is not a multiple of component type byte length (${c})`),new s(o.slice(i,i+a*c),0))}
4static _GetNumComponents(e,t){switch(t){case`SCALAR`:return 1;case`VEC2`:return 2;case`VEC3`:return 3;case`VEC4`:return 4;case`MAT2`:return 4;case`MAT3`:return 9;case`MAT4`:return 16}throw Error(`${e}: Invalid type (${t})`)}static _ValidateUri(e){return P.IsBase64(e)||e.indexOf(`..`)===-1}static _GetDrawMode(e,t){switch(t??=4,t){case 0:return Tn.PointListDrawMode;case 1:return Tn.LineListDrawMode;case 2:return Tn.LineLoopDrawMode;case 3:return Tn.LineStripDrawMode;case 4:return Tn.TriangleFillMode;case 5:return Tn.TriangleStripDrawMode;case 6:return Tn.TriangleFanDrawMode}throw Error(`${e}: Invalid mesh primitive mode (${t})`)}_compileMaterialsAsync(){this._parent._startPerformanceCounter(`Compile materials`);let e=[];if(this._gltf.materials){for(let t of this._gltf.materials)if(t._data)for(let n in t._data){let r=t._data[n];for(let t of r.babylonMeshes){t.computeWorldMatrix(!0);let n=r.babylonMaterial;e.push(n.forceCompilationAsync(t)),e.push(n.forceCompilationAsync(t,{useInstances:!0})),this._parent.useClipPlane&&(e.push(n.forceCompilationAsync(t,{clipPlane:!0})),e.push(n.forceCompilationAsync(t,{clipPlane:!0,useInstances:!0})))}}}return Promise.all(e).then(()=>{this._parent._endPerformanceCounter(`Compile materials`)})}_compileShadowGeneratorsAsync(){this._parent._startPerformanceCounter(`Compile shadow generators`);let e=[],t=this._babylonScene.lights;for(let n of t){let t=n.getShadowGenerator();t&&e.push(t.forceCompilationAsync())}return Promise.all(e).then(()=>{this._parent._endPerformanceCounter(`Compile shadow generators`)})}_forEachExtensions(e){for(let t of this._extensions)t.enabled&&e(t)}_applyExtensions(e,t,n){for(let r of this._extensions)if(r.enabled){let i=`${r.name}.${t}`,a=e;a._activeLoaderExtensionFunctions=a._activeLoaderExtensionFunctions||{};let o=a._activeLoaderExtensionFunctions;if(!o[i]){o[i]=!0;try{let e=n(r);if(e)return e}finally{delete o[i]}}}return null}_extensionsOnLoading(){this._forEachExtensions(e=>e.onLoading&&e.onLoading())}async _extensionsOnReadyAsync(){for(let e of this._extensions)e.enabled&&e.onReady&&await e.onReady()}_extensionsLoadSceneAsync(e,t){return this._applyExtensions(t,`loadScene`,n=>n.loadSceneAsync&&n.loadSceneAsync(e,t))}_extensionsLoadNodeAsync(e,t,n){return this._applyExtensions(t,`loadNode`,r=>r.loadNodeAsync&&r.loadNodeAsync(e,t,n))}_extensionsLoadCameraAsync(e,t,n){return this._applyExtensions(t,`loadCamera`,r=>r.loadCameraAsync&&r.loadCameraAsync(e,t,n))}_extensionsLoadVertexDataAsync(e,t,n){return this._applyExtensions(t,`loadVertexData`,r=>r._loadVertexDataAsync&&r._loadVertexDataAsync(e,t,n))}_extensionsLoadMeshPrimitiveAsync(e,t,n,r,i,a){return this._applyExtensions(i,`loadMeshPrimitive`,o=>o._loadMeshPrimitiveAsync&&o._loadMeshPrimitiveAsync(e,t,n,r,i,a))}_extensionsLoadMaterialAsync(e,t,n,r,i){return this._applyExtensions(t,`loadMaterial`,a=>a._loadMaterialAsync&&a._loadMaterialAsync(e,t,n,r,i))}_extensionsCreateMaterial(e,t,n){return this._applyExtensions(t,`createMaterial`,r=>r.createMaterial&&r.createMaterial(e,t,n))}_extensionsLoadMaterialPropertiesAsync(e,t,n){return this._applyExtensions(t,`loadMaterialProperties`,r=>r.loadMaterialPropertiesAsync&&r.loadMaterialPropertiesAsync(e,t,n))}_extensionsLoadTextureInfoAsync(e,t,n){return this._applyExtensions(t,`loadTextureInfo`,r=>r.loadTextureInfoAsync&&r.loadTextureInfoAsync(e,t,n))}_extensionsLoadTextureAsync(e,t,n){return this._applyExtensions(t,`loadTexture`,r=>r._loadTextureAsync&&r._loadTextureAsync(e,t,n))}_extensionsLoadAnimationAsync(e,t){return this._applyExtensions(t,`loadAnimation`,n=>n.loadAnimationAsync&&n.loadAnimationAsync(e,t))}_extensionsLoadAnimationChannelAsync(e,t,n,r,i){return this._applyExtensions(n,`loadAnimationChannel`,a=>a._loadAnimationChannelAsync&&a._loadAnimationChannelAsync(e,t,n,r,i))}_extensionsLoadSkinAsync(e,t,n){return this._applyExtensions(n,`loadSkin`,r=>r._loadSkinAsync&&r._loadSkinAsync(e,t,n))}_extensionsLoadUriAsync(e,t,n){return this._applyExtensions(t,`loadUri`,r=>r._loadUriAsync&&r._loadUriAsync(e,t,n))}_extensionsLoadBufferViewAsync(e,t){return this._applyExtensions(t,`loadBufferView`,n=>n.loadBufferViewAsync&&n.loadBufferViewAsync(e,t))}_extensionsLoadBufferAsync(e,t,n,r){return this._applyExtensions(t,`loadBuffer`,i=>i.loadBufferAsync&&i.loadBufferAsync(e,t,n,r))}static LoadExtensionAsync(e,t,n,r){if(!t.extensions)return null;let i=t.extensions[n];return i?r(`${e}/extensions/${n}`,i):null}static LoadExtraAsync(e,t,n,r){if(!t.extras)return null;let i=t.extras[n];return i?r(`${e}/extras/${n}`,i):null}isExtensionUsed(e){return!!this._gltf.extensionsUsed&&this._gltf.extensionsUsed.indexOf(e)!==-1}logOpen(e){this._parent._logOpen(e)}logClose(){this._parent._logClose()}log(e){this._parent._log(e)}startPerformanceCounter(e){this._parent._startPerformanceCounter(e)}endPerformanceCounter(e){this._parent._endPerformanceCounter(e)}};U.DefaultSampler={index:-1};var Zi=!1;function Qi(){Zi||(Zi=!0,a._CreateGLTF2Loader=e=>new U(e))}rt(),Qi(),f(),Yn();var $i=e({AnimationPropertyInfo:()=>ra,RegisterGLTFLoaderAnimation:()=>sa,TransformNodeAnimationPropertyInfo:()=>ia,WeightAnimationPropertyInfo:()=>aa,getQuaternion:()=>ta,getVector3:()=>ea,getWeights:()=>na});ne(),zn();function ea(e,t,n,r){return R.FromArray(t,n).scaleInPlace(r)}function ta(e,t,n,r){return z.FromArray(t,n).scaleInPlace(r)}function na(e,t,n,r){let i=Array(e._numMorphTargets);for(let e=0;e<i.length;e++)i[e]=t[n++]*r;return i}var ra=class{constructor(e,t,n,r){this.type=e,this.name=t,this.getValue=n,this.get
4Stride=r}_buildAnimation(e,t,n){let r=new M(e,this.name,t,this.type);return r.setKeys(n,!0),r}},ia=class extends ra{buildAnimations(e,t,n,r){let i=[];return i.push({babylonAnimatable:e._babylonTransformNode,babylonAnimation:this._buildAnimation(t,n,r)}),i}},aa=class extends ra{buildAnimations(e,t,n,r){let i=[];if(e._numMorphTargets)for(let a=0;a<e._numMorphTargets;a++){let o=new M(`${t}_${a}`,this.name,n,this.type);if(o.setKeys(r.map(e=>({frame:e.frame,inTangent:e.inTangent?e.inTangent[a]:void 0,value:e.value[a],outTangent:e.outTangent?e.outTangent[a]:void 0,interpolation:e.interpolation})),!0),e._primitiveBabylonMeshes){for(let t of e._primitiveBabylonMeshes)if(t.morphTargetManager){let e=t.morphTargetManager.getTarget(a),n=o.clone();e.animations.push(n),i.push({babylonAnimatable:e,babylonAnimation:n})}}}return i}},oa=!1;function sa(){oa||(oa=!0,V(`/nodes/{}/translation`,[new ia(M.ANIMATIONTYPE_VECTOR3,`position`,ea,()=>3)]),V(`/nodes/{}/rotation`,[new ia(M.ANIMATIONTYPE_QUATERNION,`rotationQuaternion`,ta,()=>4)]),V(`/nodes/{}/scale`,[new ia(M.ANIMATIONTYPE_VECTOR3,`scaling`,ea,()=>3)]),V(`/nodes/{}/weights`,[new aa(M.ANIMATIONTYPE_FLOAT,`influence`,na,e=>e._numMorphTargets)]))}sa();var ca=e({OpenPBRMaterialLoadingAdapter:()=>la});jn(),On();var la=class{constructor(e){this._specWorkflow=!1,this._diffuseTransmissionTint=N.White(),this._diffuseTransmissionTintTexture=null,this._material=e}get material(){return this._material}get isUnlit(){return this._material.unlit}set isUnlit(e){this._material.unlit=e}set backFaceCulling(e){this._material.backFaceCulling=e}get backFaceCulling(){return this._material.backFaceCulling}set twoSidedLighting(e){this._material.twoSidedLighting=e}get twoSidedLighting(){return this._material.twoSidedLighting}set alphaCutOff(e){this._material.alphaCutOff=e}get alphaCutOff(){return this._material.alphaCutOff}set useAlphaFromBaseColorTexture(e){this._material._useAlphaFromBaseColorTexture=e}get useAlphaFromBaseColorTexture(){return this._material._useAlphaFromBaseColorTexture}get transparencyAsAlphaCoverage(){return!1}set transparencyAsAlphaCoverage(e){}set baseColor(e){this._material.baseColor=e}get baseColor(){return this._material.baseColor}set baseColorTexture(e){this._material.baseColorTexture=e}get baseColorTexture(){return this._material.baseColorTexture}set baseDiffuseRoughness(e){this._material.baseDiffuseRoughness=e}get baseDiffuseRoughness(){return this._material.baseDiffuseRoughness}set baseDiffuseRoughnessTexture(e){this._material.baseDiffuseRoughnessTexture=e}get baseDiffuseRoughnessTexture(){return this._material.baseDiffuseRoughnessTexture}set baseMetalness(e){this._material.baseMetalness=e}get baseMetalness(){return this._material.baseMetalness}set baseMetalnessTexture(e){this._material.baseMetalnessTexture=e}get baseMetalnessTexture(){return this._material.baseMetalnessTexture}set useRoughnessFromMetallicTextureGreen(e){this._material._useRoughnessFromMetallicTextureGreen=e}set useMetallicFromMetallicTextureBlue(e){this._material._useMetallicFromMetallicTextureBlue=e}enableSpecularEdgeColor(e=!1){}configureSpecularGlossiness(){this._specWorkflow=!0}set specularWeight(e){this._material.specularWeight=e}get specularWeight(){return this._material.specularWeight}set specularWeightTexture(e){this._material.specularColorTexture===e?(this._material.specularWeightTexture=null,this._material._useSpecularWeightFromSpecularColorTexture=!0,this._material._useSpecularWeightFromAlpha=!0):this._material.specularWeightTexture=e}get specularWeightTexture(){return this._material.specularWeightTexture}set specularColor(e){this._material.specularColor=e}get specularColor(){return this._material.specularColor}set specularColorTexture(e){this._material.specularColorTexture=e,this._material.specularWeightTexture===this._material.specularColorTexture&&(this._material.specularWeightTexture=null,this._material._useSpecularWeightFromSpecularColorTexture=!0,this._material._useSpecularWeightFromAlpha=!0)}get specularColorTexture(){return this._material.specularColorTexture}set specularRoughness(e){this._material.specularRoughness=e}get specularRoughness(){return this._material.specularRoughness}set specularRoughnessTexture(e){this._material.specularRoughnessTexture=e}get specularRoughnessTexture(){return this._material.specularRoughnessTexture}set specularIor(e){this._material.specularIor=e}get specularIor(){return this._material.specularIor}set glossiness(e){this._material.specularRoughness=Math.max(1-e,0)}get glossiness(){return 1-this._material.specularRoughness}set emissionColor(e){this._material.emissionColor=e}get emissionColor(){return this._material.emissionColor}set emissionLuminance(e){this._material.emissionLuminance=e}get emissionLuminance(){return this._material.emissionLuminance}set emissionColorTexture(e){this._material.emissionColorTexture=e}get emissionColorTexture(){return this._material.emissionColorTexture}set ambientOcclusionTexture(e){this._material.ambientOcclusionTexture=e}get ambientOcclusionTexture(){return this._material.ambientOcclusionTexture}set ambientOcclusionTextureStrength(e){let t=this._material.ambientOcclusionTexture;t&&(t.level=e)}get ambientOcclusionTextureStrength(){return this._material.ambientOcclusionTexture?.level??1}configureCoat(){}set coatWeight(e){this._material.coatWeight=e}get coatWeight(){return this._material.coatWeight}set coatWeightTexture(e){this._material.coatWeightTexture=e}get coatWeightTexture(){return this._material.coatWeightTexture}set coatColor(e){this._material.coatColor=e}get coatColor(){return this._material.coatColor}set coatColorTexture(e){this._material.coatColorTexture=e}set coatRoughness(e){this._material.coatRoughness=e}get coatRoughness(){return this._material.coatRoughness}set coatRoughnessTexture(e){this._material.coatRoughnessTexture=e,e&&(this._material._useCoatRoughnessFromGreenChannel=!0)}get coatRoughnessTexture(){return this._material.coatRoughnessTexture}set coatIor(e){this._material.coatIor=e}get coatIor(){return this._material.coatIor}set coatDarkening(e){this._material.coatDarkening=e}get coatDarkening(){return this._material.coatDarkening}set coatDarkeningTexture(e){this._material.coatDarkeningTexture=e}set coatRoughnessAnisotropy(e){this._material.coatRoughnessAnisotropy=e}get coatRoughnessAnisotropy(){return this._material.coatRoughnessAnisotropy}set geometryCoatTangentAngle(e){this._material.geometryCoatTangentAngle=e}set geometryCoatTangentTexture(e){this._material.geometryCoatTangentTexture=e,e&&(this._material._useCoatRoughnessAnisotropyFromTangentTexture=!0)}get geometryCoatTangentTexture(){return this._material.geometryCoatTangentTexture}configureTransmission(){this._material.geometryThinWalled=1,this._material.transmissionDepth=0}set transmissionWeight(e){this._material.transmissionWeight=e}set transmissionWeightTexture(e){this._material.transmissionWeightTexture=e}get transmissionWeightTexture(){return this._material.transmissionWeightTexture}get transmissionWeight(){return this._material.transmissionWeight}set transmissionScatter(e){this._material.transmissionScatter=e}get transmissionScatter(){return this._material.transmissionScatter}set transmissionScatterTexture(e){this._material.transmissionScatterTexture=e}get transmissionScatterTexture(){return this._material.transmissionScatterTexture}set transmissionScatterAnisotropy(e){this._material.transmissionScatterAnisotropy=e}set transmissionDispersionAbbeNumber(e){this._material.transmissionDispersionAbbeNumber=e}set transmissionDispersionScale(e){this._material.transmissionDispersionScale=e}set transmissionDepth(e){e!==Number.MAX_VALUE||this._material.transmissionDepth!==0?this._material.transmissionDepth=e:this._material.transmissionDepth=0}get transmissionDepth(){return this._material.transmissionDepth}set transmissionColor(e){e.equals(N.White())||(this._material.transmissionColor=e)}get transmissionColor(){return this._material.transmissionColor}
4get refractionBackgroundTexture(){return this._material.backgroundRefractionTexture}set refractionBackgroundTexture(e){this._material.backgroundRefractionTexture=e}configureVolume(){this._material.geometryThinWalled=0}set geometryThinWalled(e){this._material.geometryThinWalled=+!!e}get geometryThinWalled(){return!!this._material.geometryThinWalled}set volumeThicknessTexture(e){this._material.geometryThicknessTexture=e,this._material._useGeometryThicknessFromGreenChannel=!0}set volumeThickness(e){this._material.geometryThickness=e}configureSubsurface(){this._material.geometryThinWalled=1,this._material.subsurfaceScatterAnisotropy=1}set subsurfaceWeight(e){this._material.subsurfaceWeight=e}get subsurfaceWeight(){return this._material.subsurfaceWeight}set subsurfaceWeightTexture(e){this._material.subsurfaceWeightTexture=e,this._material._useSubsurfaceWeightFromTextureAlpha=!0}get subsurfaceWeightTexture(){return this._material.subsurfaceWeightTexture}set subsurfaceColor(e){this._material.subsurfaceColor=e}set subsurfaceColorTexture(e){this._material.subsurfaceColorTexture=e}set diffuseTransmissionTint(e){this._diffuseTransmissionTint=e}get diffuseTransmissionTint(){return this._diffuseTransmissionTint}set diffuseTransmissionTintTexture(e){this._diffuseTransmissionTintTexture=e}get subsurfaceRadius(){return this._material.subsurfaceRadius}set subsurfaceRadius(e){this._material.subsurfaceRadius=e}get subsurfaceRadiusScale(){return this._material.subsurfaceRadiusScale}set subsurfaceRadiusScale(e){this._material.subsurfaceRadiusScale=e}set subsurfaceScatterAnisotropy(e){this._material.subsurfaceScatterAnisotropy=e}isTranslucent(){return this.transmissionWeight>0||this.subsurfaceWeight>0}configureFuzz(){}set fuzzWeight(e){this._material.fuzzWeight=e}set fuzzWeightTexture(e){this._material.fuzzWeightTexture=e}set fuzzColor(e){this._material.fuzzColor=e}set fuzzColorTexture(e){this._material.fuzzColorTexture=e}set fuzzRoughness(e){this._material.fuzzRoughness=e}set fuzzRoughnessTexture(e){this._material.fuzzRoughnessTexture=e,this._material._useFuzzRoughnessFromTextureAlpha=!0}set specularRoughnessAnisotropy(e){this._material.specularRoughnessAnisotropy=e}get specularRoughnessAnisotropy(){return this._material.specularRoughnessAnisotropy}set geometryTangentAngle(e){this._material.geometryTangentAngle=e}set geometryTangentTexture(e){this._material.geometryTangentTexture=e,this._material._useSpecularRoughnessAnisotropyFromTangentTexture=!0}get geometryTangentTexture(){return this._material.geometryTangentTexture}configureGltfStyleAnisotropy(e=!0){this._material._useGltfStyleAnisotropy=e}set thinFilmWeight(e){this._material.thinFilmWeight=e}set thinFilmIor(e){this._material.thinFilmIor=e}set thinFilmThicknessMinimum(e){this._material.thinFilmThicknessMin=e/1e3}set thinFilmThicknessMaximum(e){this._material.thinFilmThickness=e/1e3}set thinFilmWeightTexture(e){this._material.thinFilmWeightTexture=e}set thinFilmThicknessTexture(e){this._material.thinFilmThicknessTexture=e,this._material._useThinFilmThicknessFromTextureGreen=!0}set unlit(e){this._material.unlit=e}set geometryOpacity(e){this._material.geometryOpacity=e}get geometryOpacity(){return this._material.geometryOpacity}set geometryNormalTexture(e){this._material.geometryNormalTexture=e}get geometryNormalTexture(){return this._material.geometryNormalTexture}setNormalMapInversions(e,t){}set geometryCoatNormalTexture(e){this._material.geometryCoatNormalTexture=e}get geometryCoatNormalTexture(){return this._material.geometryCoatNormalTexture}set geometryCoatNormalTextureScale(e){this._material.geometryCoatNormalTexture&&(this._material.geometryCoatNormalTexture.level=e)}async finalizeAsync(e){if(this._diffuseTransmissionTint&&!this._diffuseTransmissionTint.equals(N.White())||this._diffuseTransmissionTintTexture){if(this._material.geometryThinWalled)this.subsurfaceColor=this._diffuseTransmissionTint,this.subsurfaceColorTexture=this._diffuseTransmissionTintTexture;else if(await this.copySurfaceToCoatAsync(e,this.subsurfaceWeight,this.subsurfaceWeightTexture,nr.A,this._diffuseTransmissionTint,this._diffuseTransmissionTintTexture,!0),e._disposed)return}if(this.transmissionWeight>0){if(this._material.geometryThinWalled||this._material.transmissionDepth===0)this._material.transmissionColor=this._material.baseColor,this._material.transmissionColorTexture=this._material.baseColorTexture;else if((!this.baseColor.equals(N.White())||this.baseColorTexture!==null)&&(await this.copySurfaceToCoatAsync(e,this.transmissionWeight,this.transmissionWeightTexture,nr.R,this.baseColor,this.baseColorTexture,!1),e._disposed))return}if(this._specWorkflow){let t=await hn(`newRoughnessTexture (`+this._material.name+`)`,await In(`glossiness (`+this._material.name+`)`,sr(this.specularColorTexture,new F(this.specularColor.r,this.specularColor.g,this.specularColor.b,this.glossiness),nr.A,Vt.Linear),nr.A,this._material.getScene(),Vt.Linear,qe.R),this._material.getScene(),qe.R,Vt.Linear,qe.R);if(e._disposed){t.texture?.dispose();return}this.specularRoughnessTexture=t.texture,this.specularRoughness=t.factor?t.factor.r:1;let n=await $n(`metallicTexture (`+this._material.name+`)`,sr(this.specularColorTexture,this.specularColor.toColor4(),nr.RGBA,Vt.Linear),this._material.getScene(),!1,Vt.SRGB,qe.RGB);if(e._disposed){n.texture?.dispose();return}this.baseMetalnessTexture=n.texture,this.baseMetalness=n.factor?n.factor.r:1;let r=await Ft(`newBaseColor (`+this._material.name+`)`,sr(this.baseColorTexture,this.baseColor.toColor4(),nr.RGBA,Vt.Linear),sr(this.specularColorTexture,this.specularColor.toColor4(),nr.RGBA,Vt.Linear),{...n,dispose:void 0,colorSpace:Vt.Linear},this._material.getScene(),Vt.SRGB,qe.RGB);if(e._disposed){r.texture?.dispose();return}this.baseColorTexture?.dispose(),this.baseColorTexture=r.texture,this.baseColor=r.factor?new N(r.factor.r,r.factor.g,r.factor.b):N.White(),this.specularColorTexture?.dispose(),this.specularColorTexture=null}}async copySurfaceToCoatAsync(e,t,n,r,i,a,o=!1){let s=this._material.coatWeight,c=this._material.coatWeightTexture,l=this._material.coatColor.clone(),u=this._material.coatColorTexture,d=this._material.geometryCoatNormalTexture,f=new F(s,s,s,s),p=new F(t,t,t,t);this.coatWeightTexture=null,this.coatWeight=1;
4let m=await Promise.allSettled([Ft(`lerpExistingCoat`,sr(null,new F(1,1,1,1)),sr(u,l.toColor4(),nr.RGBA,Vt.SRGB),sr(c,f,nr.R),this._material.getScene(),Vt.SRGB),Ft(`lerpSurfaceColor`,sr(null,new F(1,1,1,1)),sr(a,i.toColor4(),nr.RGBA,Vt.SRGB),sr(n,p,r),this._material.getScene(),Vt.SRGB)]),h=m.find(e=>e.status===`rejected`);if(h){for(let e of m)e.status===`fulfilled`&&e.value.texture?.dispose();throw h.reason}let[g,_]=m.map(e=>e.value);if(e._disposed){g.texture?.dispose(),_.texture?.dispose();return}let v=await Hn(`newCoatColor (`+this._material.name+`)`,g,_,this._material.getScene(),Vt.SRGB);if(e._disposed){v.texture?.dispose();return}v.texture?(this.coatColorTexture=v.texture,this.coatColor=N.White()):v.factor&&(this.coatColorTexture=null,this.coatColor.fromArray([v.factor.r,v.factor.g,v.factor.b]));let y=await Ft(`newCoatIor (`+this._material.name+`)`,sr(null,new F(this._material.specularIor,this._material.specularIor,this._material.specularIor,1),nr.R),sr(null,new F(this.coatIor,this.coatIor,this.coatIor,1),nr.R),sr(c,f,nr.R),this._material.getScene());if(e._disposed){y.texture?.dispose();return}this.coatIor=y.factor?y.factor.r:this.coatIor;let b=await Ft(`newCoatRoughness (`+this._material.name+`)`,sr(this.specularRoughnessTexture,new F(this.specularRoughness,this.specularRoughness,this.specularRoughness,1),nr.G),sr(this.coatRoughnessTexture,new F(this.coatRoughness,this.coatRoughness,this.coatRoughness,1),nr.G),sr(c,f,nr.R),this._material.getScene());if(e._disposed){b.texture?.dispose();return}this.coatRoughness=b.factor?b.factor.r:1,this.coatRoughnessTexture=b.texture;let x=await Ft(`newCoatDarkening (`+this._material.name+`)`,sr(null,new F(0,0,0,1),nr.R),sr(null,new F(this.coatDarkening,this.coatDarkening,this.coatDarkening,1),nr.R),sr(c,f,nr.R),this._material.getScene());if(e._disposed){x.texture?.dispose();return}if(this.coatDarkening=x.factor?x.factor.r:this.coatDarkening,o){let t=await Ft(`newSpecularRoughness (`+this._material.name+`)`,sr(this.specularRoughnessTexture,new F(this._material.specularRoughness,this._material.specularRoughness,this._material.specularRoughness,1),nr.G),sr(null,new F(1,1,1,1),nr.R),sr(n,p,r),this._material.getScene());if(e._disposed){t.texture?.dispose();return}this.specularRoughness=t.factor?t.factor.r:1,this.specularRoughnessTexture=t.texture}if(d||this.geometryNormalTexture){let t=await Ft(`newCoatNormal (`+this._material.name+`)`,sr(this.geometryNormalTexture,this.geometryNormalTexture?new F(1,1,1,1):new F(.5,.5,1,1),nr.RGBA),sr(d,d?new F(1,1,1,1):new F(.5,.5,1,1),nr.RGBA),sr(c,f,nr.R),this._material.getScene());if(e._disposed){t.texture?.dispose();return}t.texture&&(this.geometryCoatNormalTexture=t.texture)}}},ua=e({PBRMaterialLoadingAdapter:()=>da});_(),Se(),zn();var da=class{constructor(e){this._specWorkflow=!1,this._material=e,this._material.enableSpecularAntiAliasing=!0}get material(){return this._material}async finalizeAsync(e){}get isUnlit(){return this._material.unlit}set isUnlit(e){this._material.unlit=e}set backFaceCulling(e){this._material.backFaceCulling=e}get backFaceCulling(){return this._material.backFaceCulling}set twoSidedLighting(e){this._material.twoSidedLighting=e}get twoSidedLighting(){return this._material.twoSidedLighting}set alphaCutOff(e){this._material.alphaCutOff=e}get alphaCutOff(){return this._material.alphaCutOff}set useAlphaFromBaseColorTexture(e){this._material.useAlphaFromAlbedoTexture=e}get useAlphaFromBaseColorTexture(){return this._material.useAlphaFromAlbedoTexture}get transparencyAsAlphaCoverage(){return this._material.useRadianceOverAlpha||this._material.useSpecularOverAlpha}set transparencyAsAlphaCoverage(e){this._material.useRadianceOverAlpha=!e,this._material.useSpecularOverAlpha=!e}set baseColor(e){this._material.albedoColor=e}get baseColor(){return this._material.albedoColor}set baseColorTexture(e){this._material.albedoTexture=e}get baseColorTexture(){return this._material.albedoTexture}set baseDiffuseRoughness(e){this._material.baseDiffuseRoughness=e,e>0&&(this._material.brdf.baseDiffuseModel=k.MATERIAL_DIFFUSE_MODEL_E_OREN_NAYAR)}get baseDiffuseRoughness(){return this._material.baseDiffuseRoughness??0}set baseDiffuseRoughnessTexture(e){this._material.baseDiffuseRoughnessTexture=e}get baseDiffuseRoughnessTexture(){return this._material.baseDiffuseRoughnessTexture}set baseMetalness(e){this._material.metallic=e}get baseMetalness(){return this._material.metallic??1}set baseMetalnessTexture(e){this._material.metallicTexture=e}get baseMetalnessTexture(){return this._material.metallicTexture}set useRoughnessFromMetallicTextureGreen(e){this._material.useRoughnessFromMetallicTextureGreen=e,this._material.useRoughnessFromMetallicTextureAlpha=!e}set useMetallicFromMetallicTextureBlue(e){this._material.useMetallnessFromMetallicTextureBlue=e}enableSpecularEdgeColor(e=!1){e&&(this._material.brdf.dielectricSpecularModel=k.MATERIAL_DIELECTRIC_SPECULAR_MODEL_OPENPBR,this._material.brdf.conductorSpecularModel=k.MATERIAL_CONDUCTOR_SPECULAR_MODEL_OPENPBR)}configureSpecularGlossiness(){this._specWorkflow=!0,this._material.metallic=null,this._material.roughness=null,this._material.useMicroSurfaceFromReflectivityMapAlpha=!0}set specularWeight(e){this._material.metallicF0Factor=e}get specularWeight(){return this._material.metallicF0Factor??1}set specularWeightTexture(e){e?(this._material.metallicReflectanceTexture=e,this._material.useOnlyMetallicFromMetallicReflectanceTexture=!0):(this._material.metallicReflectanceTexture=null,this._material.useOnlyMetallicFromMetallicReflectanceTexture=!1)}get specularWeightTexture(){return this._material.metallicReflectanceTexture}set specularColor(e){this._specWorkflow?this._material.reflectivityColor=e:this._material.metallicReflectanceColor=e}get specularColor(){return this._specWorkflow?this._material.reflectivityColor:this._material.metallicReflectanceColor}set specularColorTexture(e){this._specWorkflow?(this._material.reflectivityTexture=e,this._material.reflectivityTexture&&(this._material.reflectivityTexture.hasAlpha=!0)):this._material.reflectanceTexture=e}get specularColorTexture(){return this._specWorkflow?this._material.reflectivityTexture:this._material.reflectanceTexture}set specularRoughness(e){this._material.roughness=e}get specularRoughness(){return this._material.roughness??1}set specularRoughnessTexture(e){this.baseMetalnessTexture||(this._material.metallicTexture=e)}get specularRoughnessTexture(){return this._material.metallicTexture}set specularIor(e){this._material.indexOfRefraction=e}get specularIor(){return this._material.indexOfRefraction}get glossiness(){return this._material.microSurface??1}set glossiness(e){this._material.microSurface=e}set emissionColor(e){this._material.emissiveColor=e}get emissionColor(){return this._material.emissiveColor}set emissionLuminance(e){this._material.emissiveIntensity=e}get emissionLuminance(){return this._material.emissiveIntensity}set emissionColorTexture(e){this._material.emissiveTexture=e}get emissionColorTexture(){return this._material.emissiveTexture}set ambientOcclusionTexture(e){this._material.ambientTexture=e,e&&(this._material.useAmbientInGrayScale=!0)}get ambientOcclusionTexture(){return this._material.ambientTexture}set ambientOcclusionTextureStrength(e){this._material.ambientTextureStrength=e}get ambientOcclusionTextureStrength(){return this._material.ambientTextureStrength??1}configureCoat(){this._material.clearCoat.isEnabled=!0,this._material.clearCoat.useRoughnessFromMainTexture=!1,this._material.clearCoat.remapF0OnInterfaceChange=!1}set coatWeight(e){this._material.clearCoat.isEnabled=!0,this._material.clearCoat.intensity=e}get coatWeight(){return this._material.clearCoat.intensity}set coatWeightTexture(e){this._material.clearCoat.isEnabled=!0,this._material.clearCoat.texture=e}get coatWeightTexture(){return this._material.clearCoat.texture}set coatColor(e){this._material.clearCoat.isTintEnabled=e!=N.White(),this._material.clearCoat.tintColor=e}set coatColorTexture(e){this._material.clearCoat.tintTexture=e}set coatRoughness(e){this._material.clearCoat.isEnabled=!0,this._material.clearCoat.roughness=e}get coatRoughness(){return this._material.clearCoat.roughness??0}set coatRoughnessTexture(e){this._material.clearCoat.isEnabled=!0,this._material.clearCoat.useRoughnessFromMainTexture=!1,this._material.clearCoat.textureRoughness=e}get coatRoughnessTexture(){return this._material.clearCoat.textureRoughness}set coatIor(e){this._material.clearCoat.indexOfRefraction=e}set coatDarkening(e){}set coatDarkeningTexture(e){}set coatRoughnessAnisotropy(e){}get coatRoughnessAnisotropy(){return 0}set geometryCoatTangentAngle(e){}set geometryCoatTangentTexture(e){}get geometryCoatTangentTexture(){return null}set transmissionWeight(e){this._material.subSurface.isRefractionEnabled=e>0,this._material.subSurface.refractionIntensity=e}get transmissionWeight(){return this._material.subSurface.isRefractionEnabled?this._material.subSurface.refractionIntensity:0}set transmissionWeightTexture(e){this._material.subSurface.isRefractionEnabled=!0,this._material.subSurface.refractionIntensityTexture=e,this._material.subSurface.useGltfStyleTextures=!0}set transmissionDepth(e){this.transmissionWeight>0?this._material.subSurface.tintColorAtDistance=e:this.subsurfaceWeight>0&&this._material.subSurface.diffusionDistance.multiplyInPlace(new N(e,e,e))}get transmissionDepth(){return this.transmissionWeight>0?this._material.subSurface.tintColorAtDistance:0}set transmissionColor(e){this.transmissionWeight>0?this._material.subSurface.tintColor=e:this.subsurfaceWeight>0&&this._material.subSurface.diffusionDistance.multiplyInPlace(e)}get transmissionColor(){return this.transmissionWeight>0?this._material.subSurface.tintColor:this.subsurfaceWeight>0?this._material.subSurface.diffusionDistance:new N(0,0,0)}set transmissionScatter(e){this._material.subSurface.diffusionDistance=e}get transmissionScatter(){return this._material.subSurface.diffusionDistance}set transmissionScatterTexture(e){}set transmissionScatterAnisotropy(e){}set transmissionDispersionAbbeNumber(e){}set transmissionDispersionScale(e){e>0?(this._material.subSurface.isDispersionEnabled=!0,this._material.subSurface.dispersion=20/e):(this._material.subSurface.isDispersionEnabled=!1,this._material.subSurface.dispersion=0)}
4get refractionBackgroundTexture(){return this._material.subSurface.refractionTexture}set refractionBackgroundTexture(e){this._material.subSurface.refractionTexture=e}configureTransmission(){this._material.subSurface.volumeIndexOfRefraction=1,this._material.subSurface.useAlbedoToTintRefraction=!0,this._material.subSurface.minimumThickness=0,this._material.subSurface.maximumThickness=0}configureVolume(){}set geometryThinWalled(e){}get geometryThinWalled(){return this._material.subSurface.maximumThickness===0}set volumeThicknessTexture(e){this._material.subSurface.thicknessTexture=e,this._material.subSurface.useGltfStyleTextures=!0}set volumeThickness(e){this._material.subSurface.minimumThickness=0,this._material.subSurface.maximumThickness=e,this._material.subSurface.useThicknessAsDepth=!0,e>0&&(this._material.subSurface.volumeIndexOfRefraction=this._material.indexOfRefraction)}configureSubsurface(){this._material.subSurface.useGltfStyleTextures=!0,this._material.subSurface.volumeIndexOfRefraction=1,this._material.subSurface.minimumThickness=0,this._material.subSurface.maximumThickness=0,this._material.subSurface.useAlbedoToTintTranslucency=!1}set subsurfaceWeight(e){this._material.subSurface.isTranslucencyEnabled=e>0,this._material.subSurface.translucencyIntensity=e}get subsurfaceWeight(){return this._material.subSurface.isTranslucencyEnabled?this._material.subSurface.translucencyIntensity:0}set subsurfaceWeightTexture(e){this._material.subSurface.translucencyIntensityTexture=e}set subsurfaceColor(e){let t=new R(-Math.log(this.transmissionColor.r),-Math.log(this.transmissionColor.g),-Math.log(this.transmissionColor.b));t.scaleInPlace(1/Math.max(this.transmissionDepth,.001));let n=t,r=Math.max(n.x,Math.max(n.y,n.z)),i=r>0?1/r:1;this._material.subSurface.diffusionDistance=new N(Math.exp(-n.x*i),Math.exp(-n.y*i),Math.exp(-n.z*i))}set subsurfaceColorTexture(e){}set diffuseTransmissionTint(e){this._material.subSurface.tintColor=e}get diffuseTransmissionTint(){return this._material.subSurface.tintColor}set diffuseTransmissionTintTexture(e){this._material.subSurface.translucencyColorTexture=e}get subsurfaceRadius(){return 1}set subsurfaceRadius(e){}get subsurfaceRadiusScale(){return this._material.subSurface.scatteringDiffusionProfile??N.White()}set subsurfaceRadiusScale(e){this._material.subSurface.scatteringDiffusionProfile=e}set subsurfaceScatterAnisotropy(e){}isTranslucent(){return this.transmissionWeight>0||this.subsurfaceWeight>0}configureFuzz(){this._material.sheen.isEnabled=!0,this._material.sheen.useRoughnessFromMainTexture=!1,this._material.sheen.albedoScaling=!0}set fuzzWeight(e){this._material.sheen.isEnabled=!0,this._material.sheen.intensity=e}set fuzzWeightTexture(e){this._material.sheen.texture||(this._material.sheen.texture=e)}set fuzzColor(e){this._material.sheen.isEnabled=!0,this._material.sheen.color=e}set fuzzColorTexture(e){this._material.sheen.texture=e}set fuzzRoughness(e){this._material.sheen.isEnabled=!0,this._material.sheen.roughness=e}set fuzzRoughnessTexture(e){this._material.sheen.isEnabled=!0,this._material.sheen.textureRoughness=e}set specularRoughnessAnisotropy(e){this._material.anisotropy.isEnabled=!0,this._material.anisotropy.intensity=e}get specularRoughnessAnisotropy(){return this._material.anisotropy.intensity}set geometryTangentAngle(e){this._material.anisotropy.isEnabled=!0,this._material.anisotropy.angle=e}set geometryTangentTexture(e){this._material.anisotropy.isEnabled=!0,this._material.anisotropy.texture=e}get geometryTangentTexture(){return this._material.anisotropy.texture}configureGltfStyleAnisotropy(e=!0){}set thinFilmWeight(e){this._material.iridescence.isEnabled=e>0,this._material.iridescence.intensity=e}set thinFilmIor(e){this._material.iridescence.indexOfRefraction=e}set thinFilmThicknessMinimum(e){this._material.iridescence.minimumThickness=e}set thinFilmThicknessMaximum(e){this._material.iridescence.maximumThickness=e}set thinFilmWeightTexture(e){this._material.iridescence.texture=e}set thinFilmThicknessTexture(e){this._material.iridescence.thicknessTexture=e}set unlit(e){this._material.unlit=e}set geometryOpacity(e){this._material.alpha=e}get geometryOpacity(){return this._material.alpha}set geometryNormalTexture(e){this._material.bumpTexture=e,this._material.forceIrradianceInFragment=!0}get geometryNormalTexture(){return this._material.bumpTexture}setNormalMapInversions(e,t){this._material.invertNormalMapX=e,this._material.invertNormalMapY=t}set geometryCoatNormalTexture(e){this._material.clearCoat.isEnabled=!0,this._material.clearCoat.bumpTexture=e}get geometryCoatNormalTexture(){return this._material.clearCoat.bumpTexture}set geometryCoatNormalTextureScale(e){this._material.clearCoat.bumpTexture&&(this._material.clearCoat.bumpTexture.level=e)}},fa=e({EXT_lights_image_based:()=>ma,RegisterEXT_lights_image_based:()=>ga});wn(),zn(),Dt();var pa=`EXT_lights_image_based`,ma=class{constructor(e){this.name=pa,this._loader=e,this.enabled=this._loader.isExtensionUsed(pa)}dispose(){this._loader=null,delete this._lights}onLoading(){let e=this._loader.gltf.extensions;
4if(e&&e[this.name]){let t=e[this.name];this._lights=t.lights}}loadSceneAsync(e,t){return U.LoadExtensionAsync(e,t,this.name,async(n,r)=>{this._loader._allMaterialsDirtyRequired=!0;let i=[];i.push(this._loader.loadSceneAsync(e,t)),this._loader.logOpen(`${n}`);let a=H.Get(`${n}/light`,this._lights,r.light);return i.push(this._loadLightAsync(`/extensions/${this.name}/lights/${r.light}`,a).then(e=>{this._loader.babylonScene.environmentTexture=e})),this._loader.logClose(),await Promise.all(i).then(()=>{})})}_loadLightAsync(e,t){if(!t._loaded){let n=[];this._loader.logOpen(`${e}`);let r=Array(t.specularImages.length);for(let i=0;i<t.specularImages.length;i++){let a=t.specularImages[i];r[i]=Array(a.length);for(let t=0;t<a.length;t++){let o=`${e}/specularImages/${i}/${t}`;this._loader.logOpen(`${o}`);let s=a[t],c=H.Get(o,this._loader.gltf.images,s);n.push(this._loader.loadImageAsync(`/images/${s}`,c).then(e=>{r[i][t]=e})),this._loader.logClose()}}this._loader.logClose(),t._loaded=Promise.all(n).then(async()=>{let n=new nn(this._loader.babylonScene,null,t.specularImageSize);if(n.name=t.name||`environment`,t._babylonTexture=n,t.intensity!=null&&(n.level=t.intensity),t.rotation){let e=z.FromArray(t.rotation);this._loader.babylonScene.useRightHandedSystem||(e=z.Inverse(e)),L.FromQuaternionToRef(e,n.getReflectionTextureMatrix())}if(!t.irradianceCoefficients)throw Error(`${e}: Irradiance coefficients are missing`);let i=Re.FromArray(t.irradianceCoefficients);i.scaleInPlace(t.intensity),i.convertIrradianceToLambertianRadiance();let a=xn.FromHarmonics(i),o=(r.length-1)/Math.log2(t.specularImageSize);return await n.updateRGBDAsync(r,a,o)})}return t._loaded.then(()=>t._babylonTexture)}},ha=!1;function ga(){ha||(ha=!0,m(pa),r(pa,!0,e=>new ma(e)))}ga();var _a=e({EXT_mesh_gpu_instancing:()=>ya,RegisterEXT_mesh_gpu_instancing:()=>xa});zn(),yt();var va=`EXT_mesh_gpu_instancing`,ya=class{constructor(e){this.name=va,this._loader=e,this.enabled=this._loader.isExtensionUsed(va)}dispose(){this._loader=null}loadNodeAsync(e,t,n){return U.LoadExtensionAsync(e,t,this.name,async(e,r)=>{this._loader._disableInstancedMesh++;let i=this._loader.loadNodeAsync(`/nodes/${t.index}`,t,n);if(this._loader._disableInstancedMesh--,!t._primitiveBabylonMeshes)return await i;let a=[],o=0,s=t=>{if(r.attributes[t]==null){a.push(Promise.resolve(null));return}let n=H.Get(`${e}/attributes/${t}`,this._loader.gltf.accessors,r.attributes[t]);if(a.push(this._loader._loadFloatAccessorAsync(`/accessors/${n.bufferView}`,n)),o===0)o=n.count;else if(o!==n.count)throw Error(`${e}/attributes: Instance buffer accessors do not have the same count.`)};return s(`TRANSLATION`),s(`ROTATION`),s(`SCALE`),s(`_COLOR_0`),await i.then(async e=>{let[n,r,i,s]=await Promise.all(a),c=new Float32Array(o*16);Pn.Vector3[0].copyFromFloats(0,0,0),Pn.Quaternion[0].copyFromFloats(0,0,0,1),Pn.Vector3[1].copyFromFloats(1,1,1);for(let e=0;e<o;++e)n&&R.FromArrayToRef(n,e*3,Pn.Vector3[0]),r&&z.FromArrayToRef(r,e*4,Pn.Quaternion[0]),i&&R.FromArrayToRef(i,e*3,Pn.Vector3[1]),L.ComposeToRef(Pn.Vector3[1],Pn.Quaternion[0],Pn.Vector3[0],Pn.Matrix[0]),Pn.Matrix[0].copyToArray(c,e*16);for(let e of t._primitiveBabylonMeshes)e.thinInstanceSetBuffer(`matrix`,c,16,!0),s&&(s.length===o*3?e.thinInstanceSetBuffer(`color`,s,3,!0):s.length===o*4?e.thinInstanceSetBuffer(`color`,s,4,!0):A.Warn(`Unexpected size of _COLOR_0 attribute for mesh `+e.name));return e})})}},ba=!1;function xa(){ba||(ba=!0,m(va),r(va,!0,e=>new ya(e)))}Wn(),xa(),$t();var Sa=e({EXT_meshopt_compression:()=>wa,RegisterEXT_meshopt_compression:()=>Ea});_n();var Ca=`EXT_meshopt_compression`,wa=class{constructor(e){this.name=Ca,this.enabled=e.isExtensionUsed(Ca),this._loader=e}dispose(){this._loader=null}loadBufferViewAsync(e,t){return U.LoadExtensionAsync(e,t,this.name,async(n,r)=>{let i=t;if(i._meshOptData)return await i._meshOptData;let a=H.Get(`${e}/buffer`,this._loader.gltf.buffers,r.buffer);return i._meshOptData=this._loader.loadBufferAsync(`/buffers/${a.index}`,a,r.byteOffset||0,r.byteLength).then(async e=>await w.Default.decodeGltfBufferAsync(e,r.count,r.byteStride,r.mode,r.filter)),await i._meshOptData})}},Ta=!1;function Ea(){Ta||(Ta=!0,m(Ca),r(Ca,!0,e=>new wa(e)))}Ea();var Da=e({EXT_texture_webp:()=>ka,RegisterEXT_texture_webp:()=>ja}),Oa=`EXT_texture_webp`,ka=class{constructor(e){this.name=Oa,this._loader=e,this.enabled=e.isExtensionUsed(Oa)}dispose(){this._loader=null}_loadTextureAsync(e,t,n){return U.LoadExtensionAsync(e,t,this.name,async(r,i)=>{let a=t.sampler==null?U.DefaultSampler:H.Get(`${e}/sampler`,this._loader.gltf.samplers,t.sampler),o=H.Get(`${r}/source`,this._loader.gltf.images,i.source);return await this._loader._createTextureAsync(e,a,o,e=>{n(e)},void 0,!t._textureInfo.nonColorData,t)})}},Aa=!1;function ja(){Aa||(Aa=!0,m(Oa),r(Oa,!0,e=>new ka(e)))}ja();var Ma=e({EXT_texture_avif:()=>Pa,RegisterEXT_texture_avif:()=>Ia}),Na=`EXT_texture_avif`,Pa=class{constructor(e){this.name=Na,this._loader=e,this.enabled=e.isExtensionUsed(Na)}dispose(){this._loader=null}_loadTextureAsync(e,t,n){return U.LoadExtensionAsync(e,t,this.name,async(r,i)=>{let a=t.sampler==null?U.DefaultSampler:H.Get(`${e}/sampler`,this._loader.gltf.samplers,t.sampler),o=H.Get(`${r}/source`,this._loader.gltf.images,i.source);return await this._loader._createTextureAsync(e,a,o,e=>{n(e)},void 0,!t._textureInfo.nonColorData,t)})}},Fa=!1;function Ia(){Fa||(Fa=!0,m(Na),r(Na,!0,e=>new Pa(e)))}Ia();var La=e({EXT_lights_ies:()=>za,RegisterEXT_lights_ies:()=>Va});zn(),_(),Je(),pr();
4var Ra=`EXT_lights_ies`,za=class{constructor(e){this.name=Ra,this._loader=e,this.enabled=this._loader.isExtensionUsed(Ra)}dispose(){this._loader=null,delete this._lights}onLoading(){let e=this._loader.gltf.extensions;if(e&&e[this.name]){let t=e[this.name];this._lights=t.lights,H.Assign(this._lights)}}loadNodeAsync(e,t,n){return U.LoadExtensionAsync(e,t,this.name,async(r,i)=>{this._loader._allMaterialsDirtyRequired=!0;let a,o,s=await this._loader.loadNodeAsync(e,t,e=>{o=H.Get(r,this._lights,i.light);let t=o.name||e.name;this._loader.babylonScene._blockEntityCollection=!!this._loader._assetContainer,a=new Ct(t,R.Zero(),R.Backward(),0,1,this._loader.babylonScene),a.angle=Math.PI/2,a.innerAngle=0,a._parentContainer=this._loader._assetContainer,this._loader.babylonScene._blockEntityCollection=!1,o._babylonLight=a,a.falloffType=h.FALLOFF_GLTF,a.diffuse=i.color?N.FromArray(i.color):N.White(),a.intensity=i.multiplier||1,a.range=Number.MAX_VALUE,a.parent=e,this._loader._babylonLights.push(a),U.AddPointerMetadata(a,r),n(e)}),c;if(o.uri)c=await this._loader.loadUriAsync(e,o,o.uri);else{let t=H.Get(`${e}/bufferView`,this._loader.gltf.bufferViews,o.bufferView);c=await this._loader.loadBufferViewAsync(`/bufferViews/${t.index}`,t)}return a.iesProfileTexture=new I(a.name+`_iesProfile`,this._loader.babylonScene,!0,!1,void 0,null,null,c,!0,void 0,void 0,void 0,void 0,`.ies`),s})}},Ba=!1;function Va(){Ba||(Ba=!0,m(Ra),r(Ra,!0,e=>new za(e)))}Va();var Ha=e({KHR_draco_mesh_compression:()=>Wa,RegisterKHR_draco_mesh_compression:()=>Ka});Pe(),le();var Ua=`KHR_draco_mesh_compression`,Wa=class{constructor(e){this.name=Ua,this.useNormalizedFlagFromAccessor=!0,this._loader=e,this.enabled=ke.DefaultAvailable&&this._loader.isExtensionUsed(Ua)}dispose(){delete this.dracoDecoder,this._loader=null}_loadVertexDataAsync(e,t,n){return U.LoadExtensionAsync(e,t,this.name,async(r,i)=>{if(t.mode!=null&&t.mode!==4&&t.mode!==5)throw Error(`${e}: Unsupported mode ${t.mode}`);let a={},o={},s=(e,r)=>{let s=i.attributes[e];if(s!=null&&(n._delayInfo=n._delayInfo||[],n._delayInfo.indexOf(r)===-1&&n._delayInfo.push(r),a[r]=s,this.useNormalizedFlagFromAccessor)){let n=H.TryGet(this._loader.gltf.accessors,t.attributes[e]);n&&(o[r]=n.normalized||!1)}};s(`POSITION`,j.PositionKind),s(`NORMAL`,j.NormalKind),s(`TANGENT`,j.TangentKind),s(`TEXCOORD_0`,j.UVKind),s(`TEXCOORD_1`,j.UV2Kind),s(`TEXCOORD_2`,j.UV3Kind),s(`TEXCOORD_3`,j.UV4Kind),s(`TEXCOORD_4`,j.UV5Kind),s(`TEXCOORD_5`,j.UV6Kind),s(`JOINTS_0`,j.MatricesIndicesKind),s(`WEIGHTS_0`,j.MatricesWeightsKind),s(`COLOR_0`,j.ColorKind);let c=H.Get(r,this._loader.gltf.bufferViews,i.bufferView);return c._dracoBabylonGeometry||=this._loader.loadBufferViewAsync(`/bufferViews/${c.index}`,c).then(async r=>{let i=this.dracoDecoder||ke.Default,s=H.TryGet(this._loader.gltf.accessors,t.attributes.POSITION),c=!this._loader.parent.alwaysComputeBoundingBox&&!n.skeleton&&s?Xi(s):null;return await i._decodeMeshToGeometryForGltfAsync(n.name,this._loader.babylonScene,r,a,o,c).catch(t=>{throw Error(`${e}: ${t.message}`)})}),await c._dracoBabylonGeometry})}},Ga=!1;function Ka(){Ga||(Ga=!0,m(Ua),r(Ua,!0,e=>new Wa(e)))}Ka();var qa=e({KHR_gaussian_splatting:()=>no,RegisterKHR_gaussian_splatting:()=>io});En(),Zt();var Ja=`KHR_gaussian_splatting`,Ya=.28209479177387814,Xa=`KHR_gaussian_splatting:ROTATION`,Za=`KHR_gaussian_splatting:SCALE`,Qa=`KHR_gaussian_splatting:OPACITY`,$a=`KHR_gaussian_splatting:SH_DEGREE_0_COEF_0`,eo=[0,3,5,7];function to(e){return e<=0?0:e>=255?255:e+.5|0}var no=class{constructor(e){this.name=Ja,this._loader=e,this.enabled=this._loader.isExtensionUsed(Ja)}dispose(){this._loader=null}_loadMeshPrimitiveAsync(e,t,n,r,i,a){return U.LoadExtensionAsync(e,i,this.name,async n=>{if(i.mode!=null&&i.mode!==0)throw Error(`${n}: Gaussian splatting primitives must use POINTS mode`);let r=this._loader,o=t=>{let n=i.attributes[t];if(n==null)return null;let a=H.Get(`${e}/attributes/${t}`,r.gltf.accessors,n);return r._loadFloatAccessorAsync(`/accessors/${a.index}`,a)},s=o(`POSITION`);if(!s)throw Error(`${n}: Gaussian splatting primitive is missing the POSITION attribute`);let c=0,l=[];for(let e=1;e<=3&&i.attributes[`KHR_gaussian_splatting:SH_DEGREE_${e}_COEF_0`]!=null;e++){c=e;for(let t=0;t<eo[e];t++)l.push(`KHR_gaussian_splatting:SH_DEGREE_${e}_COEF_${t}`)}let u=r.babylonScene;u._blockEntityCollection=!!r._assetContainer;let d=new Bt(t,null,u);d._parentContainer=r._assetContainer,u._blockEntityCollection=!1,U.AddPointerMetadata(d,e),r.parent.onMeshLoadedObservable.notifyObservers(d),a(d);let f=u.getEngine().getCaps(),[p,m,h,g,_,v,...y]=await Promise.all([s,o(Xa),o(Za),o(Qa),o($a),o(`COLOR_0`),...l.map(e=>o(e))]),b=p.length/3,x=v?v.length/b:0,S=new ArrayBuffer(32*b),C=new Float32Array(S),w=new Uint8Array(S),T=null;if(c>
40){let e=((c+1)*(c+1)-1)*3,t=Math.ceil(e/16),n=f.maxTextureSize,r=Math.ceil(b/n);T=Ht(t,r*n*4*4)}for(let e=0;e<b;e++){let t=e*8,n=e*32,r=e*3;if(C[t+0]=p[r+0],C[t+1]=p[r+1],C[t+2]=p[r+2],C[t+3]=h?h[r+0]:1,C[t+4]=h?h[r+1]:1,C[t+5]=h?h[r+2]:1,_)w[n+24]=to((.5+Ya*_[r+0])*255),w[n+25]=to((.5+Ya*_[r+1])*255),w[n+26]=to((.5+Ya*_[r+2])*255);else if(v){let t=e*x;w[n+24]=to(v[t+0]*255),w[n+25]=to(v[t+1]*255),w[n+26]=to(v[t+2]*255)}else w[n+24]=255,w[n+25]=255,w[n+26]=255;g?w[n+27]=to(g[e]*255):v&&x>=4?w[n+27]=to(v[e*x+3]*255):w[n+27]=255;let i=e*4,a=m?m[i+0]:0,o=m?m[i+1]:0,s=m?m[i+2]:0,c=m?m[i+3]:1;if(w[n+28]=to(c*127.5+127.5),w[n+29]=to(a*127.5+127.5),w[n+30]=to(o*127.5+127.5),w[n+31]=to(s*127.5+127.5),T){let t=e*16;for(let e=0;e<y.length;e++){let n=y[e];if(n)for(let i=0;i<3;i++){let a=e*3+i,o=a>>4,s=a&15;T[o][t+s]=to(n[r+i]*128+128)}}}}return await d.updateDataAsync(S,T??void 0,void 0,c||void 0),d})}},ro=!1;function io(){ro||(ro=!0,m(Ja),r(Ja,!0,e=>new no(e)))}io(),Qe();var ao=e({KHR_lights:()=>so,RegisterKHR_lights:()=>lo});zn(),_(),_r(),vr(),Je(),Kt();var oo=`KHR_lights_punctual`,so=class{constructor(e){this.name=oo,this._loader=e,this.enabled=this._loader.isExtensionUsed(oo)}dispose(){this._loader=null,delete this._lights}onLoading(){let e=this._loader.gltf.extensions;if(e&&e[this.name]){let t=e[this.name];this._lights=t.lights,H.Assign(this._lights)}}loadNodeAsync(e,t,n){return U.LoadExtensionAsync(e,t,this.name,async(r,i)=>(this._loader._allMaterialsDirtyRequired=!0,await this._loader.loadNodeAsync(e,t,e=>{let t,a=H.Get(r,this._lights,i.light),o=a.name||e.name;switch(this._loader.babylonScene._blockEntityCollection=!!this._loader._assetContainer,a.type){case`directional`:{let e=new Ot(o,R.Backward(),this._loader.babylonScene);e.position.setAll(0),t=e;break}case`point`:t=new O(o,R.Zero(),this._loader.babylonScene);break;case`spot`:{let e=new Ct(o,R.Zero(),R.Backward(),0,1,this._loader.babylonScene);e.angle=(a.spot&&a.spot.outerConeAngle||Math.PI/4)*2,e.innerAngle=(a.spot&&a.spot.innerConeAngle||0)*2,t=e;break}default:throw this._loader.babylonScene._blockEntityCollection=!1,Error(`${r}: Invalid light type (${a.type})`)}t._parentContainer=this._loader._assetContainer,this._loader.babylonScene._blockEntityCollection=!1,a._babylonLight=t,t.falloffType=h.FALLOFF_GLTF,t.diffuse=a.color?N.FromArray(a.color):N.White(),t.intensity=a.intensity==null?1:a.intensity,t.range=a.range==null?Number.MAX_VALUE:a.range,t.parent=e,this._loader._babylonLights.push(t),U.AddPointerMetadata(t,r),n(e)})))}},co=!1;function lo(){co||(co=!0,m(oo),r(oo,!0,e=>new so(e)))}lo();var uo=e({EXT_lights_area:()=>po,RegisterEXT_lights_area:()=>ho});zn(),_(),Kt(),It(),g();var fo=`EXT_lights_area`,po=class{constructor(e){this.name=fo,this._loader=e,this.enabled=this._loader.isExtensionUsed(fo)}dispose(){this._loader=null,delete this._lights}onLoading(){let e=this._loader.gltf.extensions;if(e&&e[this.name]){let t=e[this.name];this._lights=t.lights,H.Assign(this._lights)}}loadNodeAsync(e,t,n){return U.LoadExtensionAsync(e,t,this.name,async(r,i)=>(this._loader._allMaterialsDirtyRequired=!0,await this._loader.loadNodeAsync(e,t,e=>{let t,a=H.Get(r,this._lights,i.light),o=a.name||e.name;this._loader.babylonScene._blockEntityCollection=!!this._loader._assetContainer;let s=a.size===void 0?1:a.size;switch(a.type){case`rect`:{let e=a.rect?.aspect===void 0?s:a.rect.aspect*s,n=s;t=new wr(o,R.Zero(),e,n,this._loader.babylonScene);break}case`disk`:{let e=Math.sqrt(s*s*.25*Math.PI);t=new wr(o,R.Zero(),e,e,this._loader.babylonScene);break}default:throw this._loader.babylonScene._blockEntityCollection=!1,Error(`${r}: Invalid area light type (${a.type})`)}t._parentContainer=this._loader._assetContainer,this._loader.babylonScene._blockEntityCollection=!1,a._babylonLight=t,t.falloffType=h.FALLOFF_GLTF,t.diffuse=a.color?N.FromArray(a.color):N.White(),t.intensity=a.intensity==null?1:a.intensity;let c=new Ge(`${o}_orientation`,this._loader.babylonScene);c.rotationQuaternion=z.RotationAxis(R.Up(),Math.PI),c.parent=e,t.parent=c,this._loader._babylonLights.push(t),U.AddPointerMetadata(t,r),n(e)})))}},mo=!1;function ho(){mo||(mo=!0,m(fo),r(fo,!0,e=>new po(e)))}ho();var go=e({KHR_materials_pbrSpecularGlossiness:()=>vo,RegisterKHR_materials_pbrSpecularGlossiness:()=>bo});_();var _o=`KHR_materials_pbrSpecularGlossiness`,vo=class{constructor(e){this.name=_o,this.order=200,this._loader=e,this.enabled=this._loader.isExtensionUsed(_o)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return U.LoadExtensionAsync(e,t,this.name,async(r,i)=>{let a=[];return a.push(this._loader.loadMaterialBasePropertiesAsync(e,t,n)),a.push(this._loadSpecularGlossinessPropertiesAsync(r,i,n)),this._loader.loadMaterialAlphaProperties(e,t,n),await Promise.all(a).then(()=>{})})}_loadSpecularGlossinessPropertiesAsync(e,t,n){let r=this._loader._getOrCreateMaterialAdapter(n),i=[];return r.configureSpecularGlossiness(),t.diffuseFactor?(r.baseColor=N.FromArray(t.diffuseFactor),n.alpha=t.diffuseFactor[3]):r.baseColor=N.White(),r.specularColor=t.specularFactor?N.FromArray(t.specularFactor):N.White(),r.glossiness=t.glossinessFactor==null?1:t.glossinessFactor,t.diffuseTexture&&i.push(this._loader.loadTextureInfoA
4sync(`${e}/diffuseTexture`,t.diffuseTexture,e=>{e.name=`${n.name} (Diffuse)`,r.baseColorTexture=e})),t.specularGlossinessTexture&&i.push(this._loader.loadTextureInfoAsync(`${e}/specularGlossinessTexture`,t.specularGlossinessTexture,e=>{e.name=`${n.name} (Specular Glossiness)`,r.specularColorTexture=e})),Promise.all(i).then(()=>{})}},yo=!1;function bo(){yo||(yo=!0,m(_o),r(_o,!0,e=>new vo(e)))}bo();var xo=e({KHR_materials_unlit:()=>Co,RegisterKHR_materials_unlit:()=>To});_();var So=`KHR_materials_unlit`,Co=class{constructor(e){this.name=So,this.order=210,this._loader=e,this.enabled=this._loader.isExtensionUsed(So)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return U.LoadExtensionAsync(e,t,this.name,async()=>await this._loadUnlitPropertiesAsync(e,t,n))}_loadUnlitPropertiesAsync(e,t,n){let r=this._loader._getOrCreateMaterialAdapter(n),i=[],a=t.pbrMetallicRoughness;return a&&(a.baseColorFactor&&(r.baseColor=N.FromArray(a.baseColorFactor),r.geometryOpacity=a.baseColorFactor[3]),a.baseColorTexture&&i.push(this._loader.loadTextureInfoAsync(`${e}/baseColorTexture`,a.baseColorTexture,e=>{e.name=`${n.name} (Base Color)`,r.baseColorTexture=e}))),r.isUnlit=!0,t.doubleSided&&(r.backFaceCulling=!1,r.twoSidedLighting=!0),this._loader.loadMaterialAlphaProperties(e,t,n),Promise.all(i).then(()=>{})}},wo=!1;function To(){wo||(wo=!0,m(So),r(So,!0,e=>new Co(e)))}To();var Eo=e({KHR_materials_clearcoat:()=>Oo,RegisterKHR_materials_clearcoat:()=>Ao}),Do=`KHR_materials_clearcoat`,Oo=class{constructor(e){this.name=Do,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(Do)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return U.LoadExtensionAsync(e,t,this.name,async(r,i)=>{let a=[];a.push(this._loader.loadMaterialPropertiesAsync(e,t,n)),a.push(this._loadClearCoatPropertiesAsync(r,i,n)),await Promise.all(a)})}_loadClearCoatPropertiesAsync(e,t,n){let r=this._loader._getOrCreateMaterialAdapter(n),i=[];return r.configureCoat(),r.coatWeight=t.clearcoatFactor===void 0?0:t.clearcoatFactor,r.coatRoughness=t.clearcoatRoughnessFactor===void 0?0:t.clearcoatRoughnessFactor,t.clearcoatTexture&&i.push(this._loader.loadTextureInfoAsync(`${e}/clearcoatTexture`,t.clearcoatTexture,e=>{e.name=`${n.name} (ClearCoat)`,r.coatWeightTexture=e})),t.clearcoatRoughnessTexture&&(t.clearcoatRoughnessTexture.nonColorData=!0,i.push(this._loader.loadTextureInfoAsync(`${e}/clearcoatRoughnessTexture`,t.clearcoatRoughnessTexture,e=>{e.name=`${n.name} (ClearCoat Roughness)`,r.coatRoughnessTexture=e}))),t.clearcoatNormalTexture&&(t.clearcoatNormalTexture.nonColorData=!0,i.push(this._loader.loadTextureInfoAsync(`${e}/clearcoatNormalTexture`,t.clearcoatNormalTexture,e=>{e.name=`${n.name} (ClearCoat Normal)`,r.geometryCoatNormalTexture=e,t.clearcoatNormalTexture?.scale!=null&&(r.geometryCoatNormalTextureScale=t.clearcoatNormalTexture.scale)})),r.setNormalMapInversions(!n.getScene().useRightHandedSystem,n.getScene().useRightHandedSystem)),Promise.all(i).then(()=>{})}},ko=!1;function Ao(){ko||(ko=!0,m(Do),r(Do,!0,e=>new Oo(e)))}Ao();var jo=e({KHR_materials_coat:()=>No,RegisterKHR_materials_coat:()=>Fo});_();var Mo=`KHR_materials_coat`,No=class{constructor(e){this.name=Mo,this.order=191,this.useOpenPBR=!1,this._loader=e,this.enabled=this._loader.isExtensionUsed(Mo)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return U.LoadExtensionAsync(e,t,this.name,async(r,i)=>{let a=[];a.push(this._loader.loadMaterialPropertiesAsync(e,t,n)),t.extensions&&t.extensions.KHR_materials_openpbr&&(this.useOpenPBR=!0),a.push(this._loadCoatPropertiesAsync(r,i,n)),await Promise.all(a)})}_loadCoatPropertiesAsync(e,t,n){let r=this._loader._getOrCreateMaterialAdapter(n),i=[];r.configureCoat(),r.coatWeight=t.coatFactor===void 0?0:t.coatFactor,r.coatRoughness=t.coatRoughnessFactor===void 0?0:t.coatRoughnessFactor,t.coatTexture&&i.push(this._loader.loadTextureInfoAsync(`${e}/coatTexture`,t.coatTexture,e=>{e.name=`${n.name} (Coat)`,r.coatWeightTexture=e})),t.coatRoughnessTexture&&(t.coatRoughnessTexture.nonColorData=!0,i.push(this._loader.loadTextureInfoA
4sync(`${e}/coatRoughnessTexture`,t.coatRoughnessTexture,e=>{e.name=`${n.name} (Coat Roughness)`,r.coatRoughnessTexture=e}))),t.coatNormalTexture&&(t.coatNormalTexture.nonColorData=!0,i.push(this._loader.loadTextureInfoAsync(`${e}/coatNormalTexture`,t.coatNormalTexture,e=>{e.name=`${n.name} (Coat Normal)`,r.geometryCoatNormalTexture=e,t.coatNormalTexture?.scale!=null&&(r.geometryCoatNormalTextureScale=t.coatNormalTexture.scale)})),r.setNormalMapInversions(!n.getScene().useRightHandedSystem,n.getScene().useRightHandedSystem)),r.coatDarkening=t.coatDarkeningFactor===void 0?1:t.coatDarkeningFactor,r.coatIor=t.coatIor===void 0?1.5:t.coatIor;let a=N.White();t.coatColorFactor!==void 0&&a.fromArray(t.coatColorFactor),r.coatColor=a,t.coatColorTexture&&i.push(this._loader.loadTextureInfoAsync(`${e}/coatColorTexture`,t.coatColorTexture,e=>{e.name=`${n.name} (Coat Color)`,r.coatColorTexture=e}));let o=t.coatAnisotropyStrength??0,s=t.coatAnisotropyRotation??0;return r.coatRoughnessAnisotropy=o,r.geometryCoatTangentAngle=s,this.useOpenPBR||r.configureGltfStyleAnisotropy(!0),t.coatAnisotropyTexture&&(t.coatAnisotropyTexture.nonColorData=!0,i.push(this._loader.loadTextureInfoAsync(`${e}/coatAnisotropyTexture`,t.coatAnisotropyTexture,e=>{e.name=`${n.name} (Coat Anisotropy)`,r.geometryCoatTangentTexture=e}))),Promise.all(i).then(()=>{})}},Po=!1;function Fo(){Po||(Po=!0,m(Mo),r(Mo,!0,e=>new No(e)))}Fo();var Io=e({KHR_materials_iridescence:()=>Ro,RegisterKHR_materials_iridescence:()=>Bo}),Lo=`KHR_materials_iridescence`,Ro=class{constructor(e){this.name=Lo,this.order=195,this._loader=e,this.enabled=this._loader.isExtensionUsed(Lo)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return U.LoadExtensionAsync(e,t,this.name,async(r,i)=>{let a=[];return a.push(this._loader.loadMaterialPropertiesAsync(e,t,n)),a.push(this._loadIridescencePropertiesAsync(r,i,n)),await Promise.all(a).then(()=>{})})}_loadIridescencePropertiesAsync(e,t,n){let r=this._loader._getOrCreateMaterialAdapter(n),i=[];return r.thinFilmWeight=t.iridescenceFactor??0,r.thinFilmIor=t.iridescenceIor??t.iridescenceIOR??1.3,r.thinFilmThicknessMinimum=t.iridescenceThicknessMinimum??100,r.thinFilmThicknessMaximum=t.iridescenceThicknessMaximum??400,t.iridescenceTexture&&i.push(this._loader.loadTextureInfoAsync(`${e}/iridescenceTexture`,t.iridescenceTexture,e=>{e.name=`${n.name} (Iridescence)`,r.thinFilmWeightTexture=e})),t.iridescenceThicknessTexture&&i.push(this._loader.loadTextureInfoAsync(`${e}/iridescenceThicknessTexture`,t.iridescenceThicknessTexture,e=>{e.name=`${n.name} (Iridescence Thickness)`,r.thinFilmThicknessTexture=e})),Promise.all(i).then(()=>{})}},zo=!1;function Bo(){zo||(zo=!0,m(Lo),r(Lo,!0,e=>new Ro(e)))}Bo();var Vo=e({KHR_materials_anisotropy:()=>Uo,RegisterKHR_materials_anisotropy:()=>Go}),Ho=`KHR_materials_anisotropy`,Uo=class{constructor(e){this.name=Ho,this.order=195,this._loader=e,this.enabled=this._loader.isExtensionUsed(Ho)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return U.LoadExtensionAsync(e,t,this.name,async(r,i)=>{let a=[];a.push(this._loader.loadMaterialPropertiesAsync(e,t,n)),a.push(this._loadAnisotropyPropertiesAsync(r,i,n)),await Promise.all(a)})}async _loadAnisotropyPropertiesAsync(e,t,n){let r=this._loader._getOrCreateMaterialAdapter(n),i=[],a=t.anisotropyStrength??0,o=t.anisotropyRotation??0;r.specularRoughnessAnisotropy=a,r.geometryTangentAngle=o;let s=t.extensions??{};(!s.EXT_materials_anisotropy_openpbr||!s.EXT_materials_anisotropy_openpbr.openPbrAnisotropyEnabled)&&r.configureGltfStyleAnisotropy(!0),t.anisotropyTexture&&(t.anisotropyTexture.nonColorData=!0,i.push(this._loader.loadTextureInfoAsync(`${e}/anisotropyTexture`,t.anisotropyTexture,e=>{e.name=`${n.name} (Anisotropy Intensity)`,r.geometryTangentTexture=e}))),await Promise.all(i)}},Wo=!1;function Go(){Wo||(Wo=!0,m(Ho),r(Ho,!0,e=>new Uo(e)))}Go();var Ko=e({KHR_materials_emissive_strength:()=>Jo,RegisterKHR_materials_emissive_strength:()=>Xo}),qo=`KHR_materials_emissive_strength`,Jo=class{constructor(e){this.name=qo,this.order=170,this._loader=e,this.enabled=this._loader.isExtensionUsed(qo)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return U.LoadExtensionAsync(e,t,this.name,async(r,i)=>(await this._loader.loadMaterialPropertiesAsync(e,t,n),this._loadEmissiveProperties(r,i,n),await Promise.resolve()))}_loadEmissiveProperties(e,t,n){if(t.emissiveStrength!==void 0){let e=this._loader._getOrCreateMaterialAdapter(n);e.emissionLuminance=t.emissiveStrength}}},Yo=!1;function Xo(){Yo||(Yo=!0,m(qo),r(qo,!0,e=>new Jo(e)))}Xo();var Zo=e({KHR_materials_sheen:()=>$o,RegisterKHR_materials_sheen:()=>ts});_();var Qo=`KHR_materials_sheen`,$o=class{constructor(e){this.name=Qo,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(Qo)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return U.LoadExtensionAsync(e,t,this.name,async(r,i)=>{let a=[];return a.push(this._loader.loadMaterialPropertiesAsync(e,t,n)),a.push(this._loadSheenPropertiesAsync(r,i,n)),await Promise.all(a).then(()=>{})})}_loadSheenPropertiesAsync(e,t,n){let r=this._loader._getOrCreateMaterialAdapter(n),i=[];r.configureFuzz();let a=t.sheenColorFactor===void 0?N.Black():N.FromArray(t.sheenColorFactor),o=t.sheenRoughnessFactor===void 0?0:t.sheenRoughnessFactor;return r.fuzzWeight=1,r.fuzzColor=a,r.fuzzRoughness=o,t.sheenColorTexture&&i.push(this._loader.loadTextureInfoA
4sync(`${e}/sheenColorTexture`,t.sheenColorTexture,e=>{e.name=`${n.name} (Sheen Color)`,r.fuzzColorTexture=e})),t.sheenRoughnessTexture&&(t.sheenRoughnessTexture.nonColorData=!0,i.push(this._loader.loadTextureInfoAsync(`${e}/sheenRoughnessTexture`,t.sheenRoughnessTexture,e=>{e.name=`${n.name} (Sheen Roughness)`,r.fuzzRoughnessTexture=e}))),Promise.all(i).then(()=>{})}},es=!1;function ts(){es||(es=!0,m(Qo),r(Qo,!0,e=>new $o(e)))}ts();var ns=e({KHR_materials_fuzz:()=>is,RegisterKHR_materials_fuzz:()=>os});_();var rs=`KHR_materials_fuzz`,is=class{constructor(e){this.name=rs,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(rs)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return U.LoadExtensionAsync(e,t,this.name,async(r,i)=>{let a=[];return a.push(this._loader.loadMaterialPropertiesAsync(e,t,n)),a.push(this._loadFuzzPropertiesAsync(r,i,n)),await Promise.all(a).then(()=>{})})}_loadFuzzPropertiesAsync(e,t,n){let r=this._loader._getOrCreateMaterialAdapter(n),i=[];return r.configureFuzz(),r.fuzzWeight=t.fuzzFactor===void 0?0:t.fuzzFactor,r.fuzzColor=t.fuzzColorFactor===void 0?N.White():N.FromArray(t.fuzzColorFactor),r.fuzzRoughness=t.fuzzRoughnessFactor===void 0?.5:t.fuzzRoughnessFactor,t.fuzzTexture&&i.push(this._loader.loadTextureInfoAsync(`${e}/fuzzTexture`,t.fuzzTexture,e=>{e.name=`${n.name} (Fuzz)`,r.fuzzWeightTexture=e})),t.fuzzColorTexture&&i.push(this._loader.loadTextureInfoAsync(`${e}/fuzzColorTexture`,t.fuzzColorTexture,e=>{e.name=`${n.name} (Fuzz Color)`,r.fuzzColorTexture=e})),t.fuzzRoughnessTexture&&(t.fuzzRoughnessTexture.nonColorData=!0,i.push(this._loader.loadTextureInfoAsync(`${e}/fuzzRoughnessTexture`,t.fuzzRoughnessTexture,e=>{e.name=`${n.name} (Fuzz Roughness)`,r.fuzzRoughnessTexture=e}))),Promise.all(i).then(()=>{})}},as=!1;function os(){as||(as=!0,m(rs),r(rs,!0,e=>new is(e)))}os();var ss=e({KHR_materials_specular:()=>ls,RegisterKHR_materials_specular:()=>ds});_();var cs=`KHR_materials_specular`,ls=class{constructor(e){this.name=cs,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(cs)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return U.LoadExtensionAsync(e,t,this.name,async(r,i)=>{let a=[];a.push(this._loader.loadMaterialPropertiesAsync(e,t,n)),a.push(this._loadSpecularPropertiesAsync(r,i,n));let o=this._loader._getOrCreateMaterialAdapter(n);return i.extensions&&i.extensions.EXT_materials_specular_edge_color&&i.extensions.EXT_materials_specular_edge_color.specularEdgeColorEnabled&&o.enableSpecularEdgeColor(!0),await Promise.all(a).then(()=>{})})}_loadSpecularPropertiesAsync(e,t,n){let r=this._loader._getOrCreateMaterialAdapter(n),i=[];return r.specularWeight=t.specularFactor??1,r.specularColor=t.specularColorFactor===void 0?new N(1,1,1):N.FromArray(t.specularColorFactor),t.specularTexture&&(t.specularTexture.nonColorData=!0,i.push(this._loader.loadTextureInfoAsync(`${e}/specularTexture`,t.specularTexture,e=>{e.name=`${n.name} (Specular)`,r.specularWeightTexture=e}))),t.specularColorTexture&&i.push(this._loader.loadTextureInfoAsync(`${e}/specularColorTexture`,t.specularColorTexture,e=>{e.name=`${n.name} (Specular Color)`,r.specularColorTexture=e})),Promise.all(i).then(()=>{})}},us=!1;function ds(){us||(us=!0,m(cs),r(cs,!0,e=>new ls(e)))}ds();var fs=e({KHR_materials_ior:()=>ms,RegisterKHR_materials_ior:()=>gs}),ps=`KHR_materials_ior`,ms=class e{constructor(e){this.name=ps,this.order=180,this._loader=e,this.enabled=this._loader.isExtensionUsed(ps)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return U.LoadExtensionAsync(e,t,this.name,async(r,i)=>{let a=[];return a.push(this._loader.loadMaterialPropertiesAsync(e,t,n)),a.push(this._loadIorPropertiesAsync(r,i,n)),await Promise.all(a).then(()=>{})})}_loadIorPropertiesAsync(t,n,r){let i=this._loader._getOrCreateMaterialAdapter(r);return i.specularIor=n.ior===void 0?e._DEFAULT_IOR:n.ior,Promise.resolve()}};ms._DEFAULT_IOR=1.5;var hs=!1;function gs(){hs||(hs=!0,m(ps),r(ps,!0,e=>new ms(e)))}gs();var _s=e({KHR_materials_variants:()=>ys,RegisterKHR_materials_variants:()=>xs});Rn();var vs=`KHR_materials_variants`,ys=class e{constructor(e){this.name=vs,this._loader=e,this.enabled=this._loader.isExtensionUsed(vs)&&!this._loader.parent.skipMaterials}dispose(){this._loader=null}static GetAvailableVariants(e){let t=this._GetExtensionMetadata(e);return t?Object.keys(t.variants):[]}getAvailableVariants(t){return e.GetAvailableVariants(t)}static SelectVariant(e,t){let n=this._GetExtensionMetadata(e);if(!n)throw Error(`Cannot select variant on a glTF mesh that does not have the ${vs} extension`);let r=e=>{let t=n.variants[e];if(t)for(let e of t)e.mesh.material=e.material};if(t instanceof Array)for(let e of t)r(e);else r(t);n.lastSelected=t}selectVariant(t,n){e.SelectVariant(t,n)}static Reset(e){let t=this._GetExtensionMetadata(e);if(!t)throw Error(`Cannot reset on a glTF mesh that does not have the ${vs} extension`);for(let e of t.original)e.mesh.material=e.material;t.lastSelected=null}reset(t){e.Reset(t)}static GetLastSelectedVariant(e){let t=this._GetExtensionMetadata(e);if(!t)throw Error(`Cannot get the last selected variant on a glTF mesh that does not have the ${vs} extension`);return t.lastSelected}
4getLastSelectedVariant(t){return e.GetLastSelectedVariant(t)}static _GetExtensionMetadata(e){return e?._internalMetadata?.gltf?.[vs]||null}onLoading(){let e=this._loader.gltf.extensions;if(e&&e[this.name]){let t=e[this.name];this._variants=t.variants}}onReady(){let t=this._loader.rootBabylonMesh;if(t){let n=this._loader.parent.extensionOptions[vs];n?.defaultVariant&&e.SelectVariant(t,n.defaultVariant),n?.onLoaded?.({get variants(){return e.GetAvailableVariants(t)},get selectedVariant(){let n=e.GetLastSelectedVariant(t);return n?Array.isArray(n)?n[0]:n:e.GetAvailableVariants(t)[0]},set selectedVariant(n){e.SelectVariant(t,n)}})}}_loadMeshPrimitiveAsync(t,n,r,i,a,o){return U.LoadExtensionAsync(t,a,this.name,async(s,c)=>{let l=[];return l.push(this._loader._loadMeshPrimitiveAsync(t,n,r,i,a,n=>{if(o(n),n instanceof At){let r=U._GetDrawMode(t,a.mode),i=this._loader.rootBabylonMesh,o=i?i._internalMetadata=i._internalMetadata||{}:{},u=o.gltf=o.gltf||{},d=u[vs]=u[vs]||{lastSelected:null,original:[],variants:{}};d.original.push({mesh:n,material:n.material});for(let t=0;t<c.mappings.length;++t){let a=c.mappings[t],o=H.Get(`${s}/mappings/${t}/material`,this._loader.gltf.materials,a.material);l.push(this._loader._loadMaterialAsync(`#/materials/${a.material}`,o,n,r,t=>{for(let r=0;r<a.variants.length;++r){let o=a.variants[r],s=H.Get(`/extensions/${vs}/variants/${o}`,this._variants,o);d.variants[s.name]=d.variants[s.name]||[],d.variants[s.name].push({mesh:n,material:t}),n.onClonedObservable.add(t=>{let r=t,a,o=r;do{if(o=o.parent,!o)return;a=e._GetExtensionMetadata(o)}while(a===null);if(i&&a===e._GetExtensionMetadata(i)){o._internalMetadata={};for(let e in i._internalMetadata)o._internalMetadata[e]=i._internalMetadata[e];o._internalMetadata.gltf=[];for(let e in i._internalMetadata.gltf)o._internalMetadata.gltf[e]=i._internalMetadata.gltf[e];o._internalMetadata.gltf[vs]={lastSelected:null,original:[],variants:{}};for(let e of a.original)o._internalMetadata.gltf[vs].original.push({mesh:e.mesh,material:e.material});for(let e in a.variants)if(Object.prototype.hasOwnProperty.call(a.variants,e)){o._internalMetadata.gltf[vs].variants[e]=[];for(let t of a.variants[e])o._internalMetadata.gltf[vs].variants[e].push({mesh:t.mesh,material:t.material})}a=o._internalMetadata.gltf[vs]}for(let e of a.original)e.mesh===n&&(e.mesh=r);for(let e of a.variants[s.name])e.mesh===n&&(e.mesh=r)})}}))}}})),await Promise.all(l).then(([e])=>e)})}},bs=!1;function xs(){bs||(bs=!0,m(vs),r(vs,!0,e=>new ys(e)))}xs(),gt(),ln(),Se(),Ze();var Ss=class e{static _GetDefaultOptions(){return{renderSize:1024,samples:4,lodGenerationScale:1,lodGenerationOffset:-4,renderTargetTextureType:k.TEXTURETYPE_HALF_FLOAT,generateMipmaps:!0}}constructor(t,n){this._opaqueRenderTarget=null,this._opaqueMeshesCache=[],this._transparentMeshesCache=[],this._materialObservers={},this._newMeshObserver=null,this._removedMeshObserver=null,this._disposed=!1,this._materialImpls=[],this._adapterCache=new WeakMap,this._translucentMaterialIndices=new Map,this._opaqueOnlySubMeshes=new Map,this._savedSubMeshes=new Map,this._options={...e._GetDefaultOptions(),...t},this._scene=n,this._scene._transmissionHelper=this,this.onErrorObservable=new yr,this._scene.onDisposeObservable.addOnce(()=>{this.dispose()}),this._parseScene(),this._setupRenderTargets()}addMaterialImpl(e){this._materialImpls.some(t=>t.materialClass===e.materialClass)||this._materialImpls.push(e)}updateOptions(e){if(!Object.keys(e).filter(t=>this._options[t]!==e[t]).length)return;let t={...this._options,...e},n=this._options;this._options=t,t.renderSize!==n.renderSize||t.renderTargetTextureType!==n.renderTargetTextureType||t.generateMipmaps!==n.generateMipmaps||!this._opaqueRenderTarget?this._setupRenderTargets():(this._opaqueRenderTarget.samples=t.samples,this._opaqueRenderTarget.lodGenerationScale=t.lodGenerationScale,this._opaqueRenderTarget.lodGenerationOffset=t.lodGenerationOffset)}getOpaqueTarget(){return this._opaqueRenderTarget}_getOrCreateAdapter(e){let t=this._adapterCache.get(e);if(!t){for(let n of this._materialImpls)if(e instanceof n.materialClass){t=new n.adapterClass(e),this._adapterCache.set(e,t);break}}return t}_classifyMeshMaterials(e){let t=e.material;if(!t)return`opaque`;if(!(t instanceof er)){let e=this._getOrCreateAdapter(t);
4return e&&e.isTranslucent()?(e.refractionBackgroundTexture=this._opaqueRenderTarget,`transparent`):`opaque`}let n=!1,r=!1,i=new Set;for(let e=0;e<t.subMaterials.length;e++){let a=t.subMaterials[e];if(!a){r=!0;continue}let o=this._getOrCreateAdapter(a);o&&o.isTranslucent()?(o.refractionBackgroundTexture=this._opaqueRenderTarget,n=!0,i.add(e)):r=!0}return n&&r?(this._translucentMaterialIndices.set(e,i),this._rebuildOpaqueOnlySubMeshes(e,i),`mixed`):(this._translucentMaterialIndices.delete(e),this._opaqueOnlySubMeshes.delete(e),n?`transparent`:`opaque`)}_rebuildOpaqueOnlySubMeshes(e,t){e.subMeshes&&this._opaqueOnlySubMeshes.set(e,e.subMeshes.filter(e=>!t.has(e.materialIndex)))}_addMesh(e){this._materialObservers[e.uniqueId]=e.onMaterialChangedObservable.add(this._onMeshMaterialChanged.bind(this)),P.SetImmediate(()=>{this._disposed||e.material&&(this._classifyMeshMaterials(e)===`transparent`?this._transparentMeshesCache.indexOf(e)===-1&&this._transparentMeshesCache.push(e):this._opaqueMeshesCache.indexOf(e)===-1&&this._opaqueMeshesCache.push(e))})}_removeMesh(e){e.onMaterialChangedObservable.remove(this._materialObservers[e.uniqueId]),delete this._materialObservers[e.uniqueId];let t=this._transparentMeshesCache.indexOf(e);t!==-1&&this._transparentMeshesCache.splice(t,1),t=this._opaqueMeshesCache.indexOf(e),t!==-1&&this._opaqueMeshesCache.splice(t,1),this._translucentMaterialIndices.delete(e),this._opaqueOnlySubMeshes.delete(e)}_parseScene(){this._scene.meshes.forEach(this._addMesh.bind(this)),this._newMeshObserver=this._scene.onNewMeshAddedObservable.add(this._addMesh.bind(this)),this._removedMeshObserver=this._scene.onMeshRemovedObservable.add(this._removeMesh.bind(this))}_onMeshMaterialChanged(e){let t=this._transparentMeshesCache.indexOf(e),n=this._opaqueMeshesCache.indexOf(e);this._classifyMeshMaterials(e)===`transparent`?n===-1?t===-1&&this._transparentMeshesCache.push(e):(this._opaqueMeshesCache.splice(n,1),this._transparentMeshesCache.push(e)):t===-1?n===-1&&this._opaqueMeshesCache.push(e):(this._transparentMeshesCache.splice(t,1),this._opaqueMeshesCache.push(e))}_isRenderTargetValid(){return this._opaqueRenderTarget?.getInternalTexture()!==null}_setupRenderTargets(){this._opaqueRenderTarget&&this._opaqueRenderTarget.dispose(),this._opaqueRenderTarget=new cr(`opaqueSceneTexture`,this._options.renderSize,this._scene,this._options.generateMipmaps,void 0,this._options.renderTargetTextureType),this._opaqueRenderTarget.ignoreCameraViewport=!0,this._opaqueRenderTarget.renderList=this._opaqueMeshesCache,this._opaqueRenderTarget.forceLayerMaskCheck=!0,this._opaqueRenderTarget.clearColor=this._options.clearColor?.clone()??this._scene.clearColor.clone(),this._opaqueRenderTarget.clearColor.a=0,this._opaqueRenderTarget.gammaSpace=!1,this._opaqueRenderTarget.lodGenerationScale=this._options.lodGenerationScale,this._opaqueRenderTarget.lodGenerationOffset=this._options.lodGenerationOffset,this._opaqueRenderTarget.samples=this._options.samples,this._opaqueRenderTarget.renderSprites=!0,this._opaqueRenderTarget.renderParticles=!0,this._opaqueRenderTarget.disableImageProcessing=!0;let e;this._opaqueRenderTarget.onBeforeBindObservable.add(t=>{e=this._scene.environmentIntensity,this._scene.environmentIntensity=1,this._options.clearColor?t.clearColor.copyFrom(this._options.clearColor):this._scene.clearColor.toLinearSpaceToRef(t.clearColor,this._scene.getEngine().useExactSrgbConversions),t.clearColor.a=0;let n=this._opaqueOnlySubMeshes.entries();for(let e=n.next();!e.done;e=n.next()){let t=e.value[0],n=e.value[1];t.subMeshes&&=(this._savedSubMeshes.set(t,t.subMeshes),n)}}),this._opaqueRenderTarget.onAfterUnbindObservable.add(()=>{this._scene.environmentIntensity=e;let t=this._savedSubMeshes.entries();for(let e=t.next();!e.done;e=t.next())e.value[0].subMeshes=e.value[1];this._savedSubMeshes.clear()});for(let e of this._transparentMeshesCache)e.material&&this._classifyMeshMaterials(e);let t=this._translucentMaterialIndices.entries();for(let e=t.next();!e.done;e=t.next()){let t=e.value[0];t.material&&this._classifyMeshMaterials(t)}}dispose(){this._disposed=!0,this._newMeshObserver?.remove(),this._removedMeshObserver?.remove(),this._newMeshObserver=null,this._removedMeshObserver=null;let e=[...this._transparentMeshesCache,...this._opaqueMeshesCache];for(let t of e){let e=this._materialObservers[t.uniqueId];e&&(e.remove(),delete this._materialObservers[t.uniqueId])}for(let e of this._scene.meshes){let t=this._materialObservers[e.uniqueId];t&&(t.remove(),delete this._materialObservers[e.uniqueId])}this._materialObservers={},this._scene._transmissionHelper=void 0,this._opaqueRenderTarget&&=(this._opaqueRenderTarget.dispose(),null),this._transparentMeshesCache=[],this._opaqueMeshesCache=[],this._translucentMaterialIndices.clear(),this._opaqueOnlySubMeshes.clear(),this._savedSubMeshes.clear()}};function Cs(e,t){if(e.parent.dontUseTransmissionHelper)return;
4let n=t.getScene()._transmissionHelper,r=n??new Ss({},t.getScene());for(let t of Array.from(e._pbrMaterialImpls.values()))r.addMaterialImpl(t);n&&!n._isRenderTargetValid()&&n._setupRenderTargets()}var ws=e({KHR_materials_transmission:()=>Es,RegisterKHR_materials_transmission:()=>Os}),Ts=`KHR_materials_transmission`,Es=class{constructor(e){this.name=Ts,this.order=175,this._loader=e,this.enabled=this._loader.isExtensionUsed(Ts),this.enabled&&(e.parent.transparencyAsCoverage=!0)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return U.LoadExtensionAsync(e,t,this.name,async(r,i)=>{let a=[];return a.push(this._loader.loadMaterialPropertiesAsync(e,t,n)),a.push(this._loadTransparentPropertiesAsync(r,t,n,i)),await Promise.all(a).then(()=>{})})}_loadTransparentPropertiesAsync(e,t,n,r){let i=this._loader._getOrCreateMaterialAdapter(n),a=r.transmissionFactor===void 0?0:r.transmissionFactor;if(a===0||!i)return Promise.resolve();i.configureTransmission(),i.transmissionWeight=a,a>0&&Cs(this._loader,n);let o=Promise.resolve(null);return r.transmissionTexture&&(r.transmissionTexture.nonColorData=!0,o=this._loader.loadTextureInfoAsync(`${e}/transmissionTexture`,r.transmissionTexture,e=>{e.name=`${n.name} (Transmission)`,i.transmissionWeightTexture=e})),o.then(()=>{})}},Ds=!1;function Os(){Ds||(Ds=!0,m(Ts),r(Ts,!0,e=>new Es(e)))}Os();var ks=e({KHR_materials_diffuse_transmission:()=>js,RegisterKHR_materials_diffuse_transmission:()=>Ns});_();var As=`KHR_materials_diffuse_transmission`,js=class{constructor(e){this.name=As,this.order=174,this._loader=e,this.enabled=this._loader.isExtensionUsed(As),this.enabled&&(e.parent.transparencyAsCoverage=!0)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return U.LoadExtensionAsync(e,t,this.name,async(r,i)=>{let a=[];return a.push(this._loader.loadMaterialPropertiesAsync(e,t,n)),a.push(this._loadTranslucentPropertiesAsync(r,t,n,i)),await Promise.all(a).then(()=>{})})}_loadTranslucentPropertiesAsync(e,t,n,r){let i=this._loader._getOrCreateMaterialAdapter(n);i.configureSubsurface(),i.subsurfaceWeight=r.diffuseTransmissionFactor??0,i.subsurfaceWeight>0&&Cs(this._loader,n),i.diffuseTransmissionTint=r.diffuseTransmissionColorFactor===void 0?N.White():N.FromArray(r.diffuseTransmissionColorFactor);let a=[];return r.diffuseTransmissionTexture&&(r.diffuseTransmissionTexture.nonColorData=!0,a.push(this._loader.loadTextureInfoAsync(`${e}/diffuseTransmissionTexture`,r.diffuseTransmissionTexture).then(e=>{e.name=`${n.name} (Diffuse Transmission)`,i.subsurfaceWeightTexture=e}))),r.diffuseTransmissionColorTexture&&a.push(this._loader.loadTextureInfoAsync(`${e}/diffuseTransmissionColorTexture`,r.diffuseTransmissionColorTexture).then(e=>{e.name=`${n.name} (Diffuse Transmission Color)`,i.diffuseTransmissionTintTexture=e})),Promise.all(a).then(()=>{})}},Ms=!1;function Ns(){Ms||(Ms=!0,m(As),r(As,!0,e=>new js(e)))}Ns();var Ps=e({KHR_materials_volume:()=>Is,RegisterKHR_materials_volume:()=>Rs});_();var Fs=`KHR_materials_volume`,Is=class{constructor(e){this.name=Fs,this.order=173,this._loader=e,this.enabled=this._loader.isExtensionUsed(Fs),this.enabled&&this._loader._disableInstancedMesh++}dispose(){this.enabled&&this._loader._disableInstancedMesh--,this._loader=null}loadMaterialPropertiesAsync(e,t,n){return U.LoadExtensionAsync(e,t,this.name,async(r,i)=>{let a=[];return a.push(this._loader.loadMaterialPropertiesAsync(e,t,n)),a.push(this._loadVolumePropertiesAsync(r,t,n,i)),await Promise.all(a).then(()=>{})})}_loadVolumePropertiesAsync(e,t,n,r){let i=this._loader._getOrCreateMaterialAdapter(n);if(i.transmissionWeight===0&&i.subsurfaceWeight===0||!r.thicknessFactor)return Promise.resolve();i.geometryThinWalled=!1;let a=r.attenuationDistance===void 0?Number.MAX_VALUE:r.attenuationDistance,o=r.attenuationColor!==void 0&&r.attenuationColor.length==3?N.FromArray(r.attenuationColor):N.White();i.configureVolume(),i.transmissionColor=o,i.transmissionDepth=a,i.volumeThickness=r.thicknessFactor??0;let s=[];return r.thicknessTexture&&(r.thicknessTexture.nonColorData=!0,s.push(this._loader.loadTextureInfoAsync(`${e}/thicknessTexture`,r.thicknessTexture,e=>{e.name=`${n.name} (Thickness)`,i.volumeThicknessTexture=e}))),Promise.all(s).then(()=>{})}},Ls=!1;function Rs(){Ls||(Ls=!0,m(Fs),r(Fs,!0,e=>new Is(e)))}Rs();var zs=e({KHR_materials_volume_scatter:()=>Hs,RegisterKHR_materials_volume_scatter:()=>Ws});_(),zn();var Bs=`KHR_materials_volume_scatter`;function Vs(e){let t=new R(e.r,e.g,e.b),n=new R(4.09712,4.09712,4.09712);n.addInPlace(new R(4.20863,4.20863,4.20863).multiplyInPlace(t));let r=new R(9.59217,9.59217,9.59217);return r.addInPlace(new R(41.6808,41.6808,41.6808).multiplyInPlace(t)),r.addInPlace(new R(17.7126,17.7126,17.7126).multiplyInPlace(t.multiply(t))),n.subtractInPlace(new R(Math.sqrt(r.x),Math.sqrt(r.y),Math.sqrt(r.z))),new R(1,1,1).subtract(n.multiply(n))}var Hs=class{constructor(e){this.name=Bs,this.order=172,this._loader=e,this.enabled=this._loader.isExtensionUsed(Bs),this.enabled&&this._loader._disableInstancedMesh++}
4dispose(){this.enabled&&this._loader._disableInstancedMesh--,this._loader=null}loadMaterialPropertiesAsync(e,t,n){return U.LoadExtensionAsync(e,t,this.name,async(r,i)=>{let a=[];return a.push(this._loader.loadMaterialPropertiesAsync(e,t,n)),a.push(this._loadVolumePropertiesAsync(r,t,n,i)),await Promise.all(a).then(()=>{})})}_loadVolumePropertiesAsync(e,t,n,r){let i=this._loader._getOrCreateMaterialAdapter(n);if(i.transmissionWeight===0&&i.subsurfaceWeight===0||i.geometryThinWalled)return Promise.resolve();let a=r.multiscatterColorFactor!==void 0&&r.multiscatterColorFactor.length==3?N.FromArray(r.multiscatterColorFactor):N.Black(),o=r.scatterAnisotropy===void 0?0:r.scatterAnisotropy,s=Promise.resolve(null);r.multiscatterColorTexture&&(r.multiscatterColorTexture.nonColorData=!0,s=this._loader.loadTextureInfoAsync(`${e}/multiscatterColorTexture`,r.multiscatterColorTexture,e=>{e.name=`${n.name} (Scatter Color)`,i.transmissionWeight>0&&(i.transmissionScatterTexture=e),i.subsurfaceWeight>0&&(i.subsurfaceColorTexture=e)}));let c=new R(-Math.log(i.transmissionColor.r),-Math.log(i.transmissionColor.g),-Math.log(i.transmissionColor.b));if(c.scaleInPlace(1/Math.max(i.transmissionDepth,1e-6)),i.transmissionWeight>0){let e=Vs(a),t=c.multiply(e);t.scaleInPlace(i.transmissionDepth),i.transmissionScatter.set(t.x,t.y,t.z),i.transmissionScatterAnisotropy=o}if(i.subsurfaceWeight>0){i.subsurfaceScatterAnisotropy=o,i.subsurfaceColor=a;let e=new R(c.x===0?1:1/c.x,c.y===0?1:1/c.y,c.z===0?1:1/c.z);i.subsurfaceRadius=Math.max(e.x,e.y,e.z),i.subsurfaceRadiusScale=new N(e.x/i.subsurfaceRadius,e.y/i.subsurfaceRadius,e.z/i.subsurfaceRadius)}return s.then(()=>{})}},Us=!1;function Ws(){Us||(Us=!0,m(Bs),r(Bs,!0,e=>new Hs(e)))}Ws();var Gs=e({KHR_materials_dispersion:()=>qs,RegisterKHR_materials_dispersion:()=>Ys}),Ks=`KHR_materials_dispersion`,qs=class{constructor(e){this.name=Ks,this.order=174,this._loader=e,this.enabled=this._loader.isExtensionUsed(Ks)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return U.LoadExtensionAsync(e,t,this.name,async(r,i)=>{let a=[];return a.push(this._loader.loadMaterialPropertiesAsync(e,t,n)),a.push(this._loadDispersionPropertiesAsync(r,t,n,i)),await Promise.all(a).then(()=>{})})}_loadDispersionPropertiesAsync(e,t,n,r){let i=this._loader._getOrCreateMaterialAdapter(n);return i.transmissionWeight==0||!r.dispersion?Promise.resolve():(i.transmissionDispersionAbbeNumber=20,i.transmissionDispersionScale=r.dispersion,Promise.resolve())}},Js=!1;function Ys(){Js||(Js=!0,m(Ks),r(Ks,!0,e=>new qs(e)))}Ys();var Xs=e({KHR_materials_diffuse_roughness:()=>Qs,RegisterKHR_materials_diffuse_roughness:()=>ec}),Zs=`KHR_materials_diffuse_roughness`,Qs=class{constructor(e){this.name=Zs,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(Zs)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return U.LoadExtensionAsync(e,t,this.name,async(r,i)=>{let a=[];return a.push(this._loader.loadMaterialPropertiesAsync(e,t,n)),a.push(this._loadDiffuseRoughnessPropertiesAsync(r,i,n)),await Promise.all(a).then(()=>{})})}_loadDiffuseRoughnessPropertiesAsync(e,t,n){let r=this._loader._getOrCreateMaterialAdapter(n),i=[];return r.baseDiffuseRoughness=t.diffuseRoughnessFactor??0,t.diffuseRoughnessTexture&&i.push(this._loader.loadTextureInfoAsync(`${e}/diffuseRoughnessTexture`,t.diffuseRoughnessTexture,e=>{e.name=`${n.name} (Diffuse Roughness)`,r.baseDiffuseRoughnessTexture=e})),Promise.all(i).then(()=>{})}},$s=!1;function ec(){$s||($s=!0,m(Zs),r(Zs,!0,e=>new Qs(e)))}ec();var tc=e({KHR_mesh_quantization:()=>rc,RegisterKHR_mesh_quantization:()=>ac}),nc=`KHR_mesh_quantization`,rc=class{constructor(e){this.name=nc,this.enabled=e.isExtensionUsed(nc)}dispose(){}},ic=!1;function ac(){ic||(ic=!0,m(nc),r(nc,!0,e=>new rc(e)))}ac();var oc=e({KHR_texture_basisu:()=>cc,RegisterKHR_texture_basisu:()=>uc}),sc=`KHR_texture_basisu`,cc=class{constructor(e){this.name=sc,this._loader=e,this.enabled=e.isExtensionUsed(sc)}dispose(){this._loader=null}_loadTextureAsync(e,t,n){return U.LoadExtensionAsync(e,t,this.name,async(r,i)=>{let a=t.sampler==null?U.DefaultSampler:H.Get(`${e}/sampler`,this._loader.gltf.samplers,t.sampler),o=H.Get(`${r}/source`,this._loader.gltf.images,i.source);return await this._loader._createTextureAsync(e,a,o,e=>{n(e)},t._textureInfo.nonColorData?{useRGBAIfASTCBC7NotAvailableWhenUASTC:!0}:void 0,!t._textureInfo.nonColorData,t)})}},lc=!1;function uc(){lc||(lc=!0,m(sc),r(sc,!0,e=>new cc(e)))}uc();var dc=e({KHR_texture_transform:()=>pc,RegisterKHR_texture_transform:()=>hc});pr();var fc=`KHR_texture_transform`,pc=class{constructor(e){this.name=fc,this._loader=e,this.enabled=this._loader.isExtensionUsed(fc)}dispose(){this._loader=null}
4loadTextureInfoAsync(e,t,n){return U.LoadExtensionAsync(e,t,this.name,async(r,i)=>await this._loader.loadTextureInfoAsync(e,t,e=>{if(!(e instanceof I))throw Error(`${r}: Texture type not supported`);i.offset&&(e.uOffset=i.offset[0],e.vOffset=i.offset[1]),e.uRotationCenter=0,e.vRotationCenter=0,i.rotation&&(e.wAng=-i.rotation),i.scale&&(e.uScale=i.scale[0],e.vScale=i.scale[1]),i.texCoord!=null&&(e.coordinatesIndex=i.texCoord),n(e)}))}},mc=!1;function hc(){mc||(mc=!0,m(fc),r(fc,!0,e=>new pc(e)))}hc();var gc=e({KHR_xmp_json_ld:()=>vc,RegisterKHR_xmp_json_ld:()=>bc}),_c=`KHR_xmp_json_ld`,vc=class{constructor(e){this.name=_c,this.order=100,this._loader=e,this.enabled=this._loader.isExtensionUsed(_c)}dispose(){this._loader=null}onLoading(){if(this._loader.rootBabylonMesh===null)return;let e=this._loader.gltf.extensions?.KHR_xmp_json_ld,t=this._loader.gltf.asset?.extensions?.KHR_xmp_json_ld;if(e&&t){let n=+t.packet;e.packets&&n<e.packets.length&&(this._loader.rootBabylonMesh.metadata=this._loader.rootBabylonMesh.metadata||{},this._loader.rootBabylonMesh.metadata.xmp=e.packets[n])}}},yc=!1;function bc(){yc||(yc=!0,m(_c),r(_c,!0,e=>new vc(e)))}bc();var xc=e({KHR_animation_pointer:()=>Cc,RegisterKHR_animation_pointer:()=>Tc});yt();var Sc=`KHR_animation_pointer`,Cc=class{constructor(e){this.name=Sc,this._loader=e,this._pathToObjectConverter=Wi(this._loader.gltf)}get enabled(){return this._loader.isExtensionUsed(Sc)}dispose(){this._loader=null,delete this._pathToObjectConverter}_loadAnimationChannelAsync(e,t,n,r,i){let a=r.target.extensions?.KHR_animation_pointer;if(!a||!this._pathToObjectConverter)return null;r.target.path!==`pointer`&&A.Warn(`${e}/target/path: Value (${r.target.path}) must be (pointer) when using the ${this.name} extension`),r.target.node!=null&&A.Warn(`${e}/target/node: Value (${r.target.node}) must not be present when using the ${this.name} extension`);let o=`${e}/extensions/${this.name}`,s=a.pointer;if(!s)throw Error(`${o}: Pointer is missing`);try{let a=this._pathToObjectConverter.convert(s);if(!a.info.interpolation)throw Error(`${o}/pointer: Interpolation is missing`);return this._loader._loadAnimationChannelFromTargetInfoAsync(e,t,n,r,{object:a.object,info:a.info.interpolation},i)}catch{return A.Warn(`${o}/pointer: Invalid pointer (${s}) skipped`),null}}},wc=!1;function Tc(){wc||(wc=!0,m(Sc),r(Sc,!0,e=>new Cc(e)))}var Ec=e({_RegisterKHRAnimationPointerData:()=>Lc});ne(),_();function Dc(e,t,n,r){return N.FromArray(t,n).scale(r)}function Oc(e,t,n,r){return t[n+3]*r}function W(e,t,n,r){return t[n]*r}function kc(e,t,n,r){return-t[n]*r}function Ac(e,t,n,r){return t[n+1]*r}function jc(e,t,n,r){return t[n]*r*2}function Mc(e){return{scale:[new G(M.ANIMATIONTYPE_FLOAT,`${e}.uScale`,W,()=>2),new G(M.ANIMATIONTYPE_FLOAT,`${e}.vScale`,Ac,()=>2)],offset:[new G(M.ANIMATIONTYPE_FLOAT,`${e}.uOffset`,W,()=>2),new G(M.ANIMATIONTYPE_FLOAT,`${e}.vOffset`,Ac,()=>2)],rotation:[new G(M.ANIMATIONTYPE_FLOAT,`${e}.wAng`,kc,()=>1)]}}var Nc=class extends ra{buildAnimations(e,t,n,r){return[{babylonAnimatable:e._babylonCamera,babylonAnimation:this._buildAnimation(t,n,r)}]}},G=class extends ra{buildAnimations(e,t,n,r){let i=[];for(let a in e._data)i.push({babylonAnimatable:e._data[a].babylonMaterial,babylonAnimation:this._buildAnimation(t,n,r)});return i}},Pc=class extends ra{buildAnimations(e,t,n,r){return[{babylonAnimatable:e._babylonLight,babylonAnimation:this._buildAnimation(t,n,r)}]}},Fc=class extends ra{buildAnimations(e,t,n,r){return e._primitiveBabylonMeshes?e._primitiveBabylonMeshes.map(e=>({babylonAnimatable:e,babylonAnimation:this._buildAnimation(t,n,r)})):[]}},Ic=!1;function Lc(){if(Ic)return;Ic=!0,sa(),V(`/cameras/{}/orthographic/xmag`,[new Nc(M.ANIMATIONTYPE_FLOAT,`orthoLeft`,kc,()=>1),new Nc(M.ANIMATIONTYPE_FLOAT,`orthoRight`,Ac,()=>1)]),V(`/cameras/{}/orthographic/ymag`,[new Nc(M.ANIMATIONTYPE_FLOAT,`orthoBottom`,kc,()=>1),new Nc(M.ANIMATIONTYPE_FLOAT,`orthoTop`,Ac,()=>1)]),V(`/cameras/{}/orthographic/zfar`,[new Nc(M.ANIMATIONTYPE_FLOAT,`maxZ`,W,()=>1)]),V(`/cameras/{}/orthographic/znear`,[new Nc(M.ANIMATIONTYPE_FLOAT,`minZ`,W,()=>1)]),V(`/cameras/{}/perspective/yfov`,[new Nc(M.ANIMATIONTYPE_FLOAT,`fov`,W,()=>1)]),V(`/cameras/{}/perspective/zfar`,[new Nc(M.ANIMATIONTYPE_FLOAT,`maxZ`,W,()=>1)]),V(`/cameras/{}/perspective/znear`,[new Nc(M.ANIMATIONTYPE_FLOAT,`minZ`,W,()=>1)]),V(`/materials/{}/pbrMetallicRoughness/baseColorFactor`,[new G(M.ANIMATIONTYPE_COLOR3,`albedoColor`,Dc,()=>4),new G(M.ANIMATIONTYPE_FLOAT,`alpha`,Oc,()=>
44)]),V(`/materials/{}/pbrMetallicRoughness/metallicFactor`,[new G(M.ANIMATIONTYPE_FLOAT,`metallic`,W,()=>1)]),V(`/materials/{}/pbrMetallicRoughness/metallicFactor`,[new G(M.ANIMATIONTYPE_FLOAT,`roughness`,W,()=>1)]);let e=Mc(`albedoTexture`);V(`/materials/{}/pbrMetallicRoughness/baseColorTexture/extensions/KHR_texture_transform/scale`,e.scale),V(`/materials/{}/pbrMetallicRoughness/baseColorTexture/extensions/KHR_texture_transform/offset`,e.offset),V(`/materials/{}/pbrMetallicRoughness/baseColorTexture/extensions/KHR_texture_transform/rotation`,e.rotation);let t=Mc(`metallicTexture`);V(`//materials/{}/pbrMetallicRoughness/metallicRoughnessTexture/scale`,t.scale),V(`//materials/{}/pbrMetallicRoughness/metallicRoughnessTexture/offset`,t.offset),V(`//materials/{}/pbrMetallicRoughness/metallicRoughnessTexture/rotation`,t.rotation),V(`/materials/{}/emissiveFactor`,[new G(M.ANIMATIONTYPE_COLOR3,`emissiveColor`,Dc,()=>3)]);let n=Mc(`bumpTexture`);V(`/materials/{}/normalTexture/scale`,[new G(M.ANIMATIONTYPE_FLOAT,`bumpTexture.level`,W,()=>1)]),V(`/materials/{}/normalTexture/extensions/KHR_texture_transform/scale`,n.scale),V(`/materials/{}/normalTexture/extensions/KHR_texture_transform/offset`,n.offset),V(`/materials/{}/normalTexture/extensions/KHR_texture_transform/rotation`,n.rotation),V(`/materials/{}/occlusionTexture/strength`,[new G(M.ANIMATIONTYPE_FLOAT,`ambientTextureStrength`,W,()=>1)]);let r=Mc(`ambientTexture`);V(`/materials/{}/occlusionTexture/extensions/KHR_texture_transform/scale`,r.scale),V(`/materials/{}/occlusionTexture/extensions/KHR_texture_transform/offset`,r.offset),V(`/materials/{}/occlusionTexture/extensions/KHR_texture_transform/rotation`,r.rotation);let i=Mc(`emissiveTexture`);V(`/materials/{}/emissiveTexture/extensions/KHR_texture_transform/scale`,i.scale),V(`/materials/{}/emissiveTexture/extensions/KHR_texture_transform/offset`,i.offset),V(`/materials/{}/emissiveTexture/extensions/KHR_texture_transform/rotation`,i.rotation),V(`/materials/{}/extensions/KHR_materials_anisotropy/anisotropyStrength`,[new G(M.ANIMATIONTYPE_FLOAT,`anisotropy.intensity`,W,()=>1)]),V(`/materials/{}/extensions/KHR_materials_anisotropy/anisotropyRotation`,[new G(M.ANIMATIONTYPE_FLOAT,`anisotropy.angle`,W,()=>1)]);let a=Mc(`anisotropy.texture`);V(`/materials/{}/extensions/KHR_materials_anisotropy/anisotropyTexture/extensions/KHR_texture_transform/scale`,a.scale),V(`/materials/{}/extensions/KHR_materials_anisotropy/anisotropyTexture/extensions/KHR_texture_transform/offset`,a.offset),V(`/materials/{}/extensions/KHR_materials_anisotropy/anisotropyTexture/extensions/KHR_texture_transform/rotation`,a.rotation),V(`/materials/{}/extensions/KHR_materials_clearcoat/clearcoatFactor`,[new G(M.ANIMATIONTYPE_FLOAT,`clearCoat.intensity`,W,()=>1)]),V(`/materials/{}/extensions/KHR_materials_clearcoat/clearcoatRoughnessFactor`,[new G(M.ANIMATIONTYPE_FLOAT,`clearCoat.roughness`,W,()=>1)]);let o=Mc(`clearCoat.texture`);V(`/materials/{}/extensions/KHR_materials_clearcoat/clearcoatTexture/extensions/KHR_texture_transform/scale`,o.scale),V(`/materials/{}/extensions/KHR_materials_clearcoat/clearcoatTexture/extensions/KHR_texture_transform/offset`,o.offset),V(`/materials/{}/extensions/KHR_materials_clearcoat/clearcoatTexture/extensions/KHR_texture_transform/rotation`,o.rotation);let s=Mc(`clearCoat.bumpTexture`);V(`/materials/{}/extensions/KHR_materials_clearcoat/clearcoatNormalTexture/scale`,[new G(M.ANIMATIONTYPE_FLOAT,`clearCoat.bumpTexture.level`,W,()=>1)]),V(`/materials/{}/extensions/KHR_materials_clearcoat/clearcoatNormalTexture/extensions/KHR_texture_transform/scale`,s.scale),V(`/materials/{}/extensions/KHR_materials_clearcoat/clearcoatNormalTexture/extensions/KHR_texture_transform/offset`,s.offset),V(`/materials/{}/extensions/KHR_materials_clearcoat/clearcoatNormalTexture/extensions/KHR_texture_transform/rotation`,s.rotation);let c=Mc(`clearCoat.textureRoughness`);V(`/materials/{}/extensions/KHR_materials_clearcoat/clearcoatRoughnessTexture/extensions/KHR_texture_transform/scale`,c.scale),V(`/materials/{}/extensions/KHR_materials_clearcoat/clearcoatRoughnessTexture/extensions/KHR_texture_transform/offset`,c.offset),V(`/materials/{}/extensions/KHR_materials_clearcoat/clearcoatRoughnessTexture/extensions/KHR_texture_transform/rotation`,c.rotation),V(`/materials/{}/extensions/KHR_materials_dispersion/dispersionFactor`,[new G(M.ANIMATIONTYPE_FLOAT,`subSurface.dispersion`,W,()=>1)]),V(`/materials/{}/extensions/KHR_materials_emissive_strength/emissiveStrength`,[new G(M.ANIMATIONTYPE_FLOAT,`emissiveIntensity`,W,()=>1)]),V(`/materials/{}/extensions/KHR_materials_ior/ior`,[new G(M.ANIMATIONTYPE_FLOAT,`indexOfRefraction`,W,()=>1)]),V(`/materials/{}/extensions/KHR_materials_iridescence/iridescenceFactor`,[new G(M.ANIMATIONTYPE_FLOAT,`iridescence.intensity`,W,()=>1)]),V(`/materials/{}/extensions/KHR_materials_iridescence/iridescenceIor`,[new G(M.ANIMATIONTYPE_FLOAT,`iridescence.indexOfRefraction`,W,()=>1)]),V(`/materials/{}/extensions/KHR_materials_iridescence/iridescenceThicknessMinimum`,[new G(M.ANIMATIONTYPE_FLOAT,`iridescence.minimumThickness`,W,()=>1)]),V(`/materials/{}/extensions/KHR_materials_iridescence/iridescenceThicknessMaximum`,[new G(M.ANIMATIONTYPE_FLOAT,`iridescence.maximumThickness`,W,()=>1)]);let l=Mc(`iridescence.texture`);V(`/materials/{}/extensions/KHR_materials_iridescence/iridescenceTexture/extensions/KHR_texture_transform/scale`,l.scale),V(`/materials/{}/extensions/KHR_materials_iridescence/iridescenceTexture/extensions/KHR_texture_transform/offset`,l.offset),V(`/materials/{}/extensions/KHR_materials_iridescence/iridescenceTexture/extensions/KHR_texture_transform/rotation`,l.rotation);let u=Mc(`iridescence.thicknessTexture`);V(`/materials/{}/extensions/KHR_materials_iridescence/iridescenceThicknessTexture/extensions/KHR_texture_transform/scale`,u.scale),V(`/materials/{}/extensions/KHR_materials_iridescence/iridescenceThicknessTexture/extensions/KHR_texture_transform/offset`,u.offset),V(`/materials/{}/extensions/KHR_materials_iridescence/iridescenceThicknessTexture/extensions/KHR_texture_transform/rotation`,u.rotation),V(`/materials/{}/extensions/KHR_materials_sheen/sheenColorFactor`,[new G(M.ANIMATIONTYPE_COLOR3,`sheen.color`,Dc,()=>3)]),V(`/materials/{}/extensions/KHR_materials_sheen/sheenRoughnessFactor`,[new G(M.ANIMATIONTYPE_FLOAT,`sheen.roughness`,W,()=>1)]);let d=Mc(`sheen.texture`);V(`/materials/{}/extensions/KHR_materials_sheen/sheenColorTexture/extensions/KHR_texture_transform/scale`,d.scale),V(`/materials/{}/extensions/KHR_materials_sheen/sheenColorTexture/extensions/KHR_texture_transform/offset`,d.offset),V(`/materials/{}/extensions/KHR_materials_sheen/sheenColorTexture/extensions/KHR_texture_transform/rotation`,d.rotation);let f=Mc(`sheen.textureRoughness`);V(`/materials/{}/extensions/KHR_materials_sheen/sheenRoughnessTexture/extensions/KHR_texture_transform/scale`,f.scale),V(`/materials/{}/extensions/KHR_materials_sheen/sheenRoughnessTexture/extensions/KHR_texture_transform/offset`,f.offset),V(`/materials/{}/extensions/KHR_materials_sheen/sheenRoughnessTexture/extensions/KHR_texture_transform/rotation`,f.rotation),V(`/materials/{}/extensions/KHR_materials_specular/specularFactor`,[new G(M.ANIMATIONTYPE_FLOAT,`metallicF0Factor`,W,()=>1)]),V(`/materials/{}/extensions/KHR_materials_specular/specularColorFactor`,[new G(M.ANIMATIONTYPE_COLOR3,`metallicReflectanceColor`,Dc,()=>3)]);let p=Mc(`metallicReflectanceTexture`);V(`/materials/{}/extensions/KHR_materials_specular/specularTexture/extensions/KHR_texture_transform/scale`,p.scale),V(`/materials/{}/extensions/KHR_materials_specular/specularTexture/extensions/KHR_texture_transform/offset`,p.offset),V(`/materials/{}/extensions/KHR_materials_specular/specularTexture/extensions/KHR_texture_transform/rotation`,p.rotation);let m=Mc(`reflectanceTexture`);V(`/materials/{}/extensions/KHR_materials_specular/specularColorTexture/extensions/KHR_texture_transform/scale`,m.scale),V(`/materials/{}/extensions/KHR_materials_specular/specularColorTexture/extensions/KHR_texture_transform/offset`,m.offset),V(`/materials/{}/extensions/KHR_materials_specular/specularColorTexture/extensions/KHR_texture_transform/rotation`,m.rotation),V(`/materials/{}/extensions/KHR_materials_transmission/transmissionFactor`,[new G(M.ANIMATIONTYPE_FLOAT,`subSurface.refractionIntensity`,W,()=>1)]);let h=Mc(`subSurface.refractionIntensityTexture`);V(`/materials/{}/extensions/KHR_materials_transmission/transmissionTexture/extensions/KHR_texture_transform/scale`,h.scale),V(`/materials/{}/extensions/KHR_materials_transmission/transmissionTexture/extensions/KHR_texture_transform/offset`,h.offset),V(`/materials/{}/extensions/KHR_materials_transmission/transmissionTexture/extensions/KHR_texture_transform/rotation`,h.rotation),V(`/materials/{}/extensions/KHR_materials_volume/attenuationColor`,[new G(M.ANIMATIONTYPE_COLOR3,`subSurface.tintColor`,Dc,()=>3)]),V(`/materials/{}/extensions/KHR_materials_volume/attenuationDistance`,[new G(M.ANIMATIONTYPE_FLOAT,`subSurface.tintColorAtDistance`,W,()=>1)]),V(`/materials/{}/extensions/KHR_materials_volume/thicknessFactor`,[new G(M.ANIMATIONTYPE_FLOAT,`subSurface.maximumThickness`,W,()=>1)]);let g=Mc(`subSurface.thicknessTexture`);V(`/materials/{}/extensions/KHR_materials_volume/thicknessTexture/extensions/KHR_texture_transform/scale`,g.scale),V(`/materials/{}/extensions/KHR_materials_volume/thicknessTexture/extensions/KHR_texture_transform/offset`,g.offset),V(`/materials/{}/extensions/KHR_materials_volume/thicknessTexture/extensions/KHR_texture_transform/rotation`,g.rotation),V(`/materials/{}/extensions/KHR_materials_diffuse_transmission/diffuseTransmissionFactor`,[new G(M.ANIMATIONTYPE_FLOAT,`subSurface.translucencyIntensity`,W,()=>1)]);let _=Mc(`subSurface.translucencyIntensityTexture`);V(`materials/{}/extensions/KHR_materials_diffuse_transmission/diffuseTransmissionTexture/extensions/KHR_texture_transform/scale`,_.scale),V(`materials/{}/extensions/KHR_materials_diffuse_transmission/diffuseTransmissionTexture/extensions/KHR_texture_transform/offset`,_.offset),V(`materials/{}/extensions/KHR_materials_diffuse_transmission/diffuseTransmissionTexture/extensions/KHR_texture_transform/rotation`,_.rotation),V(`/materials/{}/extensions/KHR_materials_diffuse_transmission/diffuseTransmissionColorFactor`,[new G(M.ANIMATIONTYPE_COLOR3,`subSurface.translucencyColor`,Dc,()=>3)]);let v=Mc(`subSurface.translucencyColorTexture`);V(`materials/{}/extensions/KHR_materials_diffuse_transmission/diffuseTransmissionColorTexture/extensions/KHR_texture_transform/scale`,v.scale),V(`materials/{}/extensions/KHR_materials_diffuse_transmission/diffuseTransmissionColorTexture/extensions/KHR_texture_transform/offset`,v.offset),V(`materials/{}/extensions/KHR_materials_diffuse_transmission/diffuseTransmissionColorTexture/extensions/KHR_texture_transform/rotation`,v.rotation),V(`/extensions/KHR_lights_punctual/lights/{}/color`,[new Pc(M.ANIMATIONTYPE_COLOR3,`diffuse`,Dc,()=>3)]),V(`/extensions/KHR_lights_punctual/lights/{}/intensity`,[new Pc(M.ANIMATIONTYPE_FLOAT,`intensity`,W,()=>1)]),V(`/extensions/KHR_lights_punctual/lights/{}/range`,[new Pc(M.ANIMATIONTYPE_FLOAT,`range`,W,()=>1)]),V(`/extensions/KHR_lights_punctual/lights/{}/spot/innerConeAngle`,[new Pc(M.ANIMATIONTYPE_FLOAT,`innerAngle`,jc,()=>1)]),V(`/extensions/KHR_lights_punctual/lights/{}/spot/outerConeAngle`,[new Pc(M.ANIMATIONTYPE_FLOAT,`angle`,jc,()=>1)]),V(`/extensions/EXT_lights_area/lights/{}/color`,[new Pc(M.ANIMATIONTYPE_COLOR3,`diffuse`,Dc,()=>3)]),V(`/extensions/EXT_lights_area/lights/{}/intensity`,[new Pc(M.ANIMATIONTYPE_FLOAT,`intensity`,W,()=>1)]),V(`/extensions/EXT_lights_area/lights/{}/size`,[new Pc(M.ANIMATIONTYPE_FLOAT,`radius`,W,()=>1)]),V(`/extensions/EXT_lights_area/lights/{}/rect/aspect`,[new Pc(M.ANIMATIONTYPE_FLOAT,`radius`,W,()=>1)]),V(`/nodes/{}/extensions/EXT_lights_ies/color`,[new Pc(M.ANIMATIONTYPE_COLOR3,`diffuse`,Dc,()=>3)]),V(`/nodes/{}/extensions/EXT_lights_ies/multiplier`,[new Pc(M.ANIMATIONTYPE_FLOAT,`intensity`,W,()=>1)]),V(`/nodes/{}/extensions/KHR_node_visibility/visible`,[new Fc(M.ANIMATIONTYPE_FLOAT,`isVisible`,W,()=>1)])}Lc(),Tc();var Rc=e({MSFT_audio_emitter:()=>Bc,RegisterMSFT_audio_emitter:()=>Hc});zn(),wt(),Vn(),Be(),S(),Xt();var zc=`MSFT_audio_emitter`,Bc=class{constructor(e){this.name=zc,this._loader=e,this.enabled=this._loader.isExtensionUsed(zc)}dispose(){this._loader=null,this._clips=null,this._emitters=null}onLoading(){let e=this._loader.gltf.extensions;
4if(e&&e[this.name]){let t=e[this.name];this._clips=t.clips,this._emitters=t.emitters,H.Assign(this._clips),H.Assign(this._emitters)}}loadSceneAsync(e,t){return U.LoadExtensionAsync(e,t,this.name,async(n,r)=>{let i=[];i.push(this._loader.loadSceneAsync(e,t));for(let e of r.emitters){let t=H.Get(`${n}/emitters`,this._emitters,e);if(t.refDistance!=null||t.maxDistance!=null||t.rolloffFactor!=null||t.distanceModel!=null||t.innerAngle!=null||t.outerAngle!=null)throw Error(`${n}: Direction or Distance properties are not allowed on emitters attached to a scene`);i.push(this._loadEmitterAsync(`${n}/emitters/${t.index}`,t))}await Promise.all(i)})}loadNodeAsync(e,t,n){return U.LoadExtensionAsync(e,t,this.name,async(e,r)=>{let i=[],a=await this._loader.loadNodeAsync(e,t,t=>{for(let n of r.emitters){let r=H.Get(`${e}/emitters`,this._emitters,n);i.push(this._loadEmitterAsync(`${e}/emitters/${r.index}`,r).then(()=>{for(let e of r._babylonSounds)e.attachToMesh(t),(r.innerAngle!=null||r.outerAngle!=null)&&(e.setLocalDirectionToMesh(R.Forward()),e.setDirectionalCone(2*P.ToDegrees(r.innerAngle==null?Math.PI:r.innerAngle),2*P.ToDegrees(r.outerAngle==null?Math.PI:r.outerAngle),0))}))}n(t)});return await Promise.all(i),a})}loadAnimationAsync(e,t){return U.LoadExtensionAsync(e,t,this.name,async(n,r)=>{let i=await this._loader.loadAnimationAsync(e,t),a=[];H.Assign(r.events);for(let o of r.events)a.push(this._loadAnimationEventAsync(`${n}/events/${o.index}`,e,t,o,i));return await Promise.all(a),i})}_loadClipAsync(e,t){if(t._objectURL)return t._objectURL;let n;if(t.uri)n=this._loader.loadUriAsync(e,t,t.uri);else{let r=H.Get(`${e}/bufferView`,this._loader.gltf.bufferViews,t.bufferView);n=this._loader.loadBufferViewAsync(`/bufferViews/${r.index}`,r)}return t._objectURL=n.then(e=>{let n=zt(e);return URL.createObjectURL(new Blob([n],{type:t.mimeType}))}),t._objectURL}_loadEmitterAsync(e,t){if(t._babylonSounds=t._babylonSounds||[],!t._babylonData){let e=[],n=t.name||`emitter${t.index}`,r={loop:!1,autoplay:!1,volume:t.volume==null?1:t.volume};for(let i=0;i<t.clips.length;i++){let a=`/extensions/${this.name}/clips`,o=H.Get(a,this._clips,t.clips[i].clip);e.push(this._loadClipAsync(`${a}/${t.clips[i].clip}`,o).then(e=>{let a=t._babylonSounds[i]=new Me(n,e,this._loader.babylonScene,null,r);a.refDistance=t.refDistance||1,a.maxDistance=t.maxDistance||256,a.rolloffFactor=t.rolloffFactor||1,a.distanceModel=t.distanceModel||`exponential`}))}t._babylonData={loaded:Promise.all(e).then(()=>{let e=t.clips.map(e=>e.weight||1),n=new Sn(t.loop||!1,t._babylonSounds,e);t.innerAngle&&(n.directionalConeInnerAngle=2*P.ToDegrees(t.innerAngle)),t.outerAngle&&(n.directionalConeOuterAngle=2*P.ToDegrees(t.outerAngle)),t.volume&&(n.volume=t.volume),t._babylonData.sound=n})}}return t._babylonData.loaded}_getEventAction(e,t,n,r,i){switch(n){case`play`:return e=>{let n=(i||0)+(e-r);t.play(n)};case`stop`:return()=>{t.stop()};case`pause`:return()=>{t.pause()};default:throw Error(`${e}: Unsupported action ${n}`)}}_loadAnimationEventAsync(e,t,n,r,i){if(i.targetedAnimations.length==0)return Promise.resolve();let a=i.targetedAnimations[0],o=r.emitter,s=H.Get(`/extensions/${this.name}/emitters`,this._emitters,o);return this._loadEmitterAsync(e,s).then(()=>{let t=s._babylonData.sound;if(t){let n=new Pt(r.time,this._getEventAction(e,t,r.action,r.time,r.startOffset));a.animation.addEvent(n),i.onAnimationGroupEndObservable.add(()=>{t.stop()}),i.onAnimationGroupPauseObservable.add(()=>{t.pause()})}})}},Vc=!1;function Hc(){Vc||(Vc=!0,m(zc),r(zc,!0,e=>new Bc(e)))}Ee(),Hc();var Uc=e({MSFT_lod:()=>Gc,RegisterMSFT_lod:()=>qc});xr(),Bn();var Wc=`MSFT_lod`,Gc=class{constructor(e){this.name=Wc,this.order=100,this.maxLODsToLoad=10,this.onNodeLODsLoadedObservable=new yr,this.onMaterialLODsLoadedObservable=new yr,this._bufferLODs=[],this._nodeIndexLOD=null,this._nodeSignalLODs=[],this._nodePromiseLODs=[],this._nodeBufferLODs=[],this._materialIndexLOD=null,this._materialSignalLODs=[],this._materialPromiseLODs=[],this._materialBufferLODs=[],this._loader=e,this.maxLODsToLoad=this._loader.parent.extensionOptions[Wc]?.maxLODsToLoad??this.maxLODsToLoad,this.enabled=this._loader.isExtensionUsed(Wc)}dispose(){this._loader=null,this._nodeIndexLOD=null,this._nodeSignalLODs.length=0,this._nodePromiseLODs.length=0,this._nodeBufferLODs.length=0,this._materialIndexLOD=null,this._materialSignalLODs.length=0,this._materialPromiseLODs.length=0,this._materialBufferLODs.length=0,this.onMaterialLODsLoadedObservable.clear(),this.onNodeLODsLoadedObservable.clear()}onReady(){for(let e=0;e<this._nodePromiseLODs.length;e++){let t=Promise.all(this._nodePromiseLODs[e]).then(()=>{e!==0&&(this._loader.endPerformanceCounter(`Node LOD ${e}`),this._loader.log(`Loaded node LOD ${e}`)),this.onNodeLODsLoadedObservable.notifyObservers(e),e!==this._nodePromiseLODs.length-1&&(this._loader.startPerformanceCounter(`Node LOD ${e+1}`),this._loadBufferLOD(this._nodeBufferLODs,e+1),this._nodeSignalLODs[e]&&this._nodeSignalLODs[e].resolve())});this._loader._completePromises.push(t)}for(let e=0;e<this._materialPromiseLODs.length;e++){let t=Promise.all(this._materialPromiseLODs[e]).then(()=>{e!==0&&(this._loader.endPerformanceCounter(`Material LOD ${e}`),this._loader.log(`Loaded material LOD ${e}`)),this.onMaterialLODsLoadedObservable.notifyObservers(e),e!==this._materialPromiseLODs.length-1&&(this._loader.startPerformanceCounter(`Material LOD ${e+1}`),this._loadBufferLOD(this._materialBufferLODs,e+1),this._materialSignalLODs[e]&&this._materialSignalLODs[e].resolve())});this._loader._completePromises.push(t)}}loadSceneAsync(e,t){let n=this._loader.loadSceneAsync(e,t);return this._loadBufferLOD(this._bufferLODs,0),n}loadNodeAsync(e,t,n){return U.LoadExtensionAsync(e,t,this.name,async(e,r)=>{let i,a=this._getLODs(e,t,this._loader.gltf.nodes,r.ids);this._loader.logOpen(`${e}`);for(let e=0;e<a.length;e++){let t=a[e];e!==0&&(this._nodeIndexLOD=e,this._nodeSignalLODs[e]=this._nodeSignalLODs[e]||new Nt);let r=this._loader.loadNodeAsync(`/nodes/${t.index}`,t,e=>{n(e),e.setEnabled(!1)}).then(t=>{if(e!==0){let t=a[e-1];t._babylonTransformNode&&(this._disposeTransformNode(t._babylonTransformNode),delete t._babylonTransformNode)}return t.setEnabled(!0),t});
4this._nodePromiseLODs[e]=this._nodePromiseLODs[e]||[],e===0?i=r:(this._nodeIndexLOD=null,this._nodePromiseLODs[e].push(r))}return this._loader.logClose(),await i})}_loadMaterialAsync(e,t,n,r,i){return this._nodeIndexLOD?null:U.LoadExtensionAsync(e,t,this.name,async(e,a)=>{let o,s=this._getLODs(e,t,this._loader.gltf.materials,a.ids);this._loader.logOpen(`${e}`);for(let e=0;e<s.length;e++){let t=s[e];e!==0&&(this._materialIndexLOD=e);let a=this._loader._loadMaterialAsync(`/materials/${t.index}`,t,n,r,t=>{e===0&&i(t)}).then(t=>{if(e!==0){i(t);let n=s[e-1]._data;n[r]&&(this._disposeMaterials([n[r].babylonMaterial]),delete n[r])}return t});this._materialPromiseLODs[e]=this._materialPromiseLODs[e]||[],e===0?o=a:(this._materialIndexLOD=null,this._materialPromiseLODs[e].push(a))}return this._loader.logClose(),await o})}_loadUriAsync(e,t,n){if(this._nodeIndexLOD!==null){this._loader.log(`deferred`);let r=this._nodeIndexLOD-1;return this._nodeSignalLODs[r]=this._nodeSignalLODs[r]||new Nt,this._nodeSignalLODs[this._nodeIndexLOD-1].promise.then(async()=>await this._loader.loadUriAsync(e,t,n))}if(this._materialIndexLOD!==null){this._loader.log(`deferred`);let r=this._materialIndexLOD-1;return this._materialSignalLODs[r]=this._materialSignalLODs[r]||new Nt,this._materialSignalLODs[r].promise.then(async()=>await this._loader.loadUriAsync(e,t,n))}return null}loadBufferAsync(e,t,n,r){if(this._loader.parent.useRangeRequests&&!t.uri){if(!this._loader.bin)throw Error(`${e}: Uri is missing or the binary glTF is missing its binary chunk`);let t=async(e,t)=>{let i=n,a=i+r-1,o=e[t];return o?(o.start=Math.min(o.start,i),o.end=Math.max(o.end,a)):(o={start:i,end:a,loaded:new Nt},e[t]=o),await o.loaded.promise.then(e=>new Uint8Array(e.buffer,e.byteOffset+n-o.start,r))};return this._loader.log(`deferred`),this._nodeIndexLOD===null?this._materialIndexLOD===null?t(this._bufferLODs,0):t(this._materialBufferLODs,this._materialIndexLOD):t(this._nodeBufferLODs,this._nodeIndexLOD)}return null}_loadBufferLOD(e,t){let n=e[t];n&&(this._loader.log(`Loading buffer range [${n.start}-${n.end}]`),this._loader.bin.readAsync(n.start,n.end-n.start+1).then(e=>{n.loaded.resolve(e)},e=>{n.loaded.reject(e)}))}_getLODs(e,t,n,r){if(this.maxLODsToLoad<=0)throw Error(`maxLODsToLoad must be greater than zero`);let i=[];for(let t=r.length-1;t>=0;t--)if(i.push(H.Get(`${e}/ids/${r[t]}`,n,r[t])),i.length===this.maxLODsToLoad)return i;return i.push(t),i}_disposeTransformNode(e){let t=[],n=e.material;n&&t.push(n);for(let n of e.getChildMeshes())n.material&&t.push(n.material);e.dispose();let r=t.filter(e=>this._loader.babylonScene.meshes.every(t=>t.material!=e));this._disposeMaterials(r)}_disposeMaterials(e){let t={};for(let n of e){for(let e of n.getActiveTextures())t[e.uniqueId]=e;n.dispose()}for(let e in t)for(let n of this._loader.babylonScene.materials)n.hasTexture(t[e])&&delete t[e];for(let e in t)t[e].dispose()}},Kc=!1;function qc(){Kc||(Kc=!0,m(Wc),r(Wc,!0,e=>new Gc(e)))}qc();var Jc=e({MSFT_minecraftMesh:()=>Xc,RegisterMSFT_minecraftMesh:()=>Qc}),Yc=`MSFT_minecraftMesh`,Xc=class{constructor(e){this.name=Yc,this._loader=e,this.enabled=this._loader.isExtensionUsed(Yc)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return U.LoadExtraAsync(e,t,this.name,async(r,i)=>{if(i){if(!this._loader._pbrMaterialImpls.get(`pbr`))throw Error(`${r}: Material type not supported`);let i=this._loader.loadMaterialPropertiesAsync(e,t,n);return n.needAlphaBlending()&&(n.forceDepthWrite=!0,n.separateCullingPass=!0),n.backFaceCulling=n.forceDepthWrite,n.twoSidedLighting=!0,await i}})}},Zc=!1;function Qc(){Zc||(Zc=!0,m(Yc),r(Yc,!0,e=>new Xc(e)))}Qc();var $c=e({MSFT_sRGBFactors:()=>tl,RegisterMSFT_sRGBFactors:()=>rl}),el=`MSFT_sRGBFactors`,tl=class{constructor(e){this.name=el,this._loader=e,this.enabled=this._loader.isExtensionUsed(el)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return U.LoadExtraAsync(e,t,this.name,async(r,i)=>{if(i){let r=this._loader._getOrCreateMaterialAdapter(n),i=this._loader.loadMaterialPropertiesAsync(e,t,n),a=n.getScene().getEngine().useExactSrgbConversions;return r.baseColorTexture||r.baseColor.toLinearSpaceToRef(r.baseColor,a),r.specularColorTexture||r.specularColor.toLinearSpaceToRef(r.specularColor,a),await i}})}},nl=!1;function rl(){nl||(nl=!0,m(el),r(el,!0,e=>new tl(e)))}rl(),Or(),Te(),ue(),yt();var il=2e4;function al(e){return e===`flow/waitAll`?!1:e.startsWith(`flow/`)||e.startsWith(`animation/`)||e===`pointer/set`||e===`pointer/interpolate`||e===`variable/set`||e===`variable/interpolate`||e===`event/send`||e===`event/stopPropagation`||e===`flow/log:BABYLON`}function ol(e){let t=e=>{if(Array.isArray(e))return e.slice();if(typeof e==`object`&&e){if(typeof e.asArray==`function`)return Array.from(e.asArray());if(Object.prototype.hasOwnProperty.call(e,`value`)){let t=e.value;return Array.isArray(t)?t.slice():[t]}}return[e]};return Array.isArray(e)?e.filter(e=>
4typeof e==`object`&&!!e&&typeof e.id==`string`).map(e=>({id:e.id,type:e.type,...e.value===void 0?{}:{value:t(e.value)}})).sort((e,t)=>e.id.localeCompare(t.id)):typeof e==`object`&&e?Object.entries(e).map(([e,n])=>{if(typeof n!=`object`||!n)return{id:e,malformed:!0};let r=n;return{id:e,type:typeof r.type==`string`?r.type:r.type?.typeName,...r.value===void 0?{}:{value:t(r.value)}}}).sort((e,t)=>e.id.localeCompare(t.id)):e}function sl(e,t=!0){let n=e.extension?ul(dl,e.extension):void 0,r=e.extension?ul(n,e.op):ul(fl,e.op);return!r&&t?(A.Warn(`No mapping found for operation ${e.op} and extension ${e.extension||`KHR_interactivity`}`),cl(e)):r}function cl(e){let t={},n={flows:{}};if(e.inputValueSockets){t.values=Object.create(null);for(let n in e.inputValueSockets)Object.prototype.hasOwnProperty.call(e.inputValueSockets,n)&&Object.defineProperty(t.values,n,{configurable:!0,enumerable:!0,value:{name:n},writable:!0})}return e.outputValueSockets&&(n.values=Object.create(null),Object.keys(e.outputValueSockets).forEach(e=>{Object.defineProperty(n.values,e,{configurable:!0,enumerable:!0,value:{name:e},writable:!0})})),{blocks:[],inputs:t,outputs:n}}function ll(e,t,n){let r=ul(dl,t);r||(r=Object.create(null),Object.defineProperty(dl,t,{configurable:!0,enumerable:!0,value:r,writable:!0})),Object.defineProperty(r,e,{configurable:!0,enumerable:!0,value:n,writable:!0})}function ul(e,t){return e&&Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}var dl={BABYLON:{"flow/log":{blocks:[`FlowGraphConsoleLogBlock`],inputs:{values:{message:{name:`message`},"[segment]":{name:`$1`,compatibilityOnly:!0}}},outputs:{flows:{out:{name:`out`,compatibilityOnly:!0}}}}}},fl={"event/onStart":{blocks:[`FlowGraphSceneReadyEventBlock`],outputs:{values:{event:{name:`event`}},flows:{out:{name:`done`}}}},"event/onTick":{blocks:[`FlowGraphSceneTickEventBlock`],inputs:{},outputs:{values:{timeSinceStart:{name:`timeSinceStart`,gltfType:`number`},timeSinceLastTick:{name:`deltaTime`,gltfType:`number`},event:{name:`event`}},flows:{out:{name:`done`}}}},"event/send":{blocks:[`FlowGraphSendCustomEventBlock`],configuration:{event:{name:`eventId`,configurationType:`int`,required:!0,indexSource:`events`,validationOnly:!0}},inputs:{values:{"[segment]":{name:`$1`}}},outputs:{flows:{out:{name:`out`}}},extraProcessor(e,t,n,r,i){if(t.op!==`event/send`||!e.configuration?.event)throw Error(`Send event should have a single configuration object, the event itself`);let a=e.configuration.event.value?.[0];if(typeof a!=`number`)throw Error(`Event id should be a number`);let o=r.arrays.events[a],s=i[0];return s.config||={},s.config.eventId=o.eventId,s.config.eventData=o.eventData,i}},"event/receive":{blocks:[`FlowGraphReceiveCustomEventBlock`],configuration:{event:{name:`eventId`,configurationType:`int`,required:!0,indexSource:`events`,validationOnly:!0}},outputs:{values:{event:{name:`event`},"[segment]":{name:`$1`}},flows:{out:{name:`done`}}},validation(e,t){if(!e.configuration)return A.Error(`Receive event should have a configuration object`),{valid:!1,error:`Receive event should have a configuration object`};let n=e.configuration.event;if(!n)return A.Error(`Receive event should have a single configuration object, the event itself`),{valid:!1,error:`Receive event should have a single configuration object, the event itself`};let r=n.value?.[0];return typeof r==`number`?t.events?.[r]?{valid:!0}:(A.Error(`Event with id ${r} not found`),{valid:!1,error:`Event with id ${r} not found`}):(A.Error(`Event id should be a number`),{valid:!1,error:`Event id should be a number`})},extraProcessor(e,t,n,r,i){if(t.op!==`event/receive`||!e.configuration?.event)throw Error(`Receive event should have a single configuration object, the event itself`);let a=e.configuration.event.value?.[0];if(typeof a!=`number`)throw Error(`Event id should be a number`);let o=r.arrays.events[a],s=i[0];return s.config||={},s.config.eventId=o.eventId,s.config.eventData=o.eventData,i}},"event/stopPropagation":{blocks:[`FlowGraphStopEventPropagationBlock`],inputs:{values:{event:{name:`event`},stopImmediate:{name:`stopImmediate`}},flows:{in:{name:`in`}}},outputs:{flows:{out:{name:`out`}}}},"math/E":K(`FlowGraphEBlock`,[]),"math/Pi":K(`FlowGraphPIBlock`,[]),"math/Tau":K(`FlowGraphTauBlock`,[]),"math/Inf":K(`FlowGraphInfBlock`,[]),"math/NaN":K(`FlowGraphNaNBlock`,[]),"math/abs":K(`FlowGraphAbsBlock`),"math/sign":K(`FlowGraphSignBlock`),"math/trunc":K(`FlowGraphTruncBlock`),"math/floor":K(`FlowGraphFloorBlock`),"math/ceil":K(`FlowGraphCeilBlock`),"math/round":{blocks:[`FlowGraphRoundBlock`],configuration:{},inputs:{values:{a:{name:`a`}}}
4,outputs:{values:{value:{name:`value`,typeSourceInput:`a`}}},extraProcessor(e,t,n,r,i){var a;return(a=i[0]).config||(a.config={}),i[0].config.roundHalfAwayFromZero=!0,i}},"math/fract":K(`FlowGraphFractBlock`),"math/neg":K(`FlowGraphNegationBlock`),"math/add":K(`FlowGraphAddBlock`,[`a`,`b`],!0),"math/sub":K(`FlowGraphSubtractBlock`,[`a`,`b`],!0),"math/mul":{blocks:[`FlowGraphMultiplyBlock`],inputs:{values:{a:{name:`a`},b:{name:`b`}}},outputs:{values:{value:{name:`value`,typeSourceInput:`a`}}},extraProcessor(e,t,n,r,i){var a;(a=i[0]).config||(a.config={}),i[0].config.useMatrixPerComponent=!0,i[0].config.preventIntegerFloatArithmetic=!0;let o=-1;return Object.keys(e.values||{}).find(t=>e.values?.[t].type!==void 0&&(o=e.values[t].type,!0)),o!==-1&&(i[0].config.type=r.arrays.types[o].flowGraphType),i},validation(e){return e.values?pl(e):{valid:!0}}},"math/div":K(`FlowGraphDivideBlock`,[`a`,`b`],!0),"math/rem":K(`FlowGraphModuloBlock`,[`a`,`b`]),"math/min":K(`FlowGraphMinBlock`,[`a`,`b`]),"math/max":K(`FlowGraphMaxBlock`,[`a`,`b`]),"math/clamp":K(`FlowGraphClampBlock`,[`a`,`b`,`c`]),"math/saturate":K(`FlowGraphSaturateBlock`),"math/mix":K(`FlowGraphMathInterpolationBlock`,[`a`,`b`,`c`]),"math/smoothStep":K(`FlowGraphSmoothStepBlock`,[`a`,`b`,`c`]),"math/rgbToOkLCh":{blocks:[`FlowGraphRGBToOkLChBlock`],inputs:{values:{r:{name:`r`,gltfType:`number`},g:{name:`g`,gltfType:`number`},b:{name:`b`,gltfType:`number`}}},outputs:{values:{l:{name:`l`},c:{name:`c`},h:{name:`h`}}}},"math/rgbFromOkLCh":{blocks:[`FlowGraphRGBFromOkLChBlock`],inputs:{values:{l:{name:`l`,gltfType:`number`},c:{name:`c`,gltfType:`number`},h:{name:`h`,gltfType:`number`}}},outputs:{values:{r:{name:`r`},g:{name:`g`},b:{name:`b`}}}},"math/quatSlerp":K(`FlowGraphMathSlerpBlock`,[`a`,`b`,`c`]),"math/slerp":K(`FlowGraphVectorSlerpBlock`,[`a`,`b`,`c`]),"math/eq":K(`FlowGraphEqualityBlock`,[`a`,`b`]),"ref/eq":K(`FlowGraphEqualityBlock`,[`a`,`b`]),"math/lt":K(`FlowGraphLessThanBlock`,[`a`,`b`]),"math/le":K(`FlowGraphLessThanOrEqualBlock`,[`a`,`b`]),"math/gt":K(`FlowGraphGreaterThanBlock`,[`a`,`b`]),"math/ge":K(`FlowGraphGreaterThanOrEqualBlock`,[`a`,`b`]),"math/isNaN":K(`FlowGraphIsNaNBlock`),"math/isInf":K(`FlowGraphIsInfBlock`),"math/select":{blocks:[`FlowGraphConditionalBlock`],inputs:{values:{condition:{name:`condition`},a:{name:`onTrue`},b:{name:`onFalse`}}},outputs:{values:{value:{name:`output`,typeSourceInput:`a`}}}},"math/random":{blocks:[`FlowGraphRandomBlock`],outputs:{values:{value:{name:`value`,gltfType:`float`}}}},"math/sin":K(`FlowGraphSinBlock`),"math/cos":K(`FlowGraphCosBlock`),"math/tan":K(`FlowGraphTanBlock`),"math/asin":K(`FlowGraphASinBlock`),"math/acos":K(`FlowGraphACosBlock`),"math/atan":K(`FlowGraphATanBlock`),"math/atan2":K(`FlowGraphATan2Block`,[`a`,`b`]),"math/sinh":K(`FlowGraphSinhBlock`),"math/cosh":K(`FlowGraphCoshBlock`),"math/tanh":K(`FlowGraphTanhBlock`),"math/asinh":K(`FlowGraphASinhBlock`),"math/acosh":K(`FlowGraphACoshBlock`),"math/atanh":K(`FlowGraphATanhBlock`),"math/exp":K(`FlowGraphExponentialBlock`),"math/log":K(`FlowGraphLogBlock`),"math/log2":K(`FlowGraphLog2Block`),"math/log10":K(`FlowGraphLog10Block`),"math/sqrt":K(`FlowGraphSquareRootBlock`),"math/cbrt":K(`FlowGraphCubeRootBlock`),"math/pow":K(`FlowGraphPowerBlock`,[`a`,`b`]),"math/length":K(`FlowGraphLengthBlock`),"math/normalize":{...K(`FlowGraphNormalizeBlock`),outputs:{values:{value:{name:`value`,typeSourceInput:`a`},isValid:{name:`isValid`,gltfType:`bool`}}}},"math/dot":K(`FlowGraphDotBlock`,[`a`,`b`]),"math/cross":K(`FlowGraphCrossBlock`,[`a`,`b`]),"math/rotate2D":{blocks:[`FlowGraphRotate2DBlock`],inputs:{values:{a:{name:`a`},angle:{name:`b`}}},outputs:{values:{value:{name:`value`,typeSourceInput:`a`}}}},"math/rotate3D":{blocks:[`FlowGraphRotate3DBlock`],inputs:{values:{a:{name:`a`},rotation:{name:`b`}}},outputs:{values:{value:{name:`value`,typeSourceInput:`a`}}}},"math/transform":{blocks:[`FlowGraphTransformVectorBlock`],inputs:{values:{a:{name:`a`},b:{name:`b`}}},outputs:{values:{value:{name:`value`,typeSourceInput:`a`}}}},"math/combine2":{blocks:[`FlowGraphCombineVector2Block`],inputs:{values:{a:{name:`input_0`,gltfType:`number`},b:{name:`input_1`,gltfType:`number`}}},outputs:{values:{value:{name:`value`,gltfType:`float2`}}}},"math/combine3":{blocks:[`FlowGraphCombineVector3Block`],inputs:{values:{a:{name:`input_0`,gltfType:`number`},b:{name:`input_1`,gltfType:`number`},c:{name:`input_2`,gltfType:`number`}}},outputs:{values:{value:{name:`value`,gltfType:`float3`}}}},"math/combine4":{blocks:[`FlowGraphCombineVector4Block`],inputs:{values:{a:{name:`input_0`,gltfType:`number`},b:{name:`input_1`,gltfType:`number`},c:{name:`input_2`,gltfType:`number`},d:{name:`input_3`,gltfType:`number`}}},outputs:{values:{value:{name:`value`,gltfType:`float4`}}}},"math/extract2":{blocks:[`FlowGraphExtractVector2Block`],inputs:{values:{a:{name:`input`,gltfType:`number`}}},outputs:{values:{0:{name:`output_0`},1:{name:`output_1`}}}},"math/extract3":{blocks:[`FlowGraphExtractVector3Block`],inputs:{values:{a:{name:`input`,gltfType:`number`}}},outputs:{values:{0:{name:`output_0`},1:{name:`output_1`},2:{name:`output_2`}}}},"math/extract4":{blocks:[`FlowGraphExtractVector4Block`],inputs:{values:{a:{name:`input`,gltfType:`number`}}},outputs:{values:{0:{name:`output_0`},1:{name:`output_1`},2:{name:`output_2`},3:{name:`output_3`}}}},"math/transpose":K(`FlowGraphTransposeBlock`),"math/determinant":K(`FlowGraphDeterminantBlock`),"math/inverse":{...K(`FlowGraphInvertMatrixBlock`),outputs:{values:{value:{name:`value`,typeSourceIn
4put:`a`},isValid:{name:`isValid`,gltfType:`bool`}}}},"math/matMul":K(`FlowGraphMatrixMultiplicationBlock`,[`a`,`b`]),"math/matCompose":{blocks:[`FlowGraphMatrixCompose`],inputs:{values:{translation:{name:`position`,gltfType:`float3`},rotation:{name:`rotationQuaternion`,gltfType:`float4`},scale:{name:`scaling`,gltfType:`float3`}}},outputs:{values:{value:{name:`value`,gltfType:`float4x4`}}},extraProcessor(e,t,n,r,i,a){let o=i[0].dataInputs.find(e=>e.name===`rotationQuaternion`);if(!o)throw Error(`Rotation quaternion input not found`);return a._connectionValues[o.uniqueId]&&(a._connectionValues[o.uniqueId].type=`Quaternion`),i}},"math/matDecompose":{blocks:[`FlowGraphMatrixDecompose`],inputs:{values:{a:{name:`input`,gltfType:`number`}}},outputs:{values:{translation:{name:`position`},rotation:{name:`rotationQuaternion`},scale:{name:`scaling`},scaling:{name:`scaling`,compatibilityOnly:!0},isValid:{name:`isValid`,compatibilityOnly:!0}}},extraProcessor(e,t,n,r,i){var a;return(a=i[0]).config||(a.config={}),i[0].config.keepDegenerateComponents=!0,i}},"math/quatConjugate":K(`FlowGraphConjugateBlock`,[`a`]),"math/quatMul":{blocks:[`FlowGraphMultiplyBlock`],inputs:{values:{a:{name:`a`,gltfType:`float4`},b:{name:`b`,gltfType:`float4`}}},outputs:{values:{value:{name:`value`,gltfType:`float4`}}},extraProcessor(e,t,n,r,i){var a;return(a=i[0]).config||(a.config={}),i[0].config.type=`Quaternion`,i}},"math/quatAngleBetween":K(`FlowGraphAngleBetweenBlock`,[`a`,`b`]),"math/quatFromAxisAngle":{blocks:[`FlowGraphQuaternionFromAxisAngleBlock`],inputs:{values:{axis:{name:`a`,gltfType:`float3`},angle:{name:`b`,gltfType:`number`}}},outputs:{values:{value:{name:`value`,gltfType:`float4`}}}},"math/quatToAxisAngle":{blocks:[`FlowGraphAxisAngleFromQuaternionBlock`],inputs:{values:{a:{name:`a`,gltfType:`float4`}}},outputs:{values:{axis:{name:`axis`,gltfType:`float3`},angle:{name:`angle`,gltfType:`float`}}}},"math/quatFromDirections":{...K(`FlowGraphQuaternionFromDirectionsBlock`,[`a`,`b`]),outputs:{values:{value:{name:`value`,gltfType:`float4`}}}},"math/quatFromUpForward":{blocks:[`FlowGraphQuaternionFromUpForwardBlock`],inputs:{values:{up:{name:`a`,gltfType:`float3`},forward:{name:`b`,gltfType:`float3`}}},outputs:{values:{value:{name:`value`,gltfType:`float4`}}}},"math/quatFromAngles":{blocks:[`FlowGraphQuaternionFromAnglesBlock`],configuration:{order:{name:`order`,defaultValue:[`yxz`],configurationType:`string`,invalidUsesDefault:!0,allowedValues:[`xyz`,`xzy`,`yxz`,`yzx`,`zxy`,`zyx`]}},inputs:{values:{x:{name:`a`,gltfType:`number`},y:{name:`b`,gltfType:`number`},z:{name:`c`,gltfType:`number`}}},outputs:{values:{value:{name:`value`,gltfType:`float4`}}}},"math/combine2x2":{blocks:[`FlowGraphCombineMatrix2DBlock`],inputs:{values:{a:{name:`input_0`,gltfType:`number`},b:{name:`input_1`,gltfType:`number`},c:{name:`input_2`,gltfType:`number`},d:{name:`input_3`,gltfType:`number`}}},outputs:{values:{value:{name:`value`,gltfType:`float2x2`}}}},"math/extract2x2":{blocks:[`FlowGraphExtractMatrix2DBlock`],inputs:{values:{a:{name:`input`,gltfType:`float2x2`}}},outputs:{values:{0:{name:`output_0`},1:{name:`output_1`},2:{name:`output_2`},3:{name:`output_3`}}}},"math/combine3x3":{blocks:[`FlowGraphCombineMatrix3DBlock`],inputs:{values:{a:{name:`input_0`,gltfType:`number`},b:{name:`input_1`,gltfType:`number`},c:{name:`input_2`,gltfType:`number`},d:{name:`input_3`,gltfType:`number`},e:{name:`input_4`,gltfType:`number`},f:{name:`input_5`,gltfType:`number`},g:{name:`input_6`,gltfType:`number`},h:{name:`input_7`,gltfType:`number`},i:{name:`input_8`,gltfType:`number`}}},outputs:{values:{value:{name:`value`,gltfType:`float3x3`}}}},"math/extract3x3":{blocks:[`FlowGraphExtractMatrix3DBlock`],inputs:{values:{a:{name:`input`,gltfType:`float3x3`}}},outputs:{values:{0:{name:`output_0`},1:{name:`output_1`},2:{name:`output_2`},3:{name:`output_3`},4:{name:`output_4`},5:{name:`output_5`},6:{name:`output_6`},7:{name:`output_7`},8:{name:`output_8`}}}},"math/combine4x4":{blocks:[`FlowGraphCombineMatrixBlock`],inputs:{values:{a:{name:`input_0`,gltfType:`number`},b:{name:`input_1`,gltfType:`number`},c:{name:`input_2`,gltfType:`number`},d:{name:`input_3`,gltfType:`number`},e:{name:`input_4`,gltfType:`number`},f:{name:`input_5`,gltfType:`number`},g:{name:`input_6`,gltfType:`number`},h:{name:`input_7`,gltfType:`number`},i:{name:`input_8`,gltfType:`number`}
4,j:{name:`input_9`,gltfType:`number`},k:{name:`input_10`,gltfType:`number`},l:{name:`input_11`,gltfType:`number`},m:{name:`input_12`,gltfType:`number`},n:{name:`input_13`,gltfType:`number`},o:{name:`input_14`,gltfType:`number`},p:{name:`input_15`,gltfType:`number`}}},outputs:{values:{value:{name:`value`,gltfType:`float4x4`}}}},"math/extract4x4":{blocks:[`FlowGraphExtractMatrixBlock`],configuration:{},inputs:{values:{a:{name:`input`,gltfType:`number`}}},outputs:{values:{0:{name:`output_0`},1:{name:`output_1`},2:{name:`output_2`},3:{name:`output_3`},4:{name:`output_4`},5:{name:`output_5`},6:{name:`output_6`},7:{name:`output_7`},8:{name:`output_8`},9:{name:`output_9`},10:{name:`output_10`},11:{name:`output_11`},12:{name:`output_12`},13:{name:`output_13`},14:{name:`output_14`},15:{name:`output_15`}}}},"math/not":{blocks:[`FlowGraphBitwiseNotBlock`],inputs:{values:{a:{name:`a`}}},outputs:{values:{value:{name:`value`,typeSourceInput:`a`}}},extraProcessor(e,t,n,r,i,a){var o;(o=i[0]).config||(o.config={});let s=i[0].dataInputs[0];return i[0].config.valueType=a._connectionValues[s.uniqueId]?.type??`FlowGraphInteger`,i}},"math/and":{blocks:[`FlowGraphBitwiseAndBlock`],inputs:{values:{a:{name:`a`},b:{name:`b`}}},outputs:{values:{value:{name:`value`,typeSourceInput:`a`}}},extraProcessor(e,t,n,r,i,a){var o;(o=i[0]).config||(o.config={});let s=i[0].dataInputs[0],c=i[0].dataInputs[1];return i[0].config.valueType=a._connectionValues[s.uniqueId]?.type??a._connectionValues[c.uniqueId]?.type??`FlowGraphInteger`,i}},"math/or":{blocks:[`FlowGraphBitwiseOrBlock`],inputs:{values:{a:{name:`a`},b:{name:`b`}}},outputs:{values:{value:{name:`value`,typeSourceInput:`a`}}},extraProcessor(e,t,n,r,i,a){var o;(o=i[0]).config||(o.config={});let s=i[0].dataInputs[0],c=i[0].dataInputs[1];return i[0].config.valueType=a._connectionValues[s.uniqueId]?.type??a._connectionValues[c.uniqueId]?.type??`FlowGraphInteger`,i}},"math/xor":{blocks:[`FlowGraphBitwiseXorBlock`],inputs:{values:{a:{name:`a`},b:{name:`b`}}},outputs:{values:{value:{name:`value`,typeSourceInput:`a`}}},extraProcessor(e,t,n,r,i,a){var o;(o=i[0]).config||(o.config={});let s=i[0].dataInputs[0],c=i[0].dataInputs[1];return i[0].config.valueType=a._connectionValues[s.uniqueId]?.type??a._connectionValues[c.uniqueId]?.type??`FlowGraphInteger`,i}},"math/asr":K(`FlowGraphBitwiseRightShiftBlock`,[`a`,`b`]),"math/lsl":K(`FlowGraphBitwiseLeftShiftBlock`,[`a`,`b`]),"math/clz":K(`FlowGraphLeadingZerosBlock`),"math/ctz":K(`FlowGraphTrailingZerosBlock`),"math/popcnt":K(`FlowGraphOneBitsCounterBlock`),"math/rad":K(`FlowGraphDegToRadBlock`),"math/deg":K(`FlowGraphRadToDegBlock`),"type/boolToInt":K(`FlowGraphBooleanToInt`),"type/boolToFloat":K(`FlowGraphBooleanToFloat`),"type/intToBool":K(`FlowGraphIntToBoolean`),"type/intToFloat":K(`FlowGraphIntToFloat`),"type/floatToInt":K(`FlowGraphFloatToInt`),"type/floatToBool":K(`FlowGraphFloatToBoolean`),"flow/sequence":{blocks:[`FlowGraphSequenceBlock`],outputs:{flows:{"[segment]":{name:`$1`}}},extraProcessor(e,t,n,r,i){let a=i[0];return a.config||={},a.config.outputSignalCount=Object.keys(e.flows||[]).length,a.signalOutputs.forEach((e,t)=>{e.name=`out_`+t}),i}},"flow/branch":{blocks:[`FlowGraphBranchBlock`],inputs:{values:{condition:{name:`condition`,gltfType:`boolean`}}},outputs:{flows:{true:{name:`onTrue`},false:{name:`onFalse`}}}},"flow/switch":{blocks:[`FlowGraphSwitchBlock`],configuration:{cases:{name:`cases`,isArray:!0,inOptions:!0,defaultValue:[],configurationType:`int[]`,invalidUsesDefault:!0,generatesOutputFlowSockets:!0,uniqueValues:!0}},inputs:{values:{selection:{name:`case`},default:{name:`default`}}},outputs:{flows:{default:{name:`default`},"[segment]":{name:`$1`}}},validation(e){let t=e.configuration?.cases;if(t&&t.value){if(!t.value.every(e=>typeof e==`number`&&Number.isInteger(e)&&e>=-2147483648&&e<=2147483647))return A.Warn(`Switch cases should be integers. Using empty array instead.`),t.value=[],{valid:!0};let e=new Set(t.value);t.value=Array.from(e)}return{valid:!0}},extraProcessor(e,t,n,r,i){if(t.op!==`flow/switch`||!e.flows||Object.keys(e.flows).length===0)throw Error(`Switch should have a single configuration object, the cases array`);
4return i[0].signalOutputs.forEach(e=>{e.name!=="default"&&(e.name=`out_`+e.name)}),i}},"flow/while":{blocks:[`FlowGraphWhileLoopBlock`],inputs:{values:{condition:{name:`condition`,gltfType:`boolean`}}},outputs:{flows:{loopBody:{name:`executionFlow`},completed:{name:`completed`}}}},"flow/for":{blocks:[`FlowGraphForLoopBlock`],configuration:{initialIndex:{name:`initialIndex`,gltfType:`int`,inOptions:!0,defaultValue:0,configurationType:`int`,invalidUsesDefault:!0}},inputs:{values:{startIndex:{name:`startIndex`,gltfType:`int`},endIndex:{name:`endIndex`,gltfType:`int`}}},outputs:{values:{index:{name:`index`}},flows:{loopBody:{name:`executionFlow`},completed:{name:`completed`}}},extraProcessor(e,t,n,r,i){let a=i[0];return a.config||={},a.config.incrementIndexWhenLoopDone=!0,a.config.maxLoopIterations=il,i}},"flow/doN":{blocks:[`FlowGraphDoNBlock`],configuration:{},inputs:{values:{n:{name:`maxExecutions`,gltfType:`int`}},flows:{reset:{name:`reset`}}},outputs:{flows:{out:{name:`out`}},values:{currentCount:{name:`executionCount`}}}},"flow/multiGate":{blocks:[`FlowGraphMultiGateBlock`],inputs:{flows:{reset:{name:`reset`}}},configuration:{isRandom:{name:`isRandom`,gltfType:`boolean`,inOptions:!0,defaultValue:!1,configurationType:`bool`,invali
4dUsesDefault:!0,configurationGroup:`multiGate`},isLoop:{name:`isLoop`,gltfType:`boolean`,inOptions:!0,defaultValue:!1,configurationType:`bool`,invalidUsesDefault:!0,configurationGroup:`multiGate`}},outputs:{flows:{"[segment]":{name:`$1`}},values:{lastIndex:{name:`lastIndex`,gltfType:`int`}}},extraProcessor(e,t,n,r,i){if(t.op!==`flow/multiGate`)throw Error(`Invalid operation for MultiGate mapping`);let a=i[0];return a.config||={},a.config.outputSignalCount=Object.keys(e.flows??{}).length,a.signalOutputs.forEach((e,t)=>{e.name=`out_`+t}),i}},"flow/waitAll":{blocks:[`FlowGraphWaitAllBlock`],configuration:{inputFlows:{name:`inputSignalCount`,gltfType:`number`,inOptions:!0,defaultValue:[0],configurationType:`int`,invalidUsesDefault:!0,minimum:0,maximum:64,generatesInputFlowSockets:!0}},inputs:{flows:{reset:{name:`reset`},"[segment]":{name:`in_$1`}}},outputs:{flows:{out:{name:`out`},completed:{name:`completed`}},values:{remainingInputs:{name:`remainingInputs`,gltfType:`int`}}},validation(e){let t=e.configuration?.inputFlows?.value,n=t?.[0];return(t?.length!==1||typeof n!=`number`||!Number.isInteger(n)||n<0||n>64)&&(e.configuration=e.configuration||{inputFlows:{value:[0]}},e.configuration.inputFlows.value=[0]),{valid:!0}}},"flow/throttle":{blocks:[`FlowGraphThrottleBlock`],inputs:{values:{duration:{name:`duration`,gltfType:`number`}},flows:{reset:{name:`reset`}}},outputs:{flows:{out:{name:`out`},err:{name:`error`}},values:{lastRemainingTime:{name:`lastRemainingTime`,gltfType:`number`}}}},"flow/setDelay":{blocks:[`FlowGraphSetDelayBlock`],inputs:{values:{duration:{name:`duration`,gltfType:`number`}},flows:{cancel:{name:`cancel`}}},outputs:{flows:{out:{name:`out`},err:{name:`error`},done:{name:`done`}},values:{lastDelay:{name:`lastDelayIndex`},lastDelayIndex:{name:`lastDelayIndex`,compatibilityOnly:!0}}}},"flow/cancelDelay":{blocks:[`FlowGraphCancelDelayBlock`],inputs:{values:{delay:{name:`delayIndex`,gltfType:`ref`}}},outputs:{flows:{out:{name:`out`}}}},"variable/get":{blocks:[`FlowGraphGetVariableBlock`],validation(e){return e.configuration?.variable?.value?{valid:!0}:(A.Error(`Variable get block should have a variable configuration`),{valid:!1,error:`Variable get block should have a variable configuration`})},configuration:{variable:{name:`variable`,gltfType:`number`,configurationType:`int`,required:!0,indexSource:`variables`,flowGraphType:`string`,inOptions:!0,isVariable:!0,dataTransformer(e,t){return t.getVariableName(e)}}},outputs:{values:{value:{name:`value`}}}},"variable/set":{blocks:[`FlowGraphSetVariableBlock`],inputs:{values:{"[segment]":{name:`$1`}}},configuration:{variables:{name:`variables`,gltfType:`number`,configurationType:`int[]`,required:!0,indexSource:`variables`,minItems:1,generatesInputValueSockets:!0,flowGraphType:`string`,inOptions:!0,isArray:!0,dataTransformer(e,t){return e.map(e=>t.getVariableName(e))}}},outputs:{flows:{out:{name:`out`,compatibilityOnly:!0}}},extraProcessor(e,t,n,r,i){return i[0].dataInputs.forEach(e=>{e.name=r.getVariableName(+e.name)}),i}},"variable/interpolate":{blocks:[`FlowGraphInterpolationBlock`,`FlowGraphContextBlock`,`FlowGraphPlayAnimationBlock`,`FlowGraphBezierCurveEasing`,`FlowGraphGetVariableBlock`],configuration:{variable:{name:`propertyName`,configurationType:`int`,required:!0,indexSource:`variables`,inOptions:!0,isVariable:!0,dataTransformer(e,t){return t.getVariableName(e)}},useSlerp:{name:`animationType`,configurationType:`bool`,required:!0,inOptions:!0,dataTransformer(e){return e===!0?`Quaternion`:void 0}}},inputs:{values:{value:{name:`value_1`},duration:{name:`duration_1`,gltfType:`number`},p1:{name:`controlPoint1`,toBlock:`FlowGraphBezierCurveEasing`},p2:{name:`controlPoint2`,toBlock:`FlowGraphBezierCurveEasing`}},flows:{in:{name:`in`,toBlock:`FlowGraphPlayAnimationBlock`}}},outputs:{flows:{err:{name:`error`,toBlock:`FlowGraphPlayAnimationBlock`},out:{name:`out`,toBlock:`FlowGraphPlayAnimationBlock`},done:{name:`done`,toBlock:`FlowGraphPlayAnimationBlock`}}},interBlockConnectors:[{input:`object`,output:`userVariables`,inputBlockIndex:2,outputBlockIndex:1,isVariable:!0},{input:`animation`,output:`animation`,inputBlockIndex:2,outputBlockIndex:0,isVariable:!0},{input:`easingFunction`,output:`easingFunction`,inputBlockIndex:0,outputBlockIndex:3,isVariable:!0},{input:`value_0`,output:`value`,inputBlockIndex:0,outputBlockIndex:4,isVariable:!0}],extraProcessor(e,t,n,r,i){var a,o;let s=i[0],c=e.configuration?.variable.value?.[0];if(typeof c!=`number`)throw A.Error(`Variable index is not defined for variable interpolation block`),Error(`Variable index is not defined for variable interpolation block`);let l=r.arrays.staticVariables[c];s.config?.animationType?.value===void 0&&(s.config||={},(a=s.config).animationType||(a.animationType={}),s.config.animationType.value=pe(l.type));let u=i[4];return u.config||={},(o=u.config).variable||(o.variable={}),u.config.variable.value=r.getVariableName(c),i}},"pointer/get":{blocks:[`FlowGraphGetPropertyBlock`,`FlowGraphJsonPointerParserBlock`],validation:e=>gl(e),configuration:{pointer:{name:`jsonPointer`,toBlock:`FlowGraphJsonPointerParserBlock`,configurationType:`string`,required:!0,pointerTemplate:!0},type:{name:`type`,configurationType:`int`,required:!0,validationOnly:!0,indexSource:`types`}},inputs:{values:{"[segment]":{name:`$1`,toBlock:`FlowGraphJsonPointerParserBlock`}}},outputs:{values:{value:{name:`value`},isValid:{name:`isValid`,gltfType:`bool`}}},interBlockConnectors:[{input:`object`,output:`object`,inputBlockIndex:0,outputBlockIndex:1,isVariable:!0},{input:`propertyName`,output:`propertyName`,inputBlockIndex:0,outputBlockIndex:1,isVariable:!0},{input:`customGetFunction`,output:`getFunction`,inputBlockIndex:0,outputBlockIndex:1,isVariable:!0}
4],extraProcessor(e,t,n,r,i){return i.forEach(e=>{e.className===`FlowGraphJsonPointerParserBlock`&&(e.config||={},e.config.outputValue=!0)}),i}},"pointer/set":{blocks:[`FlowGraphSetPropertyBlock`,`FlowGraphJsonPointerParserBlock`],validation:e=>gl(e,new Set([`value`])),configuration:{pointer:{name:`jsonPointer`,toBlock:`FlowGraphJsonPointerParserBlock`,configurationType:`string`,required:!0,pointerTemplate:!0},type:{name:`type`,configurationType:`int`,required:!0,validationOnly:!0,indexSource:`types`}},inputs:{values:{value:{name:`value`},"[segment]":{name:`$1`,toBlock:`FlowGraphJsonPointerParserBlock`}}},outputs:{flows:{err:{name:`error`},out:{name:`out`,compatibilityOnly:!0}}},interBlockConnectors:[{input:`object`,output:`object`,inputBlockIndex:0,outputBlockIndex:1,isVariable:!0},{input:`propertyName`,output:`propertyName`,inputBlockIndex:0,outputBlockIndex:1,isVariable:!0},{input:`customSetFunction`,output:`setFunction`,inputBlockIndex:0,outputBlockIndex:1,isVariable:!0}],extraProcessor(e,t,n,r,i){return i.forEach(e=>{e.className===`FlowGraphJsonPointerParserBlock`&&(e.config||={},e.config.outputValue=!0)}),i}},"pointer/interpolate":{blocks:[`FlowGraphInterpolationBlock`,`FlowGraphJsonPointerParserBlock`,`FlowGraphPlayAnimationBlock`,`FlowGraphBezierCurveEasing`],validation:e=>gl(e,new Set([`value`,`duration`,`p1`,`p2`])),configuration:{pointer:{name:`jsonPointer`,toBlock:`FlowGraphJsonPointerParserBlock`,configurationType:`string`,required:!0,pointerTemplate:!0},type:{name:`type`,configurationType:`int`,required:!0,validationOnly:!0,indexSource:`types`,allowedSignatures:[`float`,`float2`,`float3`,`float4`,`float2x2`,`float3x3`,`float4x4`]}},inputs:{values:{value:{name:`value_1`},"[segment]":{name:`$1`,toBlock:`FlowGraphJsonPointerParserBlock`},duration:{name:`duration_1`,gltfType:`number`},p1:{name:`controlPoint1`,toBlock:`FlowGraphBezierCurveEasing`},p2:{name:`controlPoint2`,toBlock:`FlowGraphBezierCurveEasing`}},flows:{in:{name:`in`,toBlock:`FlowGraphPlayAnimationBlock`}}},outputs:{flows:{err:{name:`error`,toBlock:`FlowGraphPlayAnimationBlock`},out:{name:`out`,toBlock:`FlowGraphPlayAnimationBlock`},done:{name:`done`,toBlock:`FlowGraphPlayAnimationBlock`}}},interBlockConnectors:[{input:`object`,output:`object`,inputBlockIndex:2,outputBlockIndex:1,isVariable:!0},{input:`propertyName`,output:`propertyName`,inputBlockIndex:0,outputBlockIndex:1,isVariable:!0},{input:`customBuildAnimation`,output:`generateAnimationsFunction`,inputBlockIndex:0,outputBlockIndex:1,isVariable:!0},{input:`animation`,output:`animation`,inputBlockIndex:2,outputBlockIndex:0,isVariable:!0},{input:`easingFunction`,output:`easingFunction`,inputBlockIndex:0,outputBlockIndex:3,isVariable:!0},{input:`value_0`,output:`value`,inputBlockIndex:0,outputBlockIndex:1,isVariable:!0}],extraProcessor(e,t,n,r,i){return i.forEach(t=>{t.className===`FlowGraphJsonPointerParserBlock`?(t.config||={},t.config.outputValue=!0):t.className===`FlowGraphInterpolationBlock`&&(t.config||={},Object.keys(e.values||[]).forEach(n=>{let i=e.values?.[n];if(n===`value`&&i){let e=i.type;e!==void 0&&(t.config.animationType=r.arrays.types[e].flowGraphType)}}))}),i}},"animation/start":{blocks:[`FlowGraphPlayAnimationBlock`,`FlowGraphArrayIndexBlock`,`KHR_interactivity/FlowGraphGLTFDataProvider`],inputs:{values:{animation:{name:`index`,gltfType:`ref`,toBlock:`FlowGraphArrayIndexBlock`},speed:{name:`speed`,gltfType:`number`},startTime:{name:`from`,gltfType:`number`,convertConnectedTimeToFrames:!0,dataTransformer:(e,t)=>[e[0]*t._animationTargetFps]},endTime:{name:`to`,gltfType:`number`,convertConnectedTimeToFrames:!0,dataTransformer:(e,t)=>[e[0]*t._animationTargetFps]}}},outputs:{flows:{out:{name:`out`},err:{name:`error`},done:{name:`done`}}},interBlockConnectors:[{input:`animationGroup`,output:`value`,inputBlockIndex:0,outputBlockIndex:1,isVariable:!0},{input:`array`,output:`animationGroups`,inputBlockIndex:1,outputBlockIndex:2,isVariable:!0}],extraProcessor(e,t,n,r,i,a,o){let s=i.find(e=>e.className===`FlowGraphPlayAnimationBlock`);s&&(s.config.useVirtualTimeline=!0);let c=i.find(e=>e.className===`FlowGraphArrayIndexBlock`);c&&(c.config.referenceCollection=`animations`);let l=i[i.length-1];return l.config||={},l.config.glTF=o,i}},"animation/stop":{blocks:[`FlowGraphStopAnimationBlock`,`FlowGraphArrayIndexBlock`,`KHR_interactivity/FlowGraphGLTFDataProvider`],inputs:{values:{animation:{name:`index`,gltfType:`ref`,toBlock:`FlowGraphArrayIndexBlock`}}},outputs:{flows:{out:{name:`out`},err:{name:`error`}}},interBlockConnectors:[{input:`animationGroup`,output:`value`,inputBlockIndex:0,outputBlockIndex:1,isVariable:!0},{input:`array`,output:`animationGroups`,inputBlockIndex:1,outputBlockIndex:2,isVariable:!0}],extraProcessor(e,t,n,r,i,a,o){let s=i.find(e=>e.className===`FlowGraphStopAnimationBlock`);s&&(s.config.skipOnAnimationEnd=!0);let c=i.find(e=>e.className===`FlowGraphArrayIndexBlock`);c&&(c.config.referenceCollection=`animations`);let l=i[i.length-1];return l.config||={},l.config.glTF=o,i}},"animation/stopAt":{blocks:[`FlowGraphStopAnimationBlock`,`FlowGraphArrayIndexBlock`,`KHR_interactivity/FlowGraphGLTFDataProvider`],configuration:{},inputs:{values:{animation:{name:`index`,gltfType:`ref`,toBlock:`FlowGraphArrayIndexBlock`},stopTime:{name:`stopAtFrame`,gltfType:`number`,convertConnectedTimeToFrames:!0,dataTransformer:(e,t)=>[e[0]*t._animationTargetFps]}}},outputs:{flows:{out:{name:`out`},err:{name:`error`},done:{name:`done`}}},interBlockConnectors:[{input:`animationGroup`,output:`value`,inputBlockIndex:0,outputBlockIndex:1,isVariable:!0},{input:`array`,output:`animationGroups`,inputBlockIndex:1,outputBlockIndex:2,isVariable:!0}],extraProcessor(e,t,n,r,i,a,o){let s=i.find(e=>e.className===`FlowGraphStopAnimationBlock`);s&&(s.config.useVirtualStopAt=!0,s.config.skipOnAnimationEnd=!0);let c=i.find(e=>e.className===`FlowGraphArrayIndexBlock`);c&&(c.config.referenceCollection=`animations`);let l=i[i.length-1];return l.config||={},l.config.glTF=o,i}},"math/switch":{blocks:[`FlowGraphDataSwitchBlock`],configuration:{cases:{name:`cases`,isArray:!0,inOptions:!0,defaultValue:[],configurationType:`int[]`,invalidUsesDefault:!0,generatesCaseInputValueSockets:!0,uniqueValues:!0}},inputs:{values:{selection:{name:`case`,gltfType:`int`},default:{name:`default`},"[case]":{name:`$1`}}},outputs:{values:{value:{name:`value`}}},validation(e){let t=e.configuration?.cases;if(t&&t.value){if(!t.value.every(e=>typeof e==`number`&&/^-?\d+$/.test(e.toString())))return A.Warn(`Switch cases should be integers. Using empty array instead.`),t.value=[],{valid:!0};let e=new Set(t.value);t.value=Array.from(e)}return{valid:!0}},extraProcessor(e,t,n,r,i){let a=i[0];
4return a.dataInputs.forEach(e=>{e.name!=="default"&&e.name!==`case`&&(e.name=`in_`+e.name)}),a.config||={},a.config.treatCasesAsIntegers=!0,i}},"debug/log":{blocks:[`FlowGraphConsoleLogBlock`],inputs:{flows:{in:{name:`in`}},values:{"[parameter]":{name:`$1`}}},outputs:{flows:{out:{name:`out`}}},configuration:{severity:{name:`severity`,configurationType:`int`,defaultValue:0,invalidUsesDefault:!0,validationOnly:!0,configurationGroup:`debugLog`},message:{name:`messageTemplate`,configurationType:`string`,defaultValue:``,invalidUsesDefault:!0,inOptions:!0,configurationGroup:`debugLog`,debugLogTemplate:!0}}}};function K(e,t=[`a`],n){return{blocks:[e],inputs:{values:t.reduce((e,t)=>(e[t]={name:t},e),{})},outputs:{values:{value:{name:`value`,typeSourceInput:t[0]}}},extraProcessor(e,t,r,i,a){var o;if(n){(o=a[0]).config||(o.config={}),a[0].config.preventIntegerFloatArithmetic=!0;let t=-1;Object.keys(e.values||{}).find(n=>e.values?.[n].type!==void 0&&(t=e.values[n].type,!0)),t!==-1&&(a[0].config.type=i.arrays.types[t].flowGraphType)}return a},validation(e){return n?pl(e):{valid:!0}}}}function pl(e){if(e.values){let t=Object.keys(e.values).map(t=>e.values[t].type).filter(e=>e!==void 0);if(!t.every(e=>e===t[0]))return{valid:!1,error:`All inputs must be of the same type`}}return{valid:!0}}function ml(e){for(let t=0;t<e.length;t++){let n=e[t];if(`[]{}`.indexOf(n)===-1)continue;let r=1;for(;e[t+r]===n;)r++;if(r%2!=0)return!0;t+=r-1}return!1}function hl(e){let t=0,n=-1,r=[],i=new Set;for(let a=0;a<e.length;a++){let o=e[a];if(o===`{`){if(t===0)t=1;else if(t===1)t=0;else return{valid:!1,sockets:[]}}else if(o===`}`){if(t===0)t=3;else if(t===3)t=0;else if(t===2){let o=e.substring(n+1,a);i.has(o)||(i.add(o),r.push(o)),t=0}else return{valid:!1,sockets:[]}}else if(t===1)n=a-1,t=2;else if(t===3)return{valid:!1,sockets:[]}}return{valid:t===0,sockets:t===0?r:[]}}function gl(e,t=new Set){let n=e.configuration?.pointer?.value?.[0];if(typeof n!=`string`)return{valid:!1,error:"A pointer operation requires a string `pointer` configuration value"};if(n.length!==0&&n[0]!==`/`)return{valid:!1,error:`The JSON Pointer Template "${n}" is not a syntactically valid JSON Pointer`};let r=e=>({valid:!1,error:`The JSON Pointer Template "${n}" is invalid: ${e}`}),i=new Set;for(let e of n.split(`/`)){if(/~(?:[^01]|$)/.test(e))return r(`the path segment "${e}" contains an invalid RFC 6901 escape`);let n=e[0]===`[`&&e[1]!==`[`,a=e[0]===`{`&&e[1]!==`{`;if(!n&&!a){if(ml(e))return r(`the path segment "${e}" contains an odd number of consecutive brackets`);continue}let o=n?`]`:`}`,s=e.substring(1,e.length-1);if(e.length<3||e[e.length-1]!==o||/[[{]/.test(s)||/[\]}]/.test(s))return r(`the template parameter path segment "${e}" is malformed`);let c=s.replace(/~1/g,`/`).replace(/~0/g,`~`);if(t.has(c))return r(`the template parameter "${c}" uses a reserved input socket id`);if(i.has(c))return r(`the template parameter "${c}" is used more than once`);i.add(c)}return{valid:!0}}var _l=`f798712c5685bc9223a628140fba707db8889300`,vl={float:{length:1,flowGraphType:`number`,elementType:`number`},bool:{length:1,flowGraphType:`boolean`,elementType:`boolean`},float2:{length:2,flowGraphType:`Vector2`,elementType:`number`},float3:{length:3,flowGraphType:`Vector3`,elementType:`number`},float4:{length:4,flowGraphType:`Vector4`,elementType:`number`},float4x4:{length:16,flowGraphType:`Matrix`,elementType:`number`},float2x2:{length:4,flowGraphType:`Matrix2D`,elementType:`number`},float3x3:{length:9,flowGraphType:`Matrix3D`,elementType:`number`},int:{length:1,flowGraphType:`FlowGraphInteger`,elementType:`number`},ref:{length:1,flowGraphType:`string`,elementType:`string`},custom:{length:0,flowGraphType:`any`,elementType:`any`}};function yl(e){if(e!==void 0){if(typeof e==`object`&&e){let t=e.asArray;if(typeof t==`function`)return Array.from(t.call(e));if(`value`in e&&typeof e.value!=`object`)return[e.value]}return Array.isArray(e)?e.slice():[e]}}function bl(e,t){if(e===void 0)return[`undefined`];if(e===null)return[`null`];switch(typeof e){case`boolean`:return[`boolean`,e];case`number`:return[`number`,Number.isNaN(e)?`NaN`:e===1/0?`Infinity`:e===-1/0?`-Infinity`:Object.is(e,-0)?`-0`
4:e];case`string`:return[`string`,e];case`object`:{if(Object.getOwnPropertySymbols(e).length>0)return;if(Array.isArray(e)){if(Object.getOwnPropertyNames(e).some(t=>t!==`length`&&(!/^(0|[1-9]\d*)$/.test(t)||Number(t)>=e.length||!(`value`in Object.getOwnPropertyDescriptor(e,t)))))return}else{let t=Object.getPrototypeOf(e);if(t!==Object.prototype&&t!==null||Object.getOwnPropertyNames(e).some(t=>!Object.prototype.propertyIsEnumerable.call(e,t)||!(`value`in Object.getOwnPropertyDescriptor(e,t))))return}if(t.has(e))return;t.add(e);let n;if(Array.isArray(e)){let r=e.map(e=>bl(e,t));n=r.some(e=>e===void 0)?void 0:[`array`,r]}else{let r=[],i=!1;for(let n of Object.keys(e).sort()){let a=bl(e[n],t);if(a===void 0){i=!0;break}r.push([n,a])}n=i?void 0:[`object`,r]}return t.delete(e),n}default:return}}function xl(e){try{let t=bl(Array.isArray(e)?e:yl(e),new Set);return t===void 0?{unrepresentable:!0}:{runtimeValueFingerprint:JSON.stringify(t)}}catch{return{unrepresentable:!0}}}function Sl(e){if(Array.isArray(e))return e.map(e=>Sl(e));if(typeof e==`object`&&e){let t={};for(let[n,r]of Object.entries(e))Object.defineProperty(t,n,{configurable:!0,enumerable:!0,value:Sl(r),writable:!0});return t}return e}function Cl(e){return Sl(e)}function wl(e,t){return typeof e==`number`&&Number.isInteger(e)&&e>=0&&e<t}function Tl(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function q(e,t,n){e.push({path:t,message:n,severity:`error`})}function El(e,t,n){e.push({path:t,message:n,severity:`warning`})}function Dl(e){return e===``||/^(?:\/(?:[^~]|~[01])*)*$/.test(e)}function Ol(e,t,n,r,i,a){if(e&&Object.prototype.hasOwnProperty.call(e,t)||t===a&&e&&Object.prototype.hasOwnProperty.call(e,a))return!0;if(!Object.keys(e??{}).some(e=>e.startsWith(`[`)&&e.endsWith(`]`)))return!1;if(n.operation===`event/receive`){let e=r.configuration?.event?.value?.[0];return typeof e==`number`&&Object.prototype.hasOwnProperty.call(i.events?.[e]?.values??{},t)}return!0}function kl(e,t,n,r){return wl(e,t.types?.length??0)?!0:(q(n,r,`Type index ${String(e)} is out of range.`),!1)}function Al(e,t,n,r){if(!kl(e.type,t,n,`${r}/type`)||e.value===void 0)return;if(!Array.isArray(e.value)){q(n,`${r}/value`,`Value must be an array when present.`);return}let i=t.types[e.type],a=vl[i.signature];a&&i.signature!==`custom`&&e.value.length!==a.length&&q(n,`${r}/value`,`Expected ${a.length} value component(s) for type "${i.signature}", received ${e.value.length}.`);for(let t=0;t<e.value.length;t++){let a=e.value[t],o=!0;switch(i.signature){case`bool`:o=typeof a==`boolean`;break;case`int`:o=typeof a==`number`&&Number.isInteger(a)&&a>=-2147483648&&a<=2147483647;break;case`float`:case`float2`:case`float3`:case`float4`:case`float2x2`:case`float3x3`:case`float4x4`:o=typeof a==`number`&&Number.isFinite(a);break;case`ref`:o=typeof a==`string`&&Dl(a)}o||q(n,`${r}/value/${t}`,`Value component is invalid for type "${i.signature}".`)}}function jl(e,t,n){let r=!e.extension||!n||n.has(e.extension)?sl(e,!1):void 0;return r?e.extension&&r.declarationSchema&&!Ml(e,t,r.declarationSchema)?{mapping:void 0,support:`unsupported-extension`}:{mapping:r,support:e.extension?`extension`:`core`}:{mapping:void 0,support:e.extension?`unsupported-extension`:`unknown-core`}}function Ml(e,t,n){let r=(e,n)=>{let r=Object.keys(e??{}).sort(),i=Object.keys(n).sort();return r.length!==i.length||r.some((e,t)=>e!==i[t])?!1:r.every(r=>Tl(e[r])&&t.types?.[e[r].type]?.signature===n[r])};return r(e.inputValueSockets,n.inputValueSockets)&&r(e.outputValueSockets,n.outputValueSockets)}function Nl(e,t){if(!Array.isArray(e))return!1;let n=e=>typeof e==`number`&&Number.isInteger(e)&&e>=-2147483648&&e<=2147483647;switch(t){case`bool`:return e.length===1&&typeof e[0]==`boolean`;case`int`:return e.length===1&&n(e[0]);case`int[]`:return e.every(n);case`string`:return e.length===1&&typeof e[0]==`string`;default:return e.length>0}}function Pl(e,t,n){switch(t){case`types`:return e.types?.length??0;case`variables`:return e.variables?.length??0;case`events`:return e.events?.length??0;case`nodes`:return e.nodes?.length??0;case`assetNodes`:return n??0;default:return 0}}function Fl(e,t,n,r){if(!e||!Nl(e.value,t.configurationType)||!e.value||t.minItems!==void 0&&e.value.length<t.minItems||t.minimum!==void 0&&e.value.some(e=>typeof e!=`number`||e<t.minimum)||t.maximum!==void 0&&e.value.some(e=>typeof e!=`number`||e>t.maximum))return!1;if(t.indexSource){let i=Pl(n,t.indexSource,r);if(e.value.some(e=>!wl(e,i)))return!1}if(t.allowedSignatures){let r=e.value[0],i=typeof r==`number`?n.types?.[r]?.signature:void 0;if(!i||!t.allowedSignatures.includes(i))return!1}return!(t.allowedValues&&e.value.some(e=>!t.allowedValues.includes(e))||t.debugLogTemplate&&!hl(e.value[0]).valid)}function Il(e,t,n){let r=Cl(e);for(let e=0;e<(r.nodes?.length??0);
4e++){let i=r.nodes[e],a=t[i.declaration];if(!a||a.support===`unknown-core`||a.support===`unsupported-extension`)continue;let o=sl(a.source,!1);if(!o?.configuration)continue;let s=new Map;for(let[e,t]of Object.entries(o.configuration))if(t.configurationGroup){let a=Fl(i.configuration?.[e],t,r,n);s.set(t.configurationGroup,(s.get(t.configurationGroup)??!0)&&a)}for(let[e,t]of Object.entries(o.configuration)){let a=(!t.configurationGroup||s.get(t.configurationGroup)===!0)&&Fl(i.configuration?.[e],t,r,n);!a&&t.defaultValue!==void 0?(i.configuration??={},i.configuration[e]={value:Array.isArray(t.defaultValue)?Sl(t.defaultValue):[t.defaultValue]}):a&&t.uniqueValues&&i.configuration?.[e]?.value&&(i.configuration[e].value=Array.from(new Set(i.configuration[e].value)))}}return r}function Ll(e){let t=[];for(let n of e.split(`/`)){let e=n.startsWith(`[`)&&!n.startsWith(`[[`)?`int`:n.startsWith(`{`)&&!n.startsWith(`{{`)?`ref`:void 0;if(e){let r=n.substring(1,n.length-1).replace(/~1/g,`/`).replace(/~0/g,`~`);t.push({name:r,signature:e})}}return t}function Rl(e,t,n,r=new Set){return`node`in e?zl(e.node,e.socket??`value`,t,n,r):e.type}function zl(e,t,n,r,i=new Set){let a=`${e}:${t}`;if(i.has(a)||(i.add(a),!wl(e,n.nodes?.length??0)))return;let o=n.nodes[e];if(!wl(o.declaration,r.length))return;let s=r[o.declaration],c=s.source.outputValueSockets?.[t]?.type;if(c!==void 0)return c;let l=e=>{let t=n.types?.findIndex(t=>t.signature===e)??-1;return t>=0?t:void 0},u=()=>l(`bool`);if(t===`isValid`)return u();if(s.operation===`pointer/get`&&t===`value`){let e=o.configuration?.type?.value?.[0];return typeof e==`number`?e:void 0}if(s.operation===`variable/get`&&t===`value`){let e=o.configuration?.variable?.value?.[0];return typeof e==`number`?n.variables?.[e]?.type:void 0}if(s.operation===`math/switch`&&t===`value`){let e=o.values?.default;return e?Rl(e,n,r,i):void 0}if(s.operation===`event/receive`&&t!==`event`){let e=o.configuration?.event?.value?.[0];return typeof e==`number`?n.events?.[e]?.values?.[t]?.type:void 0}let d=Bl(s.operation,t);if(d)return l(String(d));let f=sl(s.source,!1)?.outputs?.values?.[t],p=f?.gltfType,m=p===`number`?`float`:p===`boolean`?`bool`:p;if(m&&m in vl)return l(m);let h=f?.typeSourceInput?o.values?.[f.typeSourceInput]:void 0;return h?Rl(h,n,r,i):void 0}function Bl(e,t){if(t!==`value`)return e===`math/rgbToOkLCh`&&[`l`,`c`,`h`].includes(t)||e===`math/rgbFromOkLCh`&&[`r`,`g`,`b`].includes(t)||e.startsWith(`math/extract`)?`float`:e===`math/matDecompose`?t===`rotation`?`float4`:t===`translation`||t===`scale`?`float3`:void 0:e===`math/quatToAxisAngle`?t===`axis`?`float3`:t===`angle`?`float`:void 0:e===`flow/doN`&&t===`currentCount`||e===`flow/for`&&t===`index`?`int`:e===`flow/setDelay`&&t===`lastDelay`?`ref`:e===`flow/throttle`&&t===`lastRemainingTime`?`float`:(e===`event/onStart`||e===`event/onTick`||e===`event/receive`)&&t===`event`?`ref`:e===`event/onTick`&&t===`timeSinceLastTick`||e===`event/onTick`&&t===`timeSinceStart`?`float`:void 0;if([`math/E`,`math/Pi`,`math/Tau`,`math/Inf`,`math/NaN`,`math/random`,`math/length`,`math/dot`,`math/determinant`,`math/quatAngleBetween`].includes(e))return`float`;if([`math/eq`,`ref/eq`,`math/lt`,`math/le`,`math/gt`,`math/ge`,`math/isNaN`,`math/isInf`,`type/intToBool`,`type/floatToBool`].includes(e))return`bool`;if([`math/clz`,`math/ctz`,`math/popcnt`,`type/boolToInt`,`type/floatToInt`].includes(e))return`int`;if([`type/boolToFloat`,`type/intToFloat`].includes(e))return`float`}function Vl(e,t,n,r,i,a,o){let s=`${a}/nodes/${t}`;if(!wl(e.declaration,r.length)){q(i,`${s}/declaration`,`Declaration index ${String(e.declaration)} is out of range.`);return}let c=r[e.declaration],l=c.support===`unsupported-extension`?cl(c.source):sl(c.source,!1);if(c.support===`unknown-core`||!l)return;let u=(e,t,n)=>{e.invalidUsesDefault||e.defaultValue!==void 0?El(i,t,`${n} The default configuration will be used.`):q(i,t,n)};for(let[t,n]of Object.entries(e.configuration??{})){if(!Tl(n)){q(i,`${s}/configuration/${t}`,`Configuration "${t}" must be an object.`);continue}n.value!==void 0&&!Array.isArray(n.value)?q(i,`${s}/configuration/${t}/value`,`Configuration value must be an array when present.`):n.value&&n.value.length===0&&q(i,`${s}/configuration/${t}/value`,`Configuration value arrays must contain at least one item when present.`)}for(let[t,a]of Object.entries(l.configuration??{})){let c=e.configuration?.[t],l=!!c&&Nl(c.value,a.configurationType);if(!c&&a.required?q(i,`${s}/configuration/${t}`,`Required configuration "${t}" is missing.`):c&&!l&&u(a,`${s}/configuration/${t}`,`Configuration "${t}
4" is invalid.`),l&&c.value&&a.minItems!==void 0&&c.value.length<a.minItems&&q(i,`${s}/configuration/${t}/value`,`Configuration "${t}" requires at least ${a.minItems} value(s).`),l&&c.value&&a.indexSource){let e=Pl(n,a.indexSource,o);for(let n=0;n<c.value.length;n++)wl(c.value[n],e)||u(a,`${s}/configuration/${t}/value/${n}`,`Index is out of range for graph ${a.indexSource}.`)}if(l&&c.value&&a.allowedSignatures){let e=c.value[0],r=typeof e==`number`?n.types?.[e]?.signature:void 0;(!r||!a.allowedSignatures.includes(r))&&u(a,`${s}/configuration/${t}/value/0`,`Type "${String(r)}" is not supported by this operation.`)}if(l&&c.value&&a.allowedValues&&c.value.some(e=>!a.allowedValues.includes(e))&&u(a,`${s}/configuration/${t}/value`,`Configuration "${t}" contains an unsupported value.`),l&&c.value&&a.debugLogTemplate&&!hl(c.value[0]).valid&&u(a,`${s}/configuration/${t}/value/0`,`Configuration "${t}" is not a valid debug message template.`),l&&c.value&&(a.minimum!==void 0||a.maximum!==void 0)){let e=c.value[0];(a.minimum!==void 0&&e<a.minimum||a.maximum!==void 0&&e>a.maximum)&&u(a,`${s}/configuration/${t}/value/0`,`Configuration "${t}" must be between ${String(a.minimum)} and ${String(a.maximum)}.`)}if(l&&c.value&&a.generatesInputValueSockets)for(let t of c.value){if(typeof t!=`number`||!wl(t,n.variables?.length??0))continue;let a=e.values?.[String(t)];a?Rl(a,n,r)!==n.variables[t].type&&q(i,`${s}/values/${t}/type`,`Configured input value socket "${t}" has the wrong type.`):q(i,`${s}/values/${t}`,`Required configured input value socket "${t}" is missing.`)}if(l&&c.value&&a.generatesCaseInputValueSockets){let t=e.values?.default?Rl(e.values.default,n,r):void 0;for(let a of c.value){let o=e.values?.[String(a)];o?t!==void 0&&Rl(o,n,r)!==t&&q(i,`${s}/values/${a}/type`,`Case input value socket "${a}" must match the default socket type.`):q(i,`${s}/values/${a}`,`Required case input value socket "${a}" is missing.`)}}if(l&&c.value&&a.pointerTemplate&&typeof c.value[0]==`string`)for(let t of Ll(c.value[0])){let a=e.values?.[t.name],o=n.types?.findIndex(e=>e.signature===t.signature)??-1;a?(o<0||Rl(a,n,r)!==o)&&q(i,`${s}/values/${t.name}/type`,`Pointer template input "${t.name}" must have type "${t.signature}".`):q(i,`${s}/values/${t.name}`,`Required pointer template input "${t.name}" is missing.`)}}if(c.operation===`debug/log`){let t=l.configuration?.severity,r=l.configuration?.message,a=!!t&&Fl(e.configuration?.severity,t,n,o),c=!!r&&Fl(e.configuration?.message,r,n,o),u=a&&c?e.configuration.message.value[0]:``;for(let t of hl(u).sockets)e.values?.[t]||q(i,`${s}/values/${t}`,`Required debug message template input "${t}" is missing.`)}for(let[t,a]of Object.entries(l.inputs?.values??{})){if(!t.startsWith(`[`)&&!e.values?.[t]&&q(i,`${s}/values/${t}`,`Required input value socket "${t}" is missing.`),c.operation===`event/send`){let t=e.configuration?.event?.value?.[0],a=typeof t==`number`?n.events?.[t]:void 0;for(let[t,o]of Object.entries(a?.values??{})){let a=e.values?.[t];a?Rl(a,n,r)!==o.type&&q(i,`${s}/values/${t}/type`,`Custom event input value socket "${t}" has the wrong type.`):q(i,`${s}/values/${t}`,`Required custom event input value socket "${t}" is missing.`)}}let o=a.gltfType===`number`?`float`:a.gltfType===`boolean`?`bool`:a.gltfType,l=e.values?.[t];if(l&&o&&o in vl){let e=Rl(l,n,r);e!==void 0&&n.types?.[e]?.signature!==o&&q(i,`${s}/values/${t}/type`,`Input value socket "${t}" must have type "${o}".`)}}if(l.validation)try{let t=Sl(e);for(let e of Object.values(t.values??{}))e.type===void 0&&(e.type=Rl(e,n,r));let a=l.validation(t,n);a.valid||q(i,s,a.error??`Operation "${c.operation}" is invalid.`)}catch(e){q(i,s,e.message)}for(let[a,o]of Object.entries(e.values??{})){if(!Tl(o)){q(i,`${s}/values/${a}`,`Input value socket "${a}" must be an object.`);continue}if(c.support===`unsupported-extension`&&!c.source.inputValueSockets?.[a]&&q(i,`${s}/values/${a}`,`Input value socket "${a}" is not defined by operation "${c.operation}".`),`node`in o){if(`value`in o&&q(i,`${s}/values/${a}`,`An input value socket cannot define both inline and node sources.`),!wl(o.node,n.nodes?.length??0)){q(i,`${s}/values/${a}/node`,`Node index ${String(o.node)} is out of range.`);continue}o.node>=t&&q(i,`${s}/values/${a}/node`,`Value connections must reference an earlier node.`),o.type!==void 0&&kl(o.type,n,i,`${s}/values/${a}/type`);let e=n.nodes[o.node];if(wl(e.declaration,r.length)){let t=r[e.declaration],c=t.support===`unsupported-extension`?cl(t.source):sl(t.source,!1),l=o.socket??`value`,u=Ol(c?.outputs?.values,l,t,e,n,`value`);c&&!u&&q(i,`${s}/values/${a}/socket`,`Output value socket "${l}" does not exist on node ${o.node}.`);let d=t.source.outputValueSockets?.[l]?.type??zl(o.node,l,n,r);if(o.type!==void 0){let e=c?.outputs?.values,r=(e&&Object.prototype.hasOwnProperty.call(e,l)?e[l]:void 0)?.gltfType,u=r===`
4number`?`float`:r===`boolean`?`bool`:r===`vector2`?`float2`:r===`vector3`?`float3`:r===`vector4`?`float4`:r,f=Bl(t.operation,l)??(u&&Object.prototype.hasOwnProperty.call(vl,u)?u:void 0),p=n.types?.[o.type]?.signature;(f!==void 0&&p!==f||f===void 0&&d!==void 0&&o.type!==d)&&q(i,`${s}/values/${a}/type`,`Type assertion does not match output socket "${l}".`)}}}else Al(o,n,i,`${s}/values/${a}`)}for(let[r,a]of Object.entries(e.flows??{})){if(!Tl(a)){q(i,`${s}/flows/${r}`,`Output flow socket "${r}" must be an object.`);continue}if(!wl(a.node,n.nodes?.length??0)){q(i,`${s}/flows/${r}/node`,`Node index ${String(a.node)} is out of range.`);continue}a.node<=t&&q(i,`${s}/flows/${r}/node`,`Flow connections must reference a later node.`)}}function Hl(e,t=0,n,r){let i=[],a=`/extensions/KHR_interactivity/graphs/${t}`;typeof e!=`object`||!e||Array.isArray(e)?(q(i,a,`Behavior graph must be an object.`),e={}):e=Cl(e);let o={types:()=>({signature:`custom`}),variables:()=>({type:-1}),events:()=>({}),declarations:()=>({op:``}),nodes:()=>({declaration:-1})};for(let t of[`types`,`variables`,`events`,`declarations`,`nodes`]){let n=e[t];n!==void 0&&!Array.isArray(n)?(q(i,`${a}/${t}`,`"${t}" must be an array when present.`),e[t]=[]):Array.isArray(n)&&n.length===0?q(i,`${a}/${t}`,`"${t}" must contain at least one item when present.`):Array.isArray(n)&&(e[t]=n.map((e,n)=>typeof e!=`object`||!e||Array.isArray(e)?(q(i,`${a}/${t}/${n}`,`Each "${t}" item must be an object.`),o[t]()):e))}for(let t=0;t<(e.events?.length??0);t++){let n=e.events[t];n.values!==void 0&&!Tl(n.values)?(q(i,`${a}/events/${t}/values`,`"values" must be an object when present.`),n.values=void 0):n.values&&Object.keys(n.values).length===0&&q(i,`${a}/events/${t}/values`,`"values" must contain at least one property when present.`)}for(let t=0;t<(e.declarations?.length??0);t++){let n=e.declarations[t];for(let e of[`inputValueSockets`,`outputValueSockets`])n[e]!==void 0&&!Tl(n[e])?(q(i,`${a}/declarations/${t}/${e}`,`"${e}" must be an object when present.`),n[e]=void 0):n[e]&&Object.keys(n[e]).length===0&&q(i,`${a}/declarations/${t}/${e}`,`"${e}" must contain at least one property when present.`)}for(let t=0;t<(e.nodes?.length??0);t++){let n=e.nodes[t];for(let e of[`configuration`,`values`,`flows`])n[e]!==void 0&&!Tl(n[e])?(q(i,`${a}/nodes/${t}/${e}`,`"${e}" must be an object when present.`),n[e]=void 0):n[e]&&Object.keys(n[e]).length===0&&q(i,`${a}/nodes/${t}/${e}`,`"${e}" must contain at least one property when present.`)}let s=new Set,c=(e.declarations??[]).map((t,r)=>{let o=Object.keys(t.inputValueSockets??{}).sort().map(e=>{let n=t.inputValueSockets[e];return`${JSON.stringify(e)}:${Tl(n)?String(n.type):`invalid`}`}).join(`,`),c=`${JSON.stringify(t.op)}:${JSON.stringify(t.extension??``)}:${o}`;s.has(c)&&q(i,`${a}/declarations/${r}`,`Duplicate equivalent declaration.`),s.add(c);let{support:l}=jl(t,e,n);l===`unknown-core`&&q(i,`${a}/declarations/${r}/op`,`Unknown core operation "${t.op}".`),!t.extension&&(t.inputValueSockets||t.outputValueSockets)&&q(i,`${a}/declarations/${r}`,`Core operation declarations cannot define dynamic value sockets.`);for(let[n,o]of Object.entries(t.inputValueSockets??{})){if(!Tl(o)){q(i,`${a}/declarations/${r}/inputValueSockets/${n}`,`Input value socket "${n}" must be an object.`);continue}kl(o.type,e,i,`${a}/declarations/${r}/inputValueSockets/${n}/type`)}for(let[n,o]of Object.entries(t.outputValueSockets??{})){if(!Tl(o)){q(i,`${a}/declarations/${r}/outputValueSockets/${n}`,`Output value socket "${n}" must be an object.`);continue}kl(o.type,e,i,`${a}/declarations/${r}/outputValueSockets/${n}/type`)}return{index:r,operation:t.extension?`${t.op}:${t.extension}`:t.op,support:l,source:t}}),l=new Set;for(let t=0;t<(e.types?.length??0);t++){let n=e.types[t].signature;n!==`custom`&&l.has(n)&&q(i,`${a}/types/${t}/signature`,`Duplicate built-in type signature "${n}".`),l.add(n),n!==`custom`&&!vl[n]&&q(i,`${a}/types/${t}/signature`,`Unknown built-in type signature "${n}".`)}for(let t=0;t<(e.variables?.length??0);t++)Al(e.variables[t],e,i,`${a}/variables/${t}`);for(let t=0;t<(e.events?.length??0);t++){let n=e.events[t].id;n!==void 0&&e.events.slice(0,t).some(e=>e.id===n)&&q(i,`${a}/events/${t}/id`,`Duplicate event id "${n}".`),e.events[t].values&&Object.prototype.hasOwnProperty.call(e.events[t].values,`event`)&&q(i,`${a}/events/${t}/values/event`,`Custom event value socket id "event" is reserved.`);for(let[n,r]of Object.entries(e.events[t].values??{})){if(!Tl(r)){q(i,`${a}/events/${t}/values/${n}`,`Event value socket "${n}" must be an object.`);continue}Al(r,e,i,`${a}/events/${t}/values/${n}`)}}for(let t=0;
4t<(e.nodes?.length??0);t++)Vl(e.nodes[t],t,e,c,i,a,r);return{index:t,path:a,name:e.name??`Graph ${t+1}`,source:e,effectiveSource:Il(e,c,r),declarations:c,diagnostics:i,valid:!i.some(e=>e.severity===`error`)}}function Ul(e,t,n){let r=Sl(e),i=[];Array.isArray(r.graphs)||(q(i,`/extensions/KHR_interactivity/graphs`,`"graphs" must be an array.`),r.graphs=[]),r.graphs.length===0&&q(i,`/extensions/KHR_interactivity/graphs`,`At least one behavior graph is required.`);let a=r.graph??0,o=wl(a,r.graphs.length)?a:-1;o===-1&&q(i,`/extensions/KHR_interactivity/graph`,`Default graph index ${String(a)} is out of range.`);let s=r.graphs.map((e,r)=>Hl(e,r,t,n));return r.graphs=s.map(e=>e.source),{specificationCommit:_l,source:r,defaultGraphIndex:o,graphs:s,diagnostics:i}}var Wl=`/extensions/KHR_interactivity/events/`,Gl=`/extensions/KHR_interactivity/delays/`;function Kl(e){return Wl+e}function ql(e){return Jl(e)?e.substring(37):void 0}function Jl(e){return typeof e==`string`&&e.startsWith(`/extensions/KHR_interactivity/events/`)}yt(),b();function Yl(e,t){return e&&Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function Xl(e){if(Array.isArray(e))return e.map(e=>Xl(e));if(typeof e==`object`&&e){let t={};for(let[n,r]of Object.entries(e))Object.defineProperty(t,n,{configurable:!0,enumerable:!0,value:Xl(r),writable:!0});return t}return e}function Zl(e){return e===null||[`string`,`number`,`boolean`].includes(typeof e)||Array.isArray(e)&&e.every(Zl)||typeof e==`object`&&Object.values(e).every(Zl)}function Ql(e){for(let t of e.getAllBlocks()){let e=t.metadata?.khrInteractivity;if(e){Object.prototype.hasOwnProperty.call(e.generatedConfiguration??{},`eventData`)&&(e.generatedConfigurationRuntime||={},Object.prototype.hasOwnProperty.call(e.generatedConfigurationRuntime,`eventData`)||Object.defineProperty(e.generatedConfigurationRuntime,"eventData",{configurable:!0,enumerable:!0,value:xl(ol(t.config?.eventData)),writable:!0}));for(let n of t.dataInputs){if(n.isConnected())continue;let t=n.metadata?.khrInteractivity;if(t){t.runtimeValueSnapshot??=xl(n._defaultValue);continue}e.generatedInputDefaults&&Object.prototype.hasOwnProperty.call(e.generatedInputDefaults,n.name)||(e.generatedInputDefaults||={},Object.defineProperty(e.generatedInputDefaults,n.name,{configurable:!0,enumerable:!0,value:xl(n._defaultValue),writable:!0}))}}}}var $l=class{constructor(e,t,n=60,r=0,i,a,o){this._gltf=t,this._animationTargetFps=n,this._graphIndex=r,this._supportedExtensions=i,this._declarationModels=a,this._types=[],this._mappings=[],this._staticVariables=[],this._events=[],this._internalEventsCounter=0,this._nodes=[],this._insertedBlocks=[],this._canonicalGraph=Cl(o??e),this._interactivityGraph=this._declarationModels?Il(e,this._declarationModels,this._gltf.nodes?.length??0):Cl(e),this._parseTypes(),this._parseDeclarations(),this._parseVariables(),this._parseEvents(),this._parseNodes()}get _strictValidation(){return!!this._declarationModels}_getAllowedDynamicValueSockets(e,t,n){if((e===`debug/log`||e===`flow/log:BABYLON`)&&n===`input`){let n=t.configuration?.[e===`debug/log`?`message`:`messageTemplate`]?.value?.[0];return new Set(typeof n==`string`?hl(n).sockets:[])}if(e===`event/send`&&n===`input`||e===`event/receive`&&n===`output`){let e=t.configuration?.event?.value?.[0];if(typeof e==`number`)return new Set(Object.keys(this._interactivityGraph.events?.[e]?.values??{}))}if(e===`variable/set`&&n===`input`)return new Set((t.configuration?.variables?.value??[]).map(String));if(e===`math/switch`&&n===`input`)return new Set((t.configuration?.cases?.value??[]).map(String));if((e===`pointer/get`||e===`pointer/set`||e===`pointer/interpolate`)&&n===`input`){let e=t.configuration?.pointer?.value?.[0];if(typeof e==`string`)return new Set(e.split(`/`).filter(e=>e.startsWith(`[`)&&!e.startsWith(`[[`)||e.startsWith(`{`)&&!e.startsWith(`{{`)).map(e=>e.substring(1,e.length-1).replace(/~1/g,`/`).replace(/~0/g,`~`)))}}_getAllowedDynamicFlowSockets(e,t,n){for(let[r,i]of Object.entries(t.configuration??{})){if(!(n===`input`?i.generatesInputFlowSockets:i.generatesOutputFlowSockets))continue;let t=e.configuration?.[r]?.value,a=t&&t.length>0&&(i.configurationType!==`int`||t.length===1)&&t.every(e=>typeof e==`number`&&Number.isInteger(e)&&e>=(i.minimum??-2147483648)&&e<=(i.maximum??2147483647))?t:i.defaultValue;if(n===`input`){let e=Array.isArray(a)&&typeof a[0]==`number`?a[0]:0;return new Set(Array.from({length:e},(e,t)=>String(t)))}return new Set(Array.isArray(a)?a.map(String):[])}}get arrays(){return{types:this._types,mappings:this._mappings,staticVariables:this._staticVariables,events:this._events,nodes:this._nodes}}_parseTypes(){if(this._interactivityGraph.types)for(let e of this._interactivityGraph.types)this._types.push(vl[e.signature])}_parseDeclarations(){if(this._interactivityGraph.declarations)for(let e=0;e<this._interactivityGraph.declarations.length;e++){let t=this._interactivityGraph.declarations[e],n=this._declarationModels?.[e],r=!t.extension||!this._supportedExtensions||this._supportedExtensions.has(t.extension),i=n?.support===`unsupported-extension`?void 0:r?sl(t,!1):void 0;if(!i&&!t.extension)throw Error(`Unknown core KHR_interactivity operation "${t.op}".`);
4let a=i??(t.extension?cl(t):void 0);if(!a)throw A.Error([`No mapping found for declaration`,t]),Error(`Error parsing declarations`);this._mappings.push({flowGraphMapping:a,fullOperationName:t.extension?t.op+`:`+t.extension:t.op,declaration:n??{index:e,operation:t.extension?`${t.op}:${t.extension}`:t.op,support:i?t.extension?`extension`:`core`:`unsupported-extension`,source:t}})}}_parseVariables(){if(this._interactivityGraph.variables)for(let e of this._interactivityGraph.variables){let t=this._parseVariable(e);this._staticVariables.push(t)}}_parseVariable(e,t){let n=this._types[e.type];if(!n)throw A.Error([`No type found for variable`,e]),Error(`Error parsing variables`);if(e.value&&this._interactivityGraph.types?.[e.type]?.signature!==`custom`&&e.value.length!==n.length)throw A.Error([`Invalid value length for variable`,e,n]),Error(`Error parsing variables`);let r=e.value?e.value.slice():[];if(!r.length)switch(n.flowGraphType){case`boolean`:r.push(!1);break;case`FlowGraphInteger`:r.push(0);break;case`number`:r.push(NaN);break;case`string`:r.push(``);break;case`Vector2`:r.push(NaN,NaN);break;case`Vector3`:r.push(NaN,NaN,NaN);break;case`Vector4`:case`Matrix2D`:case`Quaternion`:r.push(NaN,NaN,NaN,NaN);break;case`Matrix`:for(let e=0;e<16;e++)r.push(NaN);break;case`Matrix3D`:for(let e=0;e<9;e++)r.push(NaN)}return n.elementType===`number`&&typeof r[0]==`string`?r[0]=parseFloat(r[0]):n.flowGraphType===`string`&&typeof r[0]==`string`&&(r[0]=this._normalizeStaticReference(r[0])),{type:n.flowGraphType,value:t?t(r,this):r}}_normalizeStaticReference(e){if(!e||e.startsWith(`/extensions/KHR_interactivity/events/`)||e.startsWith(`/extensions/KHR_interactivity/delays/`)||!e.startsWith(`/`))return``;let t=this._gltf;for(let n of e.substring(1).split(`/`)){let e=n.replace(/~1/g,`/`).replace(/~0/g,`~`);if(Array.isArray(t)){if(!/^(0|[1-9]\d*)$/.test(e))return``;t=t[parseInt(e,10)]}else if(typeof t==`object`&&t&&Object.prototype.hasOwnProperty.call(t,e))t=t[e];else return``}return typeof t==`object`&&t?e:``}_parseEvents(){if(!this._interactivityGraph.events)return;let e=new Set(this._interactivityGraph.events.flatMap(e=>e.id===void 0?[]:[e.id])),t=`__babylon_khr_internal_${this._graphIndex}_`;for(let n of this._interactivityGraph.events){let r;if(n.id===void 0){do r=t+this._internalEventsCounter++;while(e.has(r));e.add(r)}let i={eventId:n.id??r};n.values&&(i.eventData=Object.keys(n.values).map(e=>{let t=n.values?.[e];if(!t)throw A.Error([`No value found for event key`,e]),Error(`Error parsing events`);let r=this._types[t.type];if(!r)throw A.Error([`No type found for event value`,t]),Error(`Error parsing events`);let i=t.value===void 0?void 0:this._parseVariable(t);return{id:e,type:r.flowGraphType,eventData:!0,value:i}})),this._events.push(i)}}_parseNodes(){if(this._interactivityGraph.nodes)for(let e=0;e<this._interactivityGraph.nodes.length;e++){let t=this._interactivityGraph.nodes[e];if(typeof t.declaration!=`number`)throw A.Error([`No declaration found for node`,t]),Error(`Error parsing nodes`);let n=this._mappings[t.declaration];if(!n)throw A.Error([`No mapping found for node`,t]),Error(`Error parsing nodes`);if(n.flowGraphMapping.validation){let e=n.flowGraphMapping.validation(t,this._interactivityGraph,this._gltf);if(!e.valid)throw Error(`Error validating interactivity node ${this._interactivityGraph.declarations?.[t.declaration].op} - ${e.error}`)}let r=[];n.declaration.support===`unsupported-extension`&&r.push(this._createUnsupportedExtensionBlock(t,e,n));for(let i=0;i<n.flowGraphMapping.blocks.length;i++){let a=n.flowGraphMapping.blocks[i],o=this._getEmptyBlock(a,n.fullOperationName,e,t.declaration,i);this._parseNodeConfiguration(t,o,n.flowGraphMapping,a),r.push(o)}this._nodes.push({blocks:r,fullOperationName:n.fullOperationName})}}_createBlockProvenance(e,t,n,r){return{graphIndex:this._graphIndex,nodeIndex:e,declarationIndex:t,operation:n,role:r,sourcePath:`/extensions/KHR_interactivity/graphs/${this._graphIndex}/nodes/${e}`}}_getEmptyBlock(e,t,n,r,i){return{uniqueId:Ye(),className:e,dataInputs:[],dataOutputs:[],signalInputs:[],signalOutputs:[],config:{},type:t,metadata:n===void 0?{}:{khrInteractivity:this._createBlockProvenance(n,r,t,i??0)}}}_setSocketProvenance(e,t,n,r,i,a,o,s){e.metadata={...e.metadata??{},khrInteractivity:{...this._createBlockProvenance(t,n,r,i),kind:a,direction:o,socket:s}}}_getBlockRole(e,t){return t.metadata?.khrInteractivity?.role??e.indexOf(t)}_createUnsupportedExtensionBlock(e,t,n){let r=this._getEmptyBlock(`KHR_interactivity/FlowGraphUnsupportedInteractivityBlock`,n.fullOperationName,t,e.declaration,0),i=new Set;for(let e of this._interactivityGraph.nodes??[])for(let n of Object.values(e.flows??{}))n.node===t&&i.add(n.socket??`in`);let a=e=>Object.entries(e??{}).map(([e,t])=>({name:e,type:this._types[t.type]?.flowGraphType,signature:this._interactivityGraph.types?.[t.type]?.signature}));r.config={operation:n.fullOperationName,inputValueSockets:a(n.declaration.source.inputValueSockets),outputValueSockets:a(n.declaration.source.outputValueSockets),inputFlowSockets:Array.from(i).sort(),outputFlowSockets:Object.keys(e.flows??{}).sort()};for(let i of r.config.inputValueSockets){let a=this._createNewSocketConnection(i.name);this._setSocketProvenance(a,t,e.declaration,n.fullOperationName,0,`value`,`input`,i.name),r.dataInputs.push(a)}for(let i of r.config.outputValueSockets){let a=this._createNewSocketConnection(i.name,!0);this._setSocketProvenance(a,t,e.declaration,n.fullOperationName,0,`value`,`output`,i.name),r.dataOutputs.push(a)}for(let i of r.config.inputFlowSockets){let a=this._createNewSocketConnection(i);this._setSocketProvenance(a,t,e.declaration,n.fullOperationName,0,`flow`,`input`,i),r.signalInputs.push(a)}for(let i of r.config.outputFlowSockets){let a=this._createNewSocketConnection(i,!0);this._setSocketProvenance(a,t,e.declaration,n.fullOperationName,0,`flow`,`output`,i),r.signalOutputs.push(a)}return r}_parseNodeConfiguration(e,t,n,r){let i=e.configuration;if(i)for(let e in i){let a=i[e];if(!a)throw Error(`Error parsing node configuration`);let o=n.configuration?.[e];if((o||!this._strictValidation)&&!o?.validationOnly&&(o&&o.toBlock?o.toBlock===r:n.blocks.indexOf(r)===0)){let n=o?.defaultValue;a?.value&&(n=a.value),o?.isArray||(n.length!==1&&A.Warn(`Invalid non-array value length: ${n.length}`),n=n[0]),o?.dataTransformer&&(n=o.dataTransformer(n,this)),n!==void 0&&(t.config[o?.name||e]={value:n})}}}_parseNodeConnections(e){for(let t=0;t<this._nodes.length;t++){let n=this._interactivityGraph.nodes?.[t];if(!n)throw A.Error([`No node found for interactivity node`,this._nodes[t]]),Error(`Error parsing node connections`);let r=this._nodes[t],i=this._mappings[n.declaration];if(!i)throw A.Error([`No mapping found for node`,n]),Error(`Error parsing node connections`);if(r.blocks.length===0){A.Warn(`Skipping connections for no-op node #${t} (unsupported operation: ${r.fullOperationName})`);continue}let a=n.flows||{},o=Object.keys(a).sort();for(let e of o){let o=a[e],s=Yl(i.flowGraphMapping.outputs?.flows,e);this._strictValidation&&s?.compatibilityOnly&&(s=void 0);let c=!1;if(!s){for(let e in i.flowGraphMapping.outputs?.flows)if(e.startsWith(`[`)&&e.endsWith(`]`)){let t=i.flowGraphMapping.outputs?.flows?.[e];if(!this._strictValidation||!t?.compatibilityOnly){c=!0,s=t;break}}}let l=c?this._getAllowedDynamicFlowSockets(n,i.flowGraphMapping,`output`):void 0;if(this._strictValidation&&l&&!l.has(e)&&(s=void 0),!s&&!this._isUnsupportedExtensionBlock(r.blocks[0]))continue;let u=s?c?s.name.replace(`$1`,e):s.name:e,d=o.node,f=this._nodes[d];if(!f)throw A.Error([`No node found for input node id`,d]),Error(`Error parsing node connections`);if(f.blocks.length===0){A.Warn(`Dropping flow connection from node #${t} "${e}" to no-op node #${d} (unsupported operation: ${f.fullOperationName})`);continue}let p=s&&s.toBlock&&r.blocks.find(e=>e.className===s.toBlock)||r.blocks[0],m=p.signalOutputs.find(e=>e.name===u)??this._createNewSocketConnection(u,!0);p.signalOutputs.includes(m)||p.signalOutputs.push(m),this._setSocketProvenance(m,t,n.declaration,r.fullOperationName,this._getBlockRole(r.blocks,p),`flow`,`output`,e);let h=this._mappings[this._interactivityGraph.nodes[d].declaration]?.flowGraphMapping;if(!h)throw A.Error([`No mapping found for input node`,f]),Error(`Error parsing node connections`);let g=Yl(h.inputs?.flows,o.socket||`in`);this._strictValidation&&g?.compatibilityOnly&&(g=void 0);let _=!1;if(!g){for(let e in h.inputs?.flows)if(e.startsWith(`[`)&&e.endsWith(`]`)){let t=h.inputs?.flows?.[e];
4(!this._strictValidation||!t?.compatibilityOnly)&&(_=!0,g=t)}let e=_?this._getAllowedDynamicFlowSockets(this._interactivityGraph.nodes[d],h,`input`):void 0;if(this._strictValidation&&e&&!e.has(o.socket??`in`)&&(g=void 0),!g&&(o.socket??`in`)===`in`&&al(f.fullOperationName)&&(g={name:`in`}),!g&&!this._isUnsupportedExtensionBlock(f.blocks[0]))continue}let v=g?_?g.name.replace(`$1`,o.socket||``):g.name:o.socket||`in`,y=g&&g.toBlock&&f.blocks.find(e=>e.className===g.toBlock)||f.blocks[0],b=y.signalInputs.find(e=>e.name===v);b||(b=this._createNewSocketConnection(v),y.signalInputs.push(b)),this._setSocketProvenance(b,d,this._interactivityGraph.nodes[d].declaration,f.fullOperationName,this._getBlockRole(f.blocks,y),`flow`,`input`,o.socket??`in`),b.connectedPointIds.push(m.uniqueId),m.connectedPointIds.push(b.uniqueId)}let s=n.values||{},c=Object.keys(s);for(let a of c){let o=s[a],c=Yl(i.flowGraphMapping.inputs?.values,a);this._strictValidation&&c?.compatibilityOnly&&(c=void 0);let l=!1;if(!c){for(let e in i.flowGraphMapping.inputs?.values)if(e.startsWith(`[`)&&e.endsWith(`]`)){let t=i.flowGraphMapping.inputs?.values?.[e];(!this._strictValidation||!t?.compatibilityOnly)&&(l=!0,c=t)}}let u=l?this._getAllowedDynamicValueSockets(i.fullOperationName,n,`input`):void 0;if(!c||u&&!u.has(a))continue;let d=c?l?c.name.replace(`$1`,a):c.name:a,f=c&&c.toBlock&&r.blocks.find(e=>e.className===c.toBlock)||r.blocks[0],p=f.dataInputs.find(e=>e.name===d)??this._createNewSocketConnection(d);f.dataInputs.includes(p)||f.dataInputs.push(p),this._setSocketProvenance(p,t,n.declaration,r.fullOperationName,this._getBlockRole(r.blocks,f),`value`,`input`,a);let m=p.metadata.khrInteractivity;m.sourceValue=Xl(this._canonicalGraph.nodes?.[t]?.values?.[a]??o);let h=!!c?.convertConnectedTimeToFrames;if(o.value!==void 0){let t=this._parseVariable(o,c&&c.dataTransformer);e._connectionValues[p.uniqueId]=t,p.defaultValue=t,m.runtimeValue=Xl(t.value)}else if(o.node!==void 0){let i=o.node,s=o.socket||`value`,c=this._nodes[i];if(!c)throw A.Error([`No node found for output socket reference`,o]),Error(`Error parsing node connections`);if(c.blocks.length===0){A.Warn(`Dropping value connection from no-op node #${i} (unsupported operation: ${c.fullOperationName}) into node #${t} "${a}"; consumer will use type-default value`);continue}let l=this._mappings[this._interactivityGraph.nodes[i].declaration]?.flowGraphMapping;if(!l)throw A.Error([`No mapping found for output socket reference`,o]),Error(`Error parsing node connections`);let u=Yl(l.outputs?.values,s);this._strictValidation&&u?.compatibilityOnly&&(u=void 0);let d=!1;if(!u){for(let e in l.outputs?.values)if(e.startsWith(`[`)&&e.endsWith(`]`)){let t=l.outputs?.values?.[e];(!this._strictValidation||!t?.compatibilityOnly)&&(d=!0,u=t)}let e=d?this._getAllowedDynamicValueSockets(c.fullOperationName,this._interactivityGraph.nodes[i],`output`):void 0;if(!u||e&&!e.has(s))continue}let f=u?d?u.name.replace(`$1`,s):u?.name:s,m=u&&u.toBlock&&c.blocks.find(e=>e.className===u.toBlock)||c.blocks[0],g=m.dataOutputs.find(e=>e.name===f);g||(g=this._createNewSocketConnection(f,!0),m.dataOutputs.push(g)),this._setSocketProvenance(g,i,this._interactivityGraph.nodes[i].declaration,c.fullOperationName,this._getBlockRole(c.blocks,m),`value`,`output`,s),h?this._connectWithSecondsToFramesConversion(e,g,p,t,n.declaration,r.fullOperationName):(p.connectedPointIds.push(g.uniqueId),g.connectedPointIds.push(p.uniqueId))}else throw A.Error([`Invalid value for value connection`,o]),Error(`Error parsing node connections`)}if(i.flowGraphMapping.interBlockConnectors)for(let e of i.flowGraphMapping.interBlockConnectors){let t=e.input,n=e.output,i=e.isVariable;this._connectFlowGraphNodes(t,n,r.blocks[e.inputBlockIndex],r.blocks[e.outputBlockIndex],i)}if(i.flowGraphMapping.extraProcessor){let t=this._interactivityGraph.declarations?.[n.declaration];if(!t)throw A.Error([`No declaration found for extra processor`,n]),Error(`Error parsing node connections`);r.blocks=i.flowGraphMapping.extraProcessor(n,t,i.flowGraphMapping,this,r.blocks,e,this._gltf)}this._ensureMappedSocketProvenance(t,n,r.blocks,i)}}_ensureMappedSocketProvenance(e,t,n,r){let i=(i,a,o)=>{for(let[s,c]of Object.entries(i??{})){if(s.startsWith(`[`)&&s.endsWith(`]`)||this._strictValidation&&c.compatibilityOnly)continue;let i=c.toBlock&&n.find(e=>e.className===c.toBlock)||n[0];if(!i)continue;let l=a===`value`?o===`input`?i.dataInputs:i.dataOutputs:o===`input`?i.signalInputs:i.signalOutputs,u=l.find(e=>e.name===c.name);u||(u=this._createNewSocketConnection(c.name,o===`output`),l.push(u)),this._setSocketProvenance(u,e,t.declaration,r.fullOperationName,this._getBlockRole(n,i),a,o,s)}};if(i(r.flowGraphMapping.outputs?.values,`value`,`output`),i(r.flowGraphMapping.inputs?.flows,`flow`,`input`),i(r.flowGraphMapping.outputs?.flows,`flow`,`output`),al(r.fullOperationName)){let i=n[0];if(i){let a=i.signalInputs.find(e=>e.name===`in`);a||(a=this._createNewSocketConnection(`in`),i.signalInputs.push(a)),this._setSocketProvenance(a,e,t.declaration,r.fullOperationName,this._getBlockRole(n,i),`flow`,`input`,`in`)}}for(let[t,i]of Object.entries(r.flowGraphMapping.configuration??{})){let r=i.toBlock&&n.find(e=>e.className===i.toBlock)||n[0],a=r?.metadata?.khrInteractivity;if(!r||!a)continue;let o=r.config?.[i.name],s=typeof o==`object`&&o&&Object.prototype.hasOwnProperty.call(o,`value`)?o.value:o;a.configuration||={};let c={sourceValue:Xl(this._canonicalGraph.nodes?.[e]?.configuration?.[t]?.value),runtimeValue:Xl(s)};Object.defineProperty(a.configuration,t,{configurable:!0,enumerable:!0,value:c,writable:!0})}for(let e of n){let t=e.metadata?.khrInteractivity;if(!t)continue;let n=new Set(Object.values(r.flowGraphMapping.configuration??{}).filter(n=>n.toBlock?e.className===n.toBlock:t.role===0).map(e=>e.name)),i=new Set([`glTF`]);for(let[r,a]of Object.entries(e.config??{})){if(n.has(r)||i.has(r))continue;let e=r===`eventData`?ol(a):typeof a==`object`&&a&&Object.prototype.hasOwnProperty.call(a,`value`)?a.value:a;Zl(e)&&(t.generatedConfiguration||={},Object.defineProperty(t.generatedConfiguration,r,{configurable:!0,enumerable:!0,value:Xl(e),writable:!0}))}}}_createNewSocketConnection(e,t){return{uniqueId:Ye(),name:e,_connectionType:+!!t,connectedPointIds:[]}}_isUnsupportedExtensionBlock(e){return e?.className===`KHR_interactivity/FlowGraphUnsupportedInteractivityBlock`}_connectWithSecondsToFramesConversion(e,t,n,r,i,a){let o=this._getEmptyBlock(`FlowGraphMultiplyBlock`,a,r,i,-1);o.config={type:`number`};let s=this._createNewSocketConnection(`a`),c=this._createNewSocketConnection(`b`),l=this._createNewSocketConnection(`value`,!0);o.dataInputs.push(s,c),o.dataOutputs.push(l);let u={type:`number`,value:[this._animationTargetFps]};e._connectionValues[c.uniqueId]=u,c.defaultValue=u,s.connectedPointIds.push(t.uniqueId),t.connectedPointIds.push(s.uniqueId),n.connectedPointIds.push(l.uniqueId),l.connectedPointIds.push(n.uniqueId),this._insertedBlocks.push(o)}_connectFlowGraphNodes(e,t,n,r,i){let a=i?n.dataInputs:n.signalInputs,o=i?r.dataOutputs:r.signalOutputs,s=a.find(t=>t.name===e)||this._createNewSocketConnection(e),c=o.find(e=>e.name===t)||this._createNewSocketConnection(t,!0);a.find(t=>t.name===e)||a.push(s),o.find(e=>e.name===t)||o.push(c),s.connectedPointIds.push(c.uniqueId),c.connectedPointIds.push(s.uniqueId)}getVariableName(e){return`staticVariable_`+e}serializeToFlowGraph(){let e={uniqueId:Ye(),_userVariables:{},_connectionValues:{}};this._parseNodeConnections(e);for(let t=0;t<this._staticVariables.length;t++){let n=this._staticVariables[t];e._userVariables[this.getVariableName(t)]=n}let t=this._nodes.reduce((e,t)=>
4e.concat(t.blocks),[]).concat(this._insertedBlocks);return{name:this._interactivityGraph.name??`Graph ${this._graphIndex+1}`,metadata:{khrInteractivity:{graphIndex:this._graphIndex,specificationCommit:_l,source:Cl(this._canonicalGraph)}},rightHanded:!0,allBlocks:t,executionContexts:[e]}}},eu=class{constructor(e,t){this._prefixes=e,this._fallback=t}addPrefix(e){this._prefixes.unshift(e)}convert(e){for(let{prefix:t,converter:n}of this._prefixes)if(e.startsWith(t))return n.convert(e);return this._fallback.convert(e)}};rr();var tu=`/extensions/BABYLON_scene_objects/`,nu=class{constructor(e,t){this._scene=e,this._tree=t}convert(e){if(!e.startsWith(`/extensions/BABYLON_scene_objects/`))throw Error(`BabylonScenePathToObjectConverter: path "${e}" does not start with the expected prefix "${tu}".`);let t=e.slice(34).split(`/`).filter(e=>e.length>0);if(t.length===0)throw Error(`BabylonScenePathToObjectConverter: path "${e}" is missing a collection name.`);let n=t[0],r=this._tree[n];if(!r)throw Error(`BabylonScenePathToObjectConverter: unknown collection "${n}" in path "${e}".`);if(t.length===2&&t[1]===`length`)return{object:this._getCollectionArray(n),info:r.length};if(t.length<2)throw Error(`BabylonScenePathToObjectConverter: path "${e}" is missing an instance id.`);if(!/^\d+$/.test(t[1]))throw Error(`BabylonScenePathToObjectConverter: invalid uniqueId "${t[1]}" in path "${e}".`);let i=parseInt(t[1],10);if(!Number.isFinite(i)||i<0)throw Error(`BabylonScenePathToObjectConverter: invalid uniqueId "${t[1]}" in path "${e}".`);let a=this._lookupInstanceByUniqueId(n,i);if(!a)throw Error(`BabylonScenePathToObjectConverter: no ${n} instance found with uniqueId ${i} (path "${e}").`);if(t.length===2)return{object:a,info:this._buildIdentityAccessor(a)};if(t.length>3)throw Error(`BabylonScenePathToObjectConverter: nested property paths are not yet supported (path "${e}").`);let o=t[2],s=r.__array__[o];if(!s||typeof s==`boolean`)throw Error(`BabylonScenePathToObjectConverter: property "${o}" is not registered on ${n} (path "${e}").`);return{object:a,info:s}}_getCollectionArray(e){switch(e){case`transformNodes`:return this._scene.transformNodes;case`meshes`:return this._scene.meshes;case`materials`:return this._scene.materials;default:return[]}}_lookupInstanceByUniqueId(e,t){switch(e){case`transformNodes`:return this._scene.transformNodes.find(e=>e.uniqueId===t)||this._scene.meshes.find(e=>e.uniqueId===t);case`meshes`:return this._scene.meshes.find(e=>e.uniqueId===t);case`materials`:return this._scene.materials.find(e=>e.uniqueId===t);default:return}}_buildIdentityAccessor(e){return{type:`object`,get:()=>e,getTarget:()=>e,isReadOnly:!0}}};function ru(){return{transformNodes:{length:{type:`number`,get:e=>e.length,getTarget:e=>e},__array__:{__target__:!0,name:{type:`string`,get:e=>e.name,set:(e,t)=>{t.name=e},getTarget:e=>e},translation:{type:`Vector3`,get:e=>e.position,set:(e,t)=>t.position.copyFrom(e),getTarget:e=>e},rotation:{type:`Quaternion`,get:e=>e.rotationQuaternion??z.RotationYawPitchRoll(e.rotation.y,e.rotation.x,e.rotation.z),set:(e,t)=>{t.rotationQuaternion?t.rotationQuaternion.copyFrom(e):t.rotationQuaternion=e.clone()},getTarget:e=>e},scale:{type:`Vector3`,get:e=>e.scaling,set:(e,t)=>t.scaling.copyFrom(e),getTarget:e=>e},matrix:{type:`Matrix`,get:e=>e.computeWorldMatrix(!1),getTarget:e=>e,isReadOnly:!0},globalMatrix:{type:`Matrix`,get:e=>e.computeWorldMatrix(!0),getTarget:e=>e,isReadOnly:!0}}},meshes:{length:{type:`number`,get:e=>e.length,getTarget:e=>e},__array__:{__target__:!0,name:{type:`string`,get:e=>e.name,set:(e,t)=>{t.name=e},getTarget:e=>e},visible:{type:`boolean`,get:e=>e.isVisible,set:(e,t)=>{t.isVisible=e},getTarget:e=>e}}},materials:{length:{type:`number`,get:e=>e.length,getTarget:e=>e},__array__:{__target__:!0,name:{type:`string`,get:e=>e.name,set:(e,t)=>{t.name=e},getTarget:e=>e}}}}}yn(),Ie();var iu={isKhrInteractivityRef:!0},au=class{convert(e){let t=e===Wl,n=e.endsWith(`/`)?e.slice(0,-1):e;if(t||n.startsWith(`/extensions/KHR_interactivity/events/`)){let r=n.substring(Wl.length);return{object:iu,info:{type:`object`,isReadOnly:!0,get:()=>t?e:r.length>0?n:void 0,getTarget:()=>iu}}}let r=n.substring(Gl.length),i=/^\d+$/.test(r)?parseInt(r,10):NaN;return{object:iu,info:{type:`object`,isReadOnly:!0,get:(e,t,n)=>{let r=n;if(!(!r||isNaN(i)||i<0))return Ae(r,i)?new Jn(i):void 0},getTarget:()=>iu}}}},ou=`/extensions/KHR_interactivity/asset/`,su=`/extensions/KHR_interactivity/limits/`,cu={major:2,minor:0},lu=2147483647,uu={maxActiveAnimations:lu,maxActiveDelays:lu,maxActivePropertyInterpolations:lu,maxActiveVariableInterpolations:lu},du={isKhrInteractivityAssetCapability:!0};function fu(e){let[t,n]=(e??``).split(`.`),r=parseInt(t,10),i=parseInt(n,10);return isNaN(r)?cu:r===cu.major?{major:r,minor:Math.min(isNaN(i)?0:i,cu.minor)}:r<cu.major?{major:r,minor:isNaN(i)?0:i}:cu}var pu=class{constructor(e,t){this._gltf=e,this._isExtensionEnabled=t}convert(e){let t=e.endsWith(`/`)?e.slice(0,-1):e;if(t.startsWith(`/extensions/KHR_interactivity/limits/`)){let n=uu[t.substring(37)];if(n===void 0)throw Error(`Path ${e}
4 is invalid`);return this._createAccessor(`number`,()=>n)}let n=t.substring(36);if(n===`majorVersion`||n===`minorVersion`)return this._createAccessor(`number`,()=>fu(this._gltf.asset?.version)[n===`majorVersion`?`major`:`minor`]);let r=n.split(`/`);if(r.length===3&&r[0]===`extensions`&&r[2]===`enabled`){let e=r[1];return this._createAccessor(`boolean`,()=>this._isExtensionEnabled(e))}throw Error(`Path ${e} is invalid`)}_createAccessor(e,t){return{object:du,info:{type:e,isReadOnly:!0,get:t,getTarget:()=>du}}}},mu=class{encodeEventReference(e){return Kl(e)}decodeEventReference(e){return ql(e)}decodeIndexReference(e,t){if(e.length===0||e[0]!==`/`)return;let n=t?`/${t}/`:`/`;if(!e.startsWith(n))return;let r=t?e.substring(n.length):e.substring(e.lastIndexOf(`/`)+1);if(/^(0|[1-9]\d*)$/.test(r))return parseInt(r,10)}getObjectReference(e,t){let n=e._internalMetadata?.gltf?.pointers;if(!Array.isArray(n))return;let r=n.filter(e=>typeof e==`string`);if(r.length!==0){if(t){let e=r.find(e=>e.split(`/`)[1]===t);if(e)return e}return r[0]}}},hu=e({KHR_interactivity:()=>vu,RegisterKHR_interactivity:()=>Cu,_AddInteractivityObjectModel:()=>yu,_RegisterKHRInteractivityRuntime:()=>xu});zn(),Se(),yt(),ae();var gu=`KHR_interactivity`,_u=new WeakMap,vu=class{constructor(e){this._loader=e,this.name=gu,this.order=200,this.enabled=this._loader.isExtensionUsed(gu),e._skipStartAnimationStep=!0}_initializePathConverter(e){this._gltfPathConverter=Wi(this._loader.gltf,t=>yu(e,this._loader.parent.targetFps,t));let t=[{prefix:tu,converter:new nu(e,ru())}],n=new au;t.push({prefix:Wl,converter:n}),t.push({prefix:Gl,converter:n});let r=new Set((this._loader.gltf.extensionsUsed??[]).filter(e=>d.has(e)&&this._loader.parent.extensionOptions[e]?.enabled!==!1)),i=new pu(this._loader.gltf,e=>r.has(e));t.push({prefix:ou,converter:i}),t.push({prefix:su,converter:i});let a=new eu(t,this._gltfPathConverter);return this._pathConverter=a,a}dispose(){this._loader=null,delete this._gltfPathConverter,delete this._pathConverter}async onReady(){if(!this._loader.babylonScene)return;let e=this._loader.babylonScene,t=this._initializePathConverter(e),n=this._loader.gltf.extensions?.KHR_interactivity;if(!n)return;let r=new Set((this._loader.gltf.extensionsUsed??[]).filter(e=>this._loader.parent.extensionOptions[e]?.enabled!==!1)),i=Ul(n,r,this._loader.gltf.nodes?.length??0),a=this._loader.parent.extensionOptions[gu],o=a?.autoStart??!0,s=a?.parseOnly??!1,c=a?.strictValidation??!0,l=_u.get(e)??[],u={assetIndex:l.length,document:i,graphs:[],pathConverter:t,glTF:this._loader.gltf,scene:e,hostResolver:new mu};l.push(u),_u.set(e,l),await Promise.all(i.graphs.map(async n=>{let a={graph:n,diagnostics:n.diagnostics.slice()};if(u.graphs[n.index]=a,!n.valid&&c){A.Error(`KHR_interactivity: rejecting behavior graph #${n.index}: ${n.diagnostics.map(e=>e.message).join(`; `)}`);return}try{let l=new $l(c?n.effectiveSource:n.source,this._loader.gltf,this._loader.parent.targetFps,n.index,r,c?n.declarations:void 0,n.source).serializeToFlowGraph();if(a.serializedFlowGraph=l,s)return;let d=new tt({scene:e,hostResolver:u.hostResolver});d.dispatchEventsSynchronously=!1,a.coordinator=d,a.flowGraph=await He(l,{coordinator:d,pathConverter:t}),Ql(a.flowGraph),o&&n.index===i.defaultGraphIndex&&d.start()}catch(e){let t=e?.message??String(e);a.diagnostics.push({path:n.path,message:t,severity:`error`}),A.Error(`KHR_interactivity: rejecting behavior graph #${n.index}: ${t}`),a.coordinator?.dispose(),delete a.coordinator,delete a.flowGraph,delete a.serializedFlowGraph}}))}};function yu(e,t,n){Ki(`/extensions/KHR_interactivity/?/activeCamera/rotation`,{get:()=>{if(!e.activeCamera)return new z(NaN,NaN,NaN,NaN);let t=z.FromRotationMatrix(e.activeCamera.getWorldMatrix()).normalize();return e.useRightHandedSystem||(t.w*=-1,t.x*=-1),t},type:`Quaternion`,getTarget:()=>e.activeCamera},n),Ki(`/extensions/KHR_interactivity/?/activeCamera/position`,{get:()=>{if(!e.activeCamera)return new R(NaN,NaN,NaN);let t=e.activeCamera.getWorldMatrix().getTranslation();return e.useRightHandedSystem||(t.x*=-1),t},type:`Vector3`,getTarget:()=>e.activeCamera},n);let r=t=>{let n=e.activeCamera;return!n||n.mode===k.ORTHOGRAPHIC_CAMERA?NaN:t(n)},i=t=>{let n=e.activeCamera;return!n||n.mode!==k.ORTHOGRAPHIC_CAMERA?NaN:t(n)};Ki(`/extensions/KHR_interactivity/?/activeCamera/perspective/aspectRatio`,{get:()=>r(e=>e.getEngine().getAspectRatio(e)),type:`number`,getTarget:()=>e.activeCamera},n),Ki(`/extensions/KHR_interactivity/?/activeCamera/perspective/yfov`,{get:()=>r(e=>{if(e.fovMode===k.FOVMODE_VERTICAL_FIXED)return e.fov;let t=e.getEngine().getAspectRatio(e);return t?2*Math.atan(Math.tan(e.fov/2)/t):e.fov}),type:`number`,getTarget:()=>e.activeCamera},n),Ki(`/extensions/KHR_interactivity/?/activeCamera/perspective/znear`,{get:()=>r(e=>e.minZ),type:`number`,getTarget:()=>e.activeCamera},n),Ki(`/extensions/KHR_interactivity/?/activeCamera/perspective/zfar`,{get:()=>r(e=>e.maxZ===0?1/0:e.maxZ),type:`number`,getTarget:()=>e.activeCamera},n),Ki(`/extensions/KHR_interactivity/?/activeCamera/orthographic/xmag`,{get:()=>i(e=>{let t=e.getEngine().getRenderWidth()/2;return((e.orthoRight??t)-(e.orthoLeft??-t))/2}),type:`number`,getTarget:()=>e.activeCamera},n),Ki(`/extensions/KHR_interactivity/?/activeCamera/orthographic/ymag`,{get:()=>i(e=>{let t=e.getEngine().getRenderHeight()/2;return((e.orthoTop??t)-(e.orthoBottom??-t))/2}),type:`number`,getTarget:()=>e.activeCamera},n),Ki(`/extensions/KHR_interactivity/?/activeCamera/orthographic/znear`,{get:()=>i(e=>e.minZ),type:`number`,getTarget:()=>e.activeCamera},n),Ki(`/extensions/KHR_interactivity/?/activeCamera/orthographic/zfar`,{get:()=>i(e=>e.maxZ),type:`number`,getTarget:()=>e.activeCamera},n);let a=e=>e._babylonAnimationGroup?.targetedAnimations?.[0]?.animation.framePerSecond??t;Ki(`/animations/{}/extensions/KHR_interactivity/isPlaying`,{get:e=>e._babylonAnimationGroup?.isPlaying??!1,type:`boolean`,getTarget:e=>e._babylonAnimationGroup},n),Ki(`/animations/{}/extensions/KHR_interactivity/minTime`,{get:e=>(e._babylonAnimationGroup?.from??0)/a(e),type:`number`,getTarget:e=>e._babylonAnimationGroup},n),Ki(`/animations/{}/extensions/KHR_interactivity/maxTime`,{get:e=>(e._babylonAnimationGroup?.to??0)/a(e),type:`number`,getTarget:e=>e._babylonAnimationGroup},n),Ki(`/animations/{}/extensions/KHR_interactivity/playhead`,{get:e=>(e._babylonAnimationGroup?.getRetainedCurrentFrame()??0)/a(e),type:`number`,getTarget:e=>e._babylonAnimationGroup},n),Ki(`/animations/{}/extensions/KHR_interactivity/virtualPlayhead`,{get:e=>(e._babylonAnimationGroup?.getVirtualCurrentFrame()??0)/a(e),type:`number`,getTarget:e=>e._babylonAnimationGroup},n)}var bu=!1;function xu(){bu||(bu=!0,ye(gu,`FlowGraphGLTFDataProvider`,async()=>(await ce(async()=>{let{FlowGraphGLTFDataProvider:e}=await Promise.resolve().then(()=>ud);return{FlowGraphGLTFDataProvider:e}}
4,void 0)).FlowGraphGLTFDataProvider),ye(gu,`FlowGraphUnsupportedInteractivityBlock`,async()=>(await ce(async()=>{let{FlowGraphUnsupportedInteractivityBlock:e}=await Promise.resolve().then(()=>_d);return{FlowGraphUnsupportedInteractivityBlock:e}},void 0)).FlowGraphUnsupportedInteractivityBlock),ye(gu,`FlowGraphObjectReferenceBlock`,async()=>(await ce(async()=>{let{FlowGraphObjectReferenceBlock:e}=await Promise.resolve().then(()=>fd);return{FlowGraphObjectReferenceBlock:e}},void 0)).FlowGraphObjectReferenceBlock),ye(gu,`FlowGraphEventReferenceBlock`,async()=>(await ce(async()=>{let{FlowGraphEventReferenceBlock:e}=await Promise.resolve().then(()=>hd);return{FlowGraphEventReferenceBlock:e}},void 0)).FlowGraphEventReferenceBlock))}var Su=!1;function Cu(){Su||(Su=!0,xu(),m(gu),r(gu,!0,e=>new vu(e)))}Cu();var wu=e({KHR_node_visibility:()=>Eu,RegisterKHR_node_visibility:()=>Au,_RegisterKHRNodeVisibilityRuntime:()=>Ou}),Tu=`KHR_node_visibility`,Eu=class{constructor(e){this.name=Tu,this._loader=e,this.enabled=e.isExtensionUsed(Tu)}onReady(){if(!this._loader)return;let e=this._loader.gltf.nodes;if(e)for(let t of e){let e=t._babylonTransformNode;e&&(e.inheritVisibility=!0,t.extensions&&t.extensions.KHR_node_visibility&&t.extensions.KHR_node_visibility.visible===!1&&(e.isVisible=!1,t._primitiveBabylonMeshes?.forEach(e=>{e.inheritVisibility=!0,e.isVisible=!1})))}}dispose(){delete this._loader}},Du=!1;function Ou(){Du||(Du=!0,Ki(`/nodes/{}/extensions/KHR_node_visibility/visible`,{get:e=>{let t=e._babylonTransformNode;return t&&t.isVisible!==void 0?t.isVisible:!0},set:(e,t)=>{t._primitiveBabylonMeshes?.forEach(e=>{e.inheritVisibility=!0}),t._babylonTransformNode&&(t._babylonTransformNode.isVisible=e),t._primitiveBabylonMeshes?.forEach(t=>{t.isVisible=e})},getTarget:e=>e._babylonTransformNode,getPropertyName:[()=>`isVisible`],type:`boolean`}))}var ku=!1;function Au(){ku||(ku=!0,Ou(),m(Tu),r(Tu,!0,e=>new Eu(e)))}Au();var ju=new WeakMap,Mu=new WeakMap,Nu=new WeakMap;function Pu(e){return e===`selectable`?Nu:Mu}function Fu(e,t){return Pu(t).get(e)??!0}function Iu(e,t){let n=e;for(;n;){if(!Fu(n,t))return!1;n=n.parent}return!0}function Lu(e,t,n){t===`selectable`?e.isPickable=n:e._isPointerMovePickable=n}function Ru(e,t){let n=Iu(e,t),r=e._primitiveBabylonMeshes??[];for(let e of r)Lu(e,t,n);let i=e._babylonTransformNode;i&&`isPickable`in i&&Lu(i,t,n)}function zu(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parent}return!1}function Bu(e,t,n){let r=Pu(t);for(let t of e)ju.set(t,e),r.set(t,n(t)??!0);for(let n of e)Ru(n,t)}function Vu(e,t){return Fu(e,t)}function Hu(e,t,n){Pu(t).set(e,n);let r=ju.get(e)??[e];for(let n of r)zu(n,e)&&Ru(n,t)}var Uu=e({KHR_node_selectability:()=>Gu,RegisterKHR_node_selectability:()=>Yu,_RegisterKHRNodeSelectabilityRuntime:()=>qu}),Wu=`KHR_node_selectability`,Gu=class{constructor(e){this.name=Wu,this.order=100,this._loader=e,this.enabled=e.isExtensionUsed(Wu)}async onReady(){Bu(this._loader.gltf.nodes??[],`selectable`,e=>e.extensions?.KHR_node_selectability?.selectable)}dispose(){this._loader=null}},Ku=!1;function qu(){Ku||(Ku=!0,ll(`event/onSelect`,Wu,{blocks:[`FlowGraphMeshPickEventBlock`,`FlowGraphGetVariableBlock`,`FlowGraphIndexOfBlock`,`KHR_interactivity/FlowGraphGLTFDataProvider`,`KHR_interactivity/FlowGraphEventReferenceBlock`],declarationSchema:{inputValueSockets:{},outputValueSockets:{selectedNode:`ref`,selectionRayOrigin:`float3`,selectionPoint:`float3`,controllerIndex:`int`,event:`ref`}},configuration:{nodeIndex:{name:`variable`,configurationType:`int`,toBlock:`FlowGraphGetVariableBlock`,indexSource:`assetNodes`,invalidUsesDefault:!0,dataTransformer(e){return`pickedMesh_`+e}}},outputs:{values:{selectedNodeIndex:{name:`index`,toBlock:`FlowGraphIndexOfBlock`},selectedNode:{name:`nodeReference`,toBlock:`KHR_interactivity/FlowGraphEventReferenceBlock`},controllerIndex:{name:`controllerIndex`,toBlock:`KHR_interactivity/FlowGraphEventReferenceBlock`},selectionPoint:{name:`selectionPoint`,toBlock:`KHR_interactivity/FlowGraphEventReferenceBlock`},selectionRayOrigin:{name:`selectionRayOrigin`,toBlock:`KHR_interactivity/FlowGraphEventReferenceBlock`},event:{name:`value`,toBlock:`KHR_interactivity/FlowGraphEventReferenceBlock`}},flows:{out:{name:`out`,toBlock:`KHR_interactivity/FlowGraphEventReferenceBlock`}}},interBlockConnectors:[{input:`asset`,output:`value`,inputBlockIndex:0,outputBlockIndex:1,isVariable:!0},{input:`array`,output:`nodes`,inputBlockIndex:2,outputBlockIndex:3,isVariable:!0},{input:`object`,output:`pickedMesh`,inputBlockIndex:2,outputBlockIndex:0,isVariable:!0},{input:`node`,output:`pickedMesh`,inputBlockIndex:4,outputBlockIndex:0,isVariable:!0},{input:`controllerIndexInput`,output:`pointerId`,inputBlockIndex:4,outputBlockIndex:0,isVariable:!0},{input:`selectionPointInput`,output:`pickedPoint`,inputBlockIndex:4,outputBlockIndex:0,isVariable:!0},{input:`selectionRayOriginInput`,output:`pickOrigin`,inputBlockIndex:4,outputBlockIndex:0,isVariable:!0},{input:`in`,output:`done`,inputBlockIndex:4,outputBlockIndex:0}],extraProcessor(e,t,n,r,i,a,o){let s=e.configuration?.nodeIndex?.value?.[0],c=typeof s==`
4number`&&Number.isInteger(s)&&s>=0&&s<(o?.nodes?.length??0),l=c?`pickedMesh_`+s:`pickedMesh_unbound`;i[1].config.variable=l,a._userVariables[l]=c?{className:`Mesh`,id:o?.nodes?.[s]._babylonTransformNode?.id,uniqueId:o?.nodes?.[s]._babylonTransformNode?.uniqueId}:{type:`any`,value:[{}]};let u=`${Wu}:event/onSelect:${s}`;return i[0].config.eventKey=u,i[0].config.useNaNDefaults=!0,i[0].config.pointerIdDefault=-1,i[4].config.eventKey=u,i}}),Ki(`/nodes/{}/extensions/KHR_node_selectability/selectable`,{get:e=>Vu(e,`selectable`),set:(e,t)=>{Hu(t,`selectable`,e)},getTarget:e=>e._babylonTransformNode,getPropertyName:[()=>`isPickable`],type:`boolean`}))}var Ju=!1;function Yu(){Ju||(Ju=!0,qu(),m(Wu),r(Wu,!0,e=>new Gu(e)))}Yu();var Xu=e({KHR_node_hoverability:()=>ed,RegisterKHR_node_hoverability:()=>id,_RegisterKHRNodeHoverabilityRuntime:()=>nd}),Zu=`KHR_node_hoverability`,Qu=`targetMeshPointerOver_`,$u=`targetMeshPointerOut_`,ed=class{constructor(e){this.name=Zu,this.order=100,this._loader=e,this.enabled=e.isExtensionUsed(Zu)}async onReady(){Bu(this._loader.gltf.nodes??[],`hoverable`,e=>e.extensions?.KHR_node_hoverability?.hoverable)}dispose(){this._loader=null}},td=!1;function nd(){td||(td=!0,ll(`event/onHoverIn`,Zu,{blocks:[`FlowGraphPointerOverEventBlock`,`FlowGraphGetVariableBlock`,`FlowGraphIndexOfBlock`,`KHR_interactivity/FlowGraphGLTFDataProvider`,`KHR_interactivity/FlowGraphEventReferenceBlock`],declarationSchema:{inputValueSockets:{},outputValueSockets:{hoveredNode:`ref`,controllerIndex:`int`,event:`ref`}},configuration:{nodeIndex:{name:`variable`,configurationType:`int`,toBlock:`FlowGraphGetVariableBlock`,indexSource:`assetNodes`,invalidUsesDefault:!0,dataTransformer(e){return Qu+e}}},outputs:{values:{hoverNodeIndex:{name:`index`,toBlock:`FlowGraphIndexOfBlock`},hoveredNode:{name:`nodeReference`,toBlock:`KHR_interactivity/FlowGraphEventReferenceBlock`},controllerIndex:{name:`controllerIndex`,toBlock:`KHR_interactivity/FlowGraphEventReferenceBlock`},event:{name:`value`,toBlock:`KHR_interactivity/FlowGraphEventReferenceBlock`}},flows:{out:{name:`out`,toBlock:`KHR_interactivity/FlowGraphEventReferenceBlock`}}},interBlockConnectors:[{input:`targetMesh`,output:`value`,inputBlockIndex:0,outputBlockIndex:1,isVariable:!0},{input:`array`,output:`nodes`,inputBlockIndex:2,outputBlockIndex:3,isVariable:!0},{input:`object`,output:`meshUnderPointer`,inputBlockIndex:2,outputBlockIndex:0,isVariable:!0},{input:`node`,output:`meshUnderPointer`,inputBlockIndex:4,outputBlockIndex:0,isVariable:!0},{input:`controllerIndexInput`,output:`pointerId`,inputBlockIndex:4,outputBlockIndex:0,isVariable:!0},{input:`in`,output:`done`,inputBlockIndex:4,outputBlockIndex:0}],extraProcessor(e,t,n,r,i,a,o){let s=e.configuration?.nodeIndex?.value?.[0],c=typeof s==`number`&&Number.isInteger(s)&&s>=0&&s<(o?.nodes?.length??0),l=c?Qu+s:`targetMeshPointerOver_unbound`;i[1].config.variable=l,a._userVariables[l]=c?{className:`Mesh`,id:o?.nodes?.[s]._babylonTransformNode?.id,uniqueId:o?.nodes?.[s]._babylonTransformNode?.uniqueId}:{type:`any`,value:[{}]};let u=`${Zu}:event/onHoverIn:${s}`;return i[0].config.eventKey=u,i[4].config.eventKey=u,i}}),ll(`event/onHoverOut`,Zu,{blocks:[`FlowGraphPointerOutEventBlock`,`FlowGraphGetVariableBlock`,`FlowGraphIndexOfBlock`,`KHR_interactivity/FlowGraphGLTFDataProvider`,`KHR_interactivity/FlowGraphEventReferenceBlock`],declarationSchema:{inputValueSockets:{},outputValueSockets:{hoveredNode:`ref`,controllerIndex:`int`,event:`ref`}},configuration:{nodeIndex:{name:`variable`,configurationType:`int`,toBlock:`FlowGraphGetVariableBlock`,indexSource:`assetNodes`,invalidUsesDefault:!0,dataTransformer(e){return $u+e}}},outputs:{values:{hoverNodeIndex:{name:`index`,toBlock:`FlowGraphIndexOfBlock`},hoveredNode:{name:`nodeReference`,toBlock:`KHR_interactivity/FlowGraphEventReferenceBlock`},controllerIndex:{name:`controllerIndex`,toBlock:`KHR_interactivity/FlowGraphEventReferenceBlock`},event:{name:`value`,toBlock:`KHR_interactivity/FlowGraphEventReferenceBlock`}},flows:{out:{name:`out`,toBlock:`KHR_interactivity/FlowGraphEventReferenceBlock`}}},interBlockConnectors:[{input:`targetMesh`,output:`value`,inputBlockIndex:0,outputBlockIndex:1,isVariable:!0},{input:`array`,output:`nodes`,inputBlockIndex:2,outputBlockIndex:3,isVariable:!0},{input:`object`,output:`meshOutOfPointer`,inputBlockIndex:2,outputBlockIndex:0,isVariable:!0},{input:`node`,output:`meshOutOfPointer`,inputBlockIndex:4,outputBlockIndex:0,isVariable:!0},{input:`controllerIndexInput`,output:`pointerId`,inputBlockIndex:4,outputBlockIndex:0,isVariable:!0},{input:`in`,output:`done`,inputBlockIndex:4,outputBlockIndex:0}],extraProcessor(e,t,n,r,i,a,o){let s=e.configuration?.nodeIndex?.value?.[0],c=typeof s==`
4number`&&Number.isInteger(s)&&s>=0&&s<(o?.nodes?.length??0),l=c?$u+s:`targetMeshPointerOut_unbound`;i[1].config.variable=l,a._userVariables[l]=c?{className:`Mesh`,id:o?.nodes?.[s]._babylonTransformNode?.id,uniqueId:o?.nodes?.[s]._babylonTransformNode?.uniqueId}:{type:`any`,value:[{}]};let u=`${Zu}:event/onHoverOut:${s}`;return i[0].config.eventKey=u,i[4].config.eventKey=u,i}}),Ki(`/nodes/{}/extensions/KHR_node_hoverability/hoverable`,{get:e=>Vu(e,`hoverable`),set:(e,t)=>{Hu(t,`hoverable`,e)},getTarget:e=>e._babylonTransformNode,getPropertyName:[()=>`pointerOverDisableMeshTesting`],type:`boolean`}))}var rd=!1;function id(){rd||(rd=!0,nd(),m(Zu),r(Zu,!0,e=>new ed(e)))}id();var ad=e({ExtrasAsMetadata:()=>sd,RegisterExtrasAsMetadata:()=>ld}),od=`ExtrasAsMetadata`,sd=class{_assignExtras(e,t){if(t.extras&&Object.keys(t.extras).length>0){let n=e.metadata=e.metadata||{},r=n.gltf=n.gltf||{};r.extras=t.extras}}constructor(e){this.name=od,this.enabled=!0,this._loader=e}dispose(){this._loader=null}loadNodeAsync(e,t,n){return this._loader.loadNodeAsync(e,t,e=>{this._assignExtras(e,t),n(e)})}loadCameraAsync(e,t,n){return this._loader.loadCameraAsync(e,t,e=>{this._assignExtras(e,t),n(e)})}createMaterial(e,t,n){let r=this._loader.createMaterial(e,t,n);return this._assignExtras(r,t),r}loadAnimationAsync(e,t){return this._loader.loadAnimationAsync(e,t).then(e=>(this._assignExtras(e,t),e))}},cd=!1;function ld(){cd||(cd=!0,m(od),r(od,!1,e=>new sd(e)))}ld();var ud=e({FlowGraphGLTFDataProvider:()=>dd});te();var dd=class extends Xe{constructor(e={}){super(e);let t=e.glTF,n=t?.animations?.map(e=>e._babylonAnimationGroup)||[];this.animationGroups=this.registerDataOutput(`animationGroups`,dt,n);let r=t?.nodes?.map(e=>e._babylonTransformNode)||[];this.nodes=this.registerDataOutput(`nodes`,dt,r)}getClassName(){return`FlowGraphGLTFDataProvider`}},fd=e({FlowGraphObjectReferenceBlock:()=>md,GetInteractivityObjectReference:()=>pd});x();function pd(e,t){let n=t;for(;n;){let t=e.getObjectReference(n,`nodes`);if(t?.startsWith(`/nodes/`))return t;n=n.parent}return``}var md=class extends Xe{constructor(e){super(e),this.object=this.registerDataInput(`object`,dt),this.value=this.registerDataOutput(`value`,st,``)}_updateOutputs(e){this.value.setValue(pd(e,this.object.getValue(e)),e)}getClassName(){return`FlowGraphObjectReferenceBlock`}},hd=e({FlowGraphEventReferenceBlock:()=>gd});Kn(),zn();var gd=class extends _t{constructor(e){super(e),this.config=e,this._assetInverse=L.Identity(),this._selectionPointValue=R.Zero(),this._selectionRayOriginValue=R.Zero();let t=new R(NaN,NaN,NaN);this.node=this.registerDataInput(`node`,dt),this.controllerIndexInput=this.registerDataInput(`controllerIndexInput`,_e,-1),this.selectionPointInput=this.registerDataInput(`selectionPointInput`,pt,t),this.selectionRayOriginInput=this.registerDataInput(`selectionRayOriginInput`,pt,t),this.nodeReference=this.registerDataOutput(`nodeReference`,st,``),this.controllerIndex=this.registerDataOutput(`controllerIndex`,_e,-1),this.selectionPoint=this.registerDataOutput(`selectionPoint`,pt,t),this.selectionRayOrigin=this.registerDataOutput(`selectionRayOrigin`,pt,t),this.value=this.registerDataOutput(`value`,st,``),this.out=this._registerSignalOutput(`out`)}_execute(e){this.nodeReference.setValue(pd(e,this.node.getValue(e)),e);let t=this.controllerIndexInput.getValue(e);if(t<0)this.controllerIndex.setValue(-1,e);else{let n=e._getGlobalContextVariable(`khrInteractivityControllerIndices`,new Map),r=n.get(t);r===void 0&&(r=n.size,n.set(t,r),e._setGlobalContextVariable(`khrInteractivityControllerIndices`,n)),this.controllerIndex.setValue(r,e)}let n=this.node.getValue(e)?.parent;for(;n?.parent;)n=n.parent;n?.getWorldMatrix?(n.getWorldMatrix().invertToRef(this._assetInverse),R.TransformCoordinatesToRef(this.selectionPointInput.getValue(e),this._assetInverse,this._selectionPointValue),R.TransformCoordinatesToRef(this.selectionRayOriginInput.getValue(e),this._assetInverse,this._selectionRayOriginValue),this.selectionPoint.setValue(this._selectionPointValue,e),this.selectionRayOrigin.setValue(this._selectionRayOriginValue,e)):(this.selectionPoint.setValue(this.selectionPointInput.getValue(e),e),this.selectionRayOrigin.setValue(this.selectionRayOriginInput.getValue(e),e)),this.value.setValue(e.getEventReference(this.config.eventKe
4y??`gltf:manual`),e),this.out._activateSignal(e)}getClassName(){return`FlowGraphEventReferenceBlock`}},_d=e({FlowGraphUnsupportedInteractivityBlock:()=>yd});Tt(),Kn(),fn(),zn();function vd(e){switch(e){case`bool`:return!1;case`int`:return new Jn(0);case`float`:return NaN;case`float2`:return new Xn(NaN,NaN);case`float3`:return new R(NaN,NaN,NaN);case`float4`:return new jt(NaN,NaN,NaN,NaN);case`float2x2`:return new Gt([NaN,NaN,NaN,NaN]);case`float3x3`:return new ir([NaN,NaN,NaN,NaN,NaN,NaN,NaN,NaN,NaN]);case`float4x4`:return L.FromArray([NaN,NaN,NaN,NaN,NaN,NaN,NaN,NaN,NaN,NaN,NaN,NaN,NaN,NaN,NaN,NaN]);case`ref`:return``;default:return}}var yd=class extends _t{constructor(e){super(e),this.config=e,this._unregisterSignalInput(`in`),this._unregisterSignalOutput(`error`);for(let t of e.inputValueSockets??[])this.registerDataInput(t.name,xe(t.type));for(let t of e.outputValueSockets??[])this.registerDataOutput(t.name,xe(t.type),vd(t.signature));for(let t of e.inputFlowSockets??[])this._registerSignalInput(t);for(let t of e.outputFlowSockets??[])this._registerSignalOutput(t)}_execute(e,t){}getClassName(){return`FlowGraphUnsupportedInteractivityBlock`}};We(),Dn(),kn(),Un(),rr(),Ze();var bd=`Xposition`,xd=`Yposition`,Sd=`Zposition`,Cd=`Xrotation`,wd=`Yrotation`,Td=`Zrotation`,Ed=`HIERARCHY`,Dd=`MOTION`,Od=class{constructor(e){this.loopMode=M.ANIMATIONLOOPMODE_CYCLE,this.list=[],this.root=kd(),this.numFrames=0,this.frameRate=0,this.skeleton=e}};function kd(){return{name:``,type:``,offset:new R,channels:[],children:[],frames:[],parent:null}}function Ad(){return{frame:0,position:new R,rotation:new z}}function jd(e){let t=e.offset.x,n=e.offset.y,r=e.offset.z;return L.Translation(t,n,r)}function Md(e,t){if(e.frames.length===0)return[];let n=[],r=e.channels.some(e=>e===bd||e===xd||e===Sd),i=e.channels.some(e=>e===Cd||e===wd||e===Td),a=new M(`${e.name}_pos`,`position`,t.frameRate,M.ANIMATIONTYPE_VECTOR3,t.loopMode),o=new M(`${e.name}_rot`,`rotationQuaternion`,t.frameRate,M.ANIMATIONTYPE_QUATERNION,t.loopMode),s=[],c=[];for(let t=0;t<e.frames.length;t++){let n=e.frames[t];r&&n.position&&s.push({frame:n.frame,value:n.position.clone()}),i&&c.push({frame:n.frame,value:n.rotation.clone()})}return s.length>0&&(a.setKeys(s),n.push(a)),c.length>0&&(o.setKeys(c),n.push(o)),n}function Nd(e,t,n){let r=jd(e),i=new mr(e.name,n.skeleton,t,r),a=Md(e,n);for(let e of a)e.getKeys()&&e.getKeys().length>0&&i.animations.push(e);for(let t of e.children)Nd(t,i,n)}function Pd(e,t,n,r){if(n.type===`ENDSITE`)return;let i=Ad();i.frame=t,i.position=new R,i.rotation=new z,n.frames.push(i);let a=L.Identity();for(let t=0;t<n.channels.length;++t){let o=n.channels[t],s=e[r.i++];if(!s)continue;let c=parseFloat(s.trim());if(o.endsWith(`position`))switch(o){case bd:i.position.x=c;break;case xd:i.position.y=c;break;case Sd:i.position.z=c}else if(o.endsWith(`rotation`)){let e=P.ToRadians(c),t;switch(o){case Cd:t=L.RotationX(e);break;case wd:t=L.RotationY(e);break;case Td:t=L.RotationZ(e)}a=t.multiply(a)}}z.FromRotationMatrixToRef(a,i.rotation);for(let i of n.children)Pd(e,t,i,r)}function Fd(e,t,n,r){let i=kd();i.parent=n,r.list.push(i);let a=t.trim().split(/\s+/);if(a[0].toUpperCase()===`END`&&a[1].toUpperCase()===`SITE`?(i.type=`ENDSITE`,i.name=`ENDSITE`):(i.name=a[1],i.type=a[0].toUpperCase()),e.shift()?.trim()!=`{`)throw Error(`Expected opening { after type & name`);let o=e.shift()?.trim().split(/\s+/);if(!o)throw Error(`Unexpected end of file: missing OFFSET`);if(a=o,a[0].toUpperCase()!=`OFFSET`)throw Error(`Expected OFFSET, but got: `+a[0]);if(a.length!=4)throw Error(`OFFSET: Invalid number of values`);let s=new R(parseFloat(a[1]),parseFloat(a[2]),parseFloat(a[3]));if(isNaN(s.x)||isNaN(s.y)||isNaN(s.z))throw Error(`OFFSET: Invalid values`);if(i.offset=s,i.type!=`ENDSITE`){if(a=e.shift()?.trim().split(/\s+/),!a)throw Error(`Unexpected end of file: missing CHANNELS`);if(a[0].toUpperCase()!=`CHANNELS`)throw Error(`Expected CHANNELS definition`);let t=parseInt(a[1]);i.channels=a.splice(2,t),i.children=[]}for(;e.length>0;){let t=e.shift()?.trim();if(t===`}`)return i;t&&i.children.push(Fd(e,t,i,r))}throw Error(`Unexpected end of file: missing closing brace`)}function Id(e,t,n,r){let i=e.split(` 5`),{loopMode:a}=r;t._blockEntityCollection=!!n;let o=new Yt(``,``,t);o._parentContainer=n,t._blockEntityCollection=!1;let s=new Od(o);s.loopMode=a;let c=i.shift();if(!c||c.trim().toUpperCase()!==Ed)throw Error(`HIERARCHY expected`);let l=i.shift();if(!l)throw Error(`Unexpected end of file after HIERARCHY`);let u=Fd(i,l.trim(),null,s),d=i.shift();if(!d||d.trim().toUpperCase()!==Dd)throw Error(`MOTION expected`);let f=i.shift();
5if(!f)throw Error(`Unexpected end of file before frame count`);let p=f.trim().split(/[\s]+/);if(p.length<2)throw Error(`Invalid frame count line`);let m=parseInt(p[1]);if(isNaN(m))throw Error(`Failed to read number of frames.`);s.numFrames=m;let h=i.shift();if(!h)throw Error(`Unexpected end of file before frame time`);let g=h.trim().split(/[\s]+/);if(g.length<3)throw Error(`Invalid frame time line`);let _=parseFloat(g[2]);if(isNaN(_))throw Error(`Failed to read frame time.`);if(_<=0)throw Error(`Failed to read frame time. Invalid value `+_);s.frameRate=1/_;for(let e=0;e<m;++e){let t=i.shift();t&&Pd(t.trim().split(/[\s]+/)||[],e,u,{i:0})}return s.root=u,Nd(s.root,null,s),s.skeleton.returnToRest(),s.skeleton}var Ld=e({BVHFileLoader:()=>Rd});ne();var Rd=class e{constructor(t){this.name=c.name,this.extensions=c.extensions,this._loadingOptions={...e._DefaultLoadingOptions,...t??{}}}static get _DefaultLoadingOptions(){return{loopMode:M.ANIMATIONLOOPMODE_CYCLE}}createPlugin(t){return new e(t[c.name])}canDirectLoad(e){return this.isBvhHeader(e)}isBvhHeader(e){return e.split(` 6`)[0]==`HIERARCHY`}isNotBvhHeader(e){return!this.isBvhHeader(e)}importMeshAsync(e,t,n){if(typeof n!=`string`)return Promise.reject(`BVH loader expects string data.`);if(this.isNotBvhHeader(n))return Promise.reject(`BVH loader expects HIERARCHY header.`);try{let e=Id(n,t,null,this._loadingOptions);return Promise.resolve({meshes:[],particleSystems:[],skeletons:[e],animationGroups:[],transformNodes:[],geometries:[],lights:[],spriteManagers:[]})}catch(e){return Promise.reject(e)}}loadAsync(e,t){return typeof t==`string`?this.isNotBvhHeader(t)?Promise.reject(`BVH loader expects HIERARCHY header.`):this.importMeshAsync(null,e,t).then(()=>{}):Promise.reject(`BVH loader expects string data.`)}loadAssetContainerAsync(e,t){if(typeof t!=`string`)return Promise.reject(`BVH loader expects string data.`);if(this.isNotBvhHeader(t))return Promise.reject(`BVH loader expects HIERARCHY header.`);let n=new bt(e);try{let r=Id(t,e,n,this._loadingOptions);return n.skeletons.push(r),Promise.resolve(n)}catch(e){return Promise.reject(e)}}};mn(),nt(),ot();var zd=65521,Bd=15,Vd=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258],Hd=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],Ud=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577],Wd=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],Gd=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];function Kd(e,t){if(!Number.isInteger(t)||t<0)throw Error(`zlib: invalid expected length`);if(e.byteLength<6)throw Error(`zlib: unexpected end of input`);let n=e[0],r=e[1];if((n&15)!=8||n>>4>7||((n<<8)+r)%31!=0)throw Error(`zlib: invalid header`);if(r&32)throw Error(`zlib: preset dictionary not supported`);let i=new qd(e,2,e.byteLength-4),a=new Jd(t),o=!1;for(;!o;)switch(o=i.readBits(1)===1,i.readBits(2)){case 0:ef(i,a);break;case 1:tf(i,a,Qd(),$d());break;case 2:{let{literalLengthTree:e,distanceTree:t}=nf(i);tf(i,a,e,t);break}default:throw Error(`deflate: invalid block type`)}if(i.byteOffset<e.byteLength-4)throw Error(`zlib: trailing deflate data`);a.finish();let s=(e[e.byteLength-4]<<24|e[e.byteLength-3]<<16|e[e.byteLength-2]<<8|e[e.byteLength-1])>>>0;if(a.adler32()!==s)throw Error(`zlib: adler32 mismatch`);return a.bytes}var qd=class{constructor(e,t,n){this.input=e,this.byteOffset=t,this.endOffset=n,this.bitBuffer=0,this.bitCount=0}readBits(e){this.ensureBits(e);let t=this.bitBuffer&(1<<e)-1;return this.bitBuffer>>>=e,this.bitCount-=e,t}readBit(){if(this.bitCount===0){if(this.byteOffset>=this.endOffset)throw Error(`zlib: unexpected end of input`);this.bitBuffer=this.input[this.byteOffset++],this.bitCount=8}let e=this.bitBuffer&1;return this.bitBuffer>>>=1,this.bitCount--,e}alignToByte(){this.bitBuffer=0,this.bitCount=0}readUint16LE(){if(this.ensureByteAligned(),this.byteOffset+2>this.endOffset)throw Error(`zlib: unexpected end of input`);let e=this.input[this.byteOffset]|this.input[this.byteOffset+1]<<8;return this.byteOffset+=2,e}readByte(){if(this.ensureByteAligned(),this.byteOffset>=this.endOffset)throw Error(`zlib: unexpected end of input`);return this.input[this.byteOffset++]}ensureByteAligned(){if(this.bitCount!==0)throw Error(`deflate: expected byte al
6ignment`)}ensureBits(e){for(;this.bitCount<e;){if(this.byteOffset>=this.endOffset)throw Error(`zlib: unexpected end of input`);this.bitBuffer|=this.input[this.byteOffset++]<<this.bitCount,this.bitCount+=8}}},Jd=class{constructor(e){this.offset=0,this.adlerA=1,this.adlerB=0,this.bytes=new Uint8Array(e)}writeByte(e){if(this.offset>=this.bytes.byteLength)throw Error(`zlib: output length mismatch`);let t=e&255;this.bytes[this.offset++]=t,this.adlerA+=t,this.adlerB+=this.adlerA,this.adlerA%=zd,this.adlerB%=zd}copy(e,t){if(e<=0||e>this.offset)throw Error(`deflate: distance out of range`);for(let n=0;n<t;n++)this.writeByte(this.bytes[this.offset-e])}finish(){if(this.offset!==this.bytes.byteLength)throw Error(`zlib: output length mismatch`)}adler32(){return(this.adlerB<<16|this.adlerA)>>>0}},Yd=class{constructor(e,t={}){let n=Array(16).fill(0),r=0,i=0;for(let t of e){if(!Number.isInteger(t)||t<0||t>Bd)throw Error(`deflate: invalid huffman code lengths`);t>0&&(n[t]++,r++,i=Math.max(i,t))}if(r===0){if(t.allowEmpty){this.symbolsByLength=[],this.maxCodeLength=0;return}throw Error(`deflate: invalid huffman code lengths`)}let a=1;for(let e=1;e<=Bd;e++)if(a=(a<<1)-n[e],a<0)throw Error(`deflate: invalid huffman code lengths`);if(a!==0&&r!==1)throw Error(`deflate: invalid huffman code lengths`);let o=Array(16).fill(0),s=0;for(let e=1;e<=Bd;e++)s=s+n[e-1]<<1,o[e]=s;this.symbolsByLength=Array.from({length:16},(e,t)=>{if(n[t]===0)return;let r=new Int16Array(1<<t);return r.fill(-1),r});for(let t=0;t<e.length;t++){let n=e[t];n!==0&&(this.symbolsByLength[n][o[n]++]=t)}this.maxCodeLength=i}decode(e){if(this.maxCodeLength===0)throw Error(`deflate: invalid huffman code`);let t=0;for(let n=1;n<=this.maxCodeLength;n++){t=t<<1|e.readBit();let r=this.symbolsByLength[n]?.[t]??-1;if(r>=0)return r}throw Error(`deflate: invalid huffman code`)}},Xd,Zd;function Qd(){if(!Xd){let e=Array(288);for(let t=0;t<=143;t++)e[t]=8;for(let t=144;t<=255;t++)e[t]=9;for(let t=256;t<=279;t++)e[t]=7;for(let t=280;t<=287;t++)e[t]=8;Xd=new Yd(e)}return Xd}function $d(){return Zd||=new Yd(Array(32).fill(5)),Zd}function ef(e,t){e.alignToByte();let n=e.readUint16LE();if(((n^e.readUint16LE())&65535)!=65535)throw Error(`deflate: invalid stored block length`);for(let r=0;r<n;r++)t.writeByte(e.readByte())}function tf(e,t,n,r){for(;;){let i=n.decode(e);if(i<256){t.writeByte(i);continue}if(i===256)return;if(i>285)throw Error(`deflate: invalid literal/length symbol`);let a=i-257,o=Vd[a]+e.readBits(Hd[a]),s=r.decode(e);if(s>29)throw Error(`deflate: invalid distance symbol`);let c=Ud[s]+e.readBits(Wd[s]);t.copy(c,o)}}function nf(e){let t=e.readBits(5)+257,n=e.readBits(5)+1,r=e.readBits(4)+4,i=Array(19).fill(0);for(let t=0;t<r;t++)i[Gd[t]]=e.readBits(3);let a=rf(e,new Yd(i),t+n),o=a.slice(0,t),s=a.slice(t);if(o[256]===0)throw Error(`deflate: missing end-of-block code`);return{literalLengthTree:new Yd(o),distanceTree:new Yd(s,{allowEmpty:!0})}}function rf(e,t,n){let r=[];for(;r.length<n;){let i=t.decode(e);if(i<=15){r.push(i);continue}let a,o;switch(i){case 16:if(r.length===0)throw Error(`deflate: invalid code length repeat`);o=r[r.length-1],a=e.readBits(2)+3;break;case 17:o=0,a=e.readBits(3)+3;break;case 18:o=0,a=e.readBits(7)+11;break;default:throw Error(`deflate: invalid code length symbol`)}if(r.length+a>n)throw Error(`deflate: invalid code length repeat`);for(let e=0;e<a;e++)r.push(o)}return r}var af=`Kaydara FBX Binary \0`,of=27,sf=!0;function cf(e){let t=new DataView(e),n=new Uint8Array(e);if(sf=n.length>22?n[22]===0:!0,vf(n,0,21)!==af)throw Error(`Not a valid binary FBX file`);if(e.byteLength<of)throw Error(`Truncated binary FBX header`);let r=t.getUint32(23,sf),i=r>=7500,a=[],o=of;for(;o<e.byteLength;){let r=lf(t,n,o,i,e.byteLength);if(r===null)break;a.push(r.node),o=r.endOffset}return{version:r,nodes:a}}function lf(e,t,n,r,i){let a,o,s,c;if(r?(ff(t,n,25,i,`FBX node header`),a=mf(e,n),o=mf(e,n+8),s=mf(e,n+16),c=25):(ff(t,n,13,i,`FBX node header`),a=e.getUint32(n,sf),o=e.getUint32(n+4,sf),s=e.getUint32(n+8,sf),c=13),a===0)return null;if(a<=n||a>i)throw Error(`Invalid FBX node end offset ${a} at offset ${n}`);let l=t[n+c-1];ff(t,n+c,l,a,`FBX node name`);let u=vf(t,n+c,l),d=n+c+l,f=d+s;if(f>a)throw Error(`Invalid FBX property list length for node '${u}' at offset ${n}`);let p=[];for(let n=0;n<o;n++){let n=uf(e,t,d,f);p.push(n.property),d=n.nextOffset}if(d!==f)throw Error(`Invalid FBX property list length for node '${u}' at offset ${n}`);let m=[];
6if(d<a)for(;d<a;){let n=lf(e,t,d,r,a);if(n===null)break;if(n.endOffset<=d||n.endOffset>a)throw Error(`Invalid FBX child node end offset ${n.endOffset} at offset ${d}`);m.push(n.node),d=n.endOffset}return{node:{name:u,properties:p,children:m},endOffset:a}}function uf(e,t,n,r){ff(t,n,1,r,`FBX property type`);let i=String.fromCharCode(t[n]);switch(n+=1,i){case`C`:{ff(t,n,1,r,`FBX boolean property`);let e=t[n];return e>1?{property:{type:`int32`,value:e},nextOffset:n+1}:{property:{type:`boolean`,value:e!==0},nextOffset:n+1}}case`Z`:return ff(t,n,1,r,`FBX byte property`),{property:{type:`int32`,value:t[n]},nextOffset:n+1};case`Y`:return ff(t,n,2,r,`FBX int16 property`),{property:{type:`int16`,value:e.getInt16(n,sf)},nextOffset:n+2};case`I`:return ff(t,n,4,r,`FBX int32 property`),{property:{type:`int32`,value:e.getInt32(n,sf)},nextOffset:n+4};case`F`:return ff(t,n,4,r,`FBX float32 property`),{property:{type:`float32`,value:e.getFloat32(n,sf)},nextOffset:n+4};case`D`:return ff(t,n,8,r,`FBX float64 property`),{property:{type:`float64`,value:e.getFloat64(n,sf)},nextOffset:n+8};case`L`:{ff(t,n,8,r,`FBX int64 property`);let i=hf(e,n),a={type:`int64`,value:i};return Number.isSafeInteger(i)||(a.raw=gf(e,n)),{property:a,nextOffset:n+8}}case`S`:{ff(t,n,4,r,`FBX string property length`);let i=e.getUint32(n,sf);return ff(t,n+4,i,r,`FBX string property data`),{property:{type:`string`,value:yf(t,n+4,i)},nextOffset:n+4+i}}case`R`:{ff(t,n,4,r,`FBX raw property length`);let i=e.getUint32(n,sf);return ff(t,n+4,i,r,`FBX raw property data`),{property:{type:`raw`,value:t.slice(n+4,n+4+i)},nextOffset:n+4+i}}case`f`:return df(e,t,n,`float32[]`,4,r);case`d`:return df(e,t,n,`float64[]`,8,r);case`i`:return df(e,t,n,`int32[]`,4,r);case`l`:return df(e,t,n,`int64[]`,8,r);case`b`:return df(e,t,n,`boolean[]`,1,r);case`c`:return df(e,t,n,`boolean[]`,1,r);default:throw Error(`Unknown FBX property type: '${i}' at offset ${n-1}`)}}function df(e,t,n,r,i,a){ff(t,n,12,a,`FBX array property header for ${r}`);let o=e.getUint32(n,sf),s=e.getUint32(n+4,sf),c=e.getUint32(n+8,sf);n+=12;let l=o*i;ff(t,n,c,a,`FBX array property data for ${r}`);let u;if(s===1)u=Kd(t.subarray(n,n+c),l);else{if(s!==0)throw Error(`Unsupported FBX array encoding: ${s}`);if(c!==l)throw Error(`Invalid FBX array byte length for ${r}`);u=t.slice(n,n+c)}!sf&&i>1&&r!==`int64[]`&&pf(u,i);let d=u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength),f;switch(r){case`float32[]`:f=new Float32Array(d);break;case`float64[]`:f=new Float64Array(d);break;case`int32[]`:f=new Int32Array(d);break;case`boolean[]`:f=u;break;case`int64[]`:f=_f(u);break;default:throw Error(`Unexpected array type: ${r}`)}return{property:{type:r,value:f},nextOffset:n+c}}function ff(e,t,n,r,i){if(t<0||n<0||t+n>r||t+n>e.byteLength)throw Error(`${i}: unexpected end of input`)}function pf(e,t){for(let n=0;n+t<=e.length;n+=t)for(let r=n,i=n+t-1;r<i;r++,i--){let t=e[r];e[r]=e[i],e[i]=t}}function mf(e,t){let n=e.getUint32(sf?t:t+4,sf);return e.getUint32(sf?t+4:t,sf)*4294967296+n}function hf(e,t){let n=e.getUint32(sf?t:t+4,sf);return e.getInt32(sf?t+4:t,sf)*4294967296+n}function gf(e,t){let n=e.getUint32(sf?t:t+4,sf),r=e.getUint32(sf?t+4:t,sf),i=!!(r&2147483648);i&&(n=~n+1>>>0,r=~r+ +(n===0)>>>0);let a=[];for(;r!==0||n!==0;){let e=Math.floor(r/10),t=r%10*4294967296+n;a.push(t%10),r=e,n=Math.floor(t/10)}return(i?`-`:``)+(a.length>0?a.reverse().join(``):`0`)}function _f(e){let t=new DataView(e.buffer,e.byteOffset,e.byteLength),n=new Float64Array(e.byteLength/8);for(let e=0;e<n.length;e++)n[e]=hf(t,e*8);return n}function vf(e,t,n){let r=``;for(let i=0;i<n;i++)r+=String.fromCharCode(e[t+i]);return r}function yf(e,t,n){return new TextDecoder(`utf-8`).decode(e.subarray(t,t+n))}function bf(e){let t=new wf(e),n=Sf(e),r=[];for(;!t.isEOF()&&(t.skipWhitespaceAndComments(),!t.isEOF());){let e=Tf(t);e&&r.push(e)}return n>=7200&&xf(r),{version:n,nodes:r}}function xf(e){for(let t of e){if(t.name===`KeyAttrDataFloat`&&t.properties.length===1&&t.properties[0].value instanceof Float64Array){let e=t.properties[0].value,n=new Int32Array(e.length);for(let t=0;t<e.length;t++)n[t]=e[t]|0;t.properties[0]={type:`float32[]`,value:new Float32Array(n.buffer)}}t.children.length>0&&xf(t.children)}}function Sf(e){let t=e.match(/;\s*FBX\s+(\d+)\.(\d+)\.(\d+)/);if(t)return parseInt(t[1])*1e3+parseInt(t[2])*100+parseInt(t[3]);let n=e.match(/FBXVersion:\s*(\d+)/);return n?parseInt(n[1]):e.includes(`Properties70`)?7e3:6e3}var Cf;(function(e){e[e.Identifier=0]=`Identifier`,e[e.Number=1]=`Number`,e[e.String=2]=`String`,e[e.OpenBrace=3]=`OpenBrace`,e[e.CloseBrace=4]=`CloseBrace`,e[e.Colon=5]=`Colon`,e[e.Comma=6]=`Comma`,e[e.Star=7]=`Star`,e[e.EOF=8]=`EOF`})(Cf||={});var wf=class{constructor(e){this.text=e,this.pos=0,this.len=e.length}isEOF(){return this.skipWhitespaceAndComments(),this.pos>=this.len}peek(){let e=this.pos,t=this.next();return this.pos=e,t}next(){if(this.skipWhitespaceAndComments(),this.pos>=this.len)return{type:8,value:``,pos:this.pos};let e=this.text[this.pos],t=this.pos;switch(e){case`{`:return this.pos++,{type:3,value:`{`,pos:t};case`}`:return this.pos++,{type:4,value:`}`,pos:t};case`:`:return this.pos++,{type:5,value:`:`,pos:t};case`,`:return this.pos++,{type:6,value:`,`,pos:t};case`*`:return this.pos++,{type:7,value:`*`,pos:t};case`"`:return this.readString();default:if(this.isNumberStart(e))return this.readNumber();if(this.isIdentStart(e))return this.readIdentifier();throw Error(`Unexpected character '${e}' at position ${this.pos}`)}}expect(e){let t=this.next();if(t.type!==e)throw Error(`Expected token type ${e} but got ${t.type} ('${t.value}') at pos ${t.pos}`);return t}isNextNodeStart(){let e=this.pos;if(this.skipWhitespaceAndComments(),this.pos<this.len&&this.isIdentStart(this.text[this.pos])){for(;this.pos<this.len&&this.isIdentChar(this.text[this.pos]);)this.pos++;for(;this.pos<this.len&&(this.text[this.pos]===` `||this.text[this.pos]===` `);)this.pos++;let t=this.pos<this.len&&this.text[this.pos]===`:`;return this.pos=e,t}return this.pos=e,!1}skipWhitespaceAndComments(){for(;this.pos<this.len;){let e=this.text[this.pos];if(e===` `||e===` `||e===`\r`||e===` 7`)this.pos++;else if(e===`;`)for(;this.pos<this.len&&this.text[this.pos]!==` 8`;)this.pos++;else break}}readString(){let e=this.pos;this.pos++;let t=``;for(;this.pos<this.len&&this.text[this.pos]!==`"`;)this.text[this.pos]===`\\`&&this.pos+1<this.len&&this.pos++,t+=this.text[this.pos],this.pos++;return this.pos<this.len&&this.pos++,t.includes(`"
8`)&&(t=t.split(`"`).join(`"`)),{type:2,value:t,pos:e}}readNumber(){let e=this.pos;if((this.text[this.pos]===`-`||this.text[this.pos]===`+`)&&this.pos++,this.pos<this.len&&this.isIdentStart(this.text[this.pos])){for(;this.pos<this.len&&this.isIdentStart(this.text[this.pos]);)this.pos++;return this.skipSpecialNumberSuffix(),{type:1,value:this.text.substring(e,this.pos),pos:e}}for(;this.pos<this.len&&this.isDigit(this.text[this.pos]);)this.pos++;if(this.pos<this.len&&this.text[this.pos]===`.`)for(this.pos++;this.pos<this.len&&this.isDigit(this.text[this.pos]);)this.pos++;if(this.pos<this.len&&(this.text[this.pos]===`e`||this.text[this.pos]===`E`))for(this.pos++,this.pos<this.len&&(this.text[this.pos]===`+`||this.text[this.pos]===`-`)&&this.pos++;this.pos<this.len&&this.isDigit(this.text[this.pos]);)this.pos++;if(this.pos<this.len&&this.text[this.pos]===`#`){for(this.pos++;this.pos<this.len&&(this.isIdentStart(this.text[this.pos])||this.isDigit(this.text[this.pos]));)this.pos++;this.skipSpecialNumberSuffix()}return{type:1,value:this.text.substring(e,this.pos),pos:e}}readIdentifier(){let e=this.pos;for(;this.pos<this.len&&this.isIdentChar(this.text[this.pos]);)this.pos++;return this.skipSpecialNumberSuffix(),{type:0,value:this.text.substring(e,this.pos),pos:e}}skipSpecialNumberSuffix(){if(this.pos<this.len&&this.text[this.pos]===`(`)for(;this.pos<this.len;){let e=this.text[this.pos];if(e===`(`||e===`)`||this.isIdentChar(e))this.pos++;else break}}isDigit(e){return e>=`0`&&e<=`9`}isNumberStart(e){if(this.isDigit(e)||e===`.`)return!0;if((e===`-`||e===`+`)&&this.pos+1<this.len){let e=this.text[this.pos+1];return this.isDigit(e)||e===`.`||Df(this.text.substring(this.pos+1,this.pos+10))}return Df(this.text.substring(this.pos,this.pos+9))?!this.isFollowedByColon(this.pos):!1}isFollowedByColon(e){let t=e;for(;t<this.len&&this.isIdentChar(this.text[t]);)t++;for(;t<this.len&&(this.text[t]===` `||this.text[t]===` `);)t++;return t<this.len&&this.text[t]===`:`}isIdentStart(e){return e>=`a`&&e<=`z`||e>=`A`&&e<=`Z`||e===`_`}isIdentChar(e){return this.isIdentStart(e)||this.isDigit(e)||e===`|`||e===`-`}};function Tf(e){let t=e.peek();if(t.type===4||t.type===8)return null;let n=e.next();if(n.type!==0)throw Error(`Expected identifier for node name, got '${n.value}' at pos ${n.pos}`);let r=n.value;e.expect(5);let i=[],a=[],o=e.peek();if(o.type===7){e.next();let t=e.expect(1),n=parseInt(t.value);e.expect(3);let o=e.next();if(o.type===0&&o.value===`a`){e.expect(5);let t=Ef(e,n);i.push({type:`float64[]`,value:new Float64Array(t)})}return e.expect(4),{name:r,properties:i,children:a}}for(o=e.peek();o.type!==3&&o.type!==4&&o.type!==8;){if(o.type===1){let t=e.next(),n=Of(t.value);if(Number.isInteger(n)&&!t.value.includes(`.`)&&!t.value.includes(`e`)&&!t.value.includes(`E`)){let e={type:Af(n)?`int32`:`int64`,value:n};Number.isSafeInteger(n)||(e.raw=kf(t.value)),i.push(e)}else i.push({type:`float64`,value:n})}else if(o.type===2){let t=e.next();i.push({type:`string`,value:t.value})}else if(o.type===0){if(e.isNextNodeStart())break;let t=e.next();i.push({type:`string`,value:t.value})}else if(o.type===6)e.next();else break;o=e.peek()}if(o=e.peek(),o.type===3){for(e.next();o=e.peek(),o.type!==4&&o.type!==8;){let t=Tf(e);if(t)a.push(t);else break}e.expect(4)}return{name:r,properties:i,children:a}}function Ef(e,t){let n=[];for(;;){let t=e.peek();if(t.type===4||t.type===8)break;if(t.type===6){e.next();continue}if(t.type===1){let t=e.next();n.push(Of(t.value))}else if(t.type===0&&!e.isNextNodeStart()){let t=e.next();n.push(Of(t.value))}else break}if(n.length!==t)throw Error(`ASCII FBX array declared ${t} values but parsed ${n.length}`);return n}function Df(e){return/^(?:inf(?:inity)?|nan|ind)(?![A-Za-z0-9_|])/i.test(e)}function Of(e){let t=Number(e);if(!Number.isNaN(t))return t;let n=e.startsWith(`-`)?-1:1,r=e.replace(/^[+-]/,``).replace(/\(.*$/,``);return/#INF/i.test(r)||/^inf/i.test(r)?n*(1/0):NaN}function kf(e){let t=e.startsWith(`-`),n=e.replace(/^[+-]/,``).replace(/^0+(?=\d)/,``);return t&&n!==`0`?`-${n}`:n}function Af(e){return e>=-2147483648&&e<=2147483647}function J(e,t){return e.children.find(e=>e.name===t)}function jf(e,t){return e.children.filter(e=>e.name===t)}
8function Mf(e,t){return e.nodes.find(e=>e.name===t)}function Y(e,t){if(t<e.properties.length)return e.properties[t].value}function Nf(e){if(typeof e==`number`&&Number.isFinite(e)&&Number.isInteger(e))return e}function Pf(e){if(!e||e.properties.length===0)return null;let t=e.properties[0].value;if(e.properties.length===1&&(t instanceof Float32Array||t instanceof Float64Array||t instanceof Int32Array||t instanceof Uint8Array))return t;let n=new Float64Array(e.properties.length);for(let t=0;t<e.properties.length;t++){let r=e.properties[t].value;if(typeof r==`number`)n[t]=r;else if(typeof r==`boolean`)n[t]=+!!r;else return null}return n}function X(e){let t=e.indexOf(`\0�`);if(t>=0)return e.substring(0,t);let n=e.indexOf(`::`);return n>=0?e.substring(n+2):e}function Ff(e){let t=new Map,n=Mf(e,`Definitions`);if(!n)return t;for(let e of n.children){if(e.name!==`ObjectType`)continue;let n=Y(e,0);if(n)for(let r of e.children){if(r.name!==`PropertyTemplate`)continue;let e=Y(r,0);if(!e)continue;let i=Hf(n,e,r),a=t.get(n);a||(a=new Map,t.set(n,a)),a.set(e,i)}}return t}function If(e,t,n){let r=e.get(t);if(r)return n?r.get(n):r.values().next().value}function Lf(e,t,n,r=0){return Bf(e,t,n)?.[r]}function Rf(e,t,n,r){return Vf(Lf(e,t,n))??r}function zf(e,t,n,r){let i=Bf(e,t,n);if(!i)return r;let a=Vf(i[0]),o=Vf(i[1]),s=Vf(i[2]);return a!==void 0&&o!==void 0&&s!==void 0?[a,o,s]:r}function Bf(e,t,n){return qf(e,n)??t?.properties.get(n)?.values}function Vf(e){if(typeof e==`number`)return e}function Hf(e,t,n){let r=new Map,i=J(n,`Properties70`);for(let e of i?.children??[]){if(e.name!==`P`)continue;let t=Jf(e);t&&r.set(t.name,t)}return{objectType:e,templateName:t,properties:r}}function Uf(e){let t=[];if(!e)return t;for(let n of e.children)if(n.name===`Properties70`||n.name===`Properties60`)for(let e of n.children){if(e.name!==`P`&&e.name!==`PS`&&e.name!==`Property`)continue;let n=Y(e,0);if(typeof n!=`string`)continue;let r=e.name!==`Property`,i=Y(e,1),a=Y(e,r?3:2);t.push({name:n,type:typeof i==`string`?i:``,flags:typeof a==`string`?a:``,values:e.properties.slice(r?4:3).map(e=>e.value)})}return t}function Wf(e){let t={},n=!1;for(let r of Uf(e)){if(!r.flags.includes(`U`))continue;let e=Kf(r.values,r.type);e!==void 0&&(t[r.name]=e,n=!0)}return n?t:void 0}var Gf=new Set([`Integer`,`int`,`Number`,`double`,`Float`,`float`,`Bool`,`bool`,`Enum`,`enum`,`Visibility`,`Roll`,`Weight`,`Distance`,`KTime`,`Time`]);function Kf(e,t){if(e.length===0)return;let n=e[0];if(t!==void 0&&Gf.has(t)&&(typeof n==`number`||typeof n==`boolean`))return n;if(e.length===1)return typeof n==`string`||typeof n==`number`||typeof n==`boolean`?n:void 0;let r=[];for(let t of e)if(typeof t==`number`)r.push(t);else if(typeof t==`boolean`)r.push(+!!t);else break;return r.length===e.length?r:typeof n==`string`?n:void 0}function qf(e,t){let n=[J(e,`Properties70`),J(e,`Properties60`)].filter(e=>e!==void 0),r;for(let e of n)for(let n of e.children)(n.name===`P`||n.name===`Property`)&&Y(n,0)===t&&(r=n.properties.slice(n.name===`Property`?3:4).map(e=>e.value));return r}function Jf(e){let t=Y(e,0);return t?{name:t,propertyType:Y(e,1)??``,label:Y(e,2)??``,flags:Y(e,3)??``,values:e.properties.slice(4).map(e=>e.value)}:null}function Yf(e,t){let n=zf(e,t,`Lcl Translation`,[0,0,0]),r=zf(e,t,`Lcl Rotation`,[0,0,0]),i=zf(e,t,`Lcl Scaling`,[1,1,1]),a=zf(e,t,`PreRotation`,[0,0,0]),o=zf(e,t,`PostRotation`,[0,0,0]),s=zf(e,t,`RotationPivot`,[0,0,0]),c=zf(e,t,`ScalingPivot`,[0,0,0]),l=zf(e,t,`RotationOffset`,[0,0,0]),u=zf(e,t,`ScalingOffset`,[0,0,0]),d=zf(e,t,`GeometricTranslation`,[0,0,0]),f=zf(e,t,`GeometricRotation`,[0,0,0]),p=zf(e,t,`GeometricScaling`,[1,1,1]),m=Rf(e,t,`RotationOrder`,0),h=Rf(e,t,`InheritType`,1),g=Rf(e,t,`RotationActive`,1),_=Rf(e,t,`RotationSpaceForLimitOnly`,0),v=g!==0&&_===0;v||(m=0,a=[0,0,0],o=[0,0,0]);let y=h===0||h===1||h===2?[]:[`InheritType ${h} is unknown; treated as RSrs.`];return{translation:n,rotation:r,scale:i,preRotation:a,postRotation:o,rotationPivot:s,scalingPivot:c,rotationOffset:l,scalingOffset:u,geometricTranslation:d,geometricRotation:f,geometricScaling:p,rotationOrder:m,inheritType:h,rotationActive:v,diagnostics:y}}function Xf(e){let t=new Map,n=[],r=new Map,i=new Map,a=[],o=[],s=[],c=new Map,l=new Map,u=new Map,d=new Map,f=Mf(e,`Objects`),p=Mf(e,`Connections`),m=new Set,h=e=>{let t=e?.value;typeof t==`number`&&Number.isSafeInteger(t)&&m.add(t)};for(let e of f?.children??[])h(e.properties[0]);for(let e of p?.children??[])h(e.properties[1]),h(e.properties[2]),h(e.properties[3]);let g=-1,_=()=>{for(;m.has(g);)g--;let e=g--;return m.add(e),e},v=new Map,y=e=>{if(e){if(e.raw!==void 0){let t=v.get(e.raw);return t===void 0&&(t=_(),v.set(e.raw,t)),t}return Nf(e.value)}},b=e=>{let t=y(e);if(t!==void 0)return t;let n=e?.value;if(typeof n!=`string`)return;let r=c.get(n);if(r!==void 0)return r;let i=X(n);return i===`Scene`?0:l.get(i)},x=e=>{let t=c.get(e);if(t===void 0){t=_(),c.set(e,t);let n=X(e);l.has(n)||l.set(n,t)}return t},S=(e,t)=>{let n=u.get(e);n||(n=new Map,u.set(e,n));let r=n.get(t);return r===void 0&&(r=_(),n.set(t,r)),r},C=(e,o,c)=>{let l=e.children.filter(e=>e.name===`Shape`);if(l.length===0)return;let u=S(`BlendShape`,c),d=$f(`Deformer`,u,`Deformer::${X(c)}`,`BlendShape`,[Qf(100)]);t.set(u,d),n.push({id:u,node:d,source:`legacySyntheticBlendShape`,legacyName:c,synthetic:!0}),ep(a,r,i,s,`OO`,u,o);for(let e of l){let o=X(Y(e,0)??`Shape`),l=S(`BlendShapeChannel`,`${c}|${o}`),d=$f(`Deformer`,l,`SubDeformer::${o}`,`BlendShapeChannel`,[Qf(100),{name:`DeformPercent`,properties:[{type:`float64`,value:0}],children:[]},{name:`Properties60`,properties:[],children:[{name:`Property`,properties:[{type:`string`,value:`DeformPercent`},{type:`string`,value:`Number`},{type:`string`,value:`A`},{type:`float64`,value:0}],children:[]}]}]);t.set(l,d),n.push({id:l,node:d,source:`legacySyntheticBlendShape`,legacyName:`${c}|${o}`,synthetic:!0}),ep(a,r,i,s,`OO`,l,u);let f=S(`Shape`,`${c}|${o}`),p=$f(`Geometry`,f,`Geometry::${o}
8`,`Shape`,e.children);t.set(f,p),n.push({id:f,node:p,source:`legacySyntheticBlendShape`,legacyName:`${c}|${o}`,synthetic:!0}),ep(a,r,i,s,`OO`,f,l)}};if(f)for(let e of f.children){let o=e.properties[0];if(o){let c=y(o);if(c!==void 0)t.set(c,e),n.push({id:c,node:e,source:`Objects`,synthetic:!1}),e.name===`Geometry`&&Y(e,2)===`Mesh`&&C(e,c,String(c));else if(typeof o.value==`string`){let c=o.value,l=x(c),u=tp(e,l);t.set(l,u),n.push({id:l,node:u,source:`Objects`,legacyName:c,synthetic:!1});let f=e.name===`Model`?Y(e,1):void 0;if(f===`Mesh`){let o=S(`Geometry`,c),u=np(e,o);t.set(o,u),n.push({id:o,node:u,source:`legacySyntheticGeometry`,legacyName:c,synthetic:!0}),ep(a,r,i,s,`OO`,o,l),d.set(l,o),C(e,o,c)}else if(f===`Light`||f===`Camera`){let o=S(`NodeAttribute`,c),u=$f(`NodeAttribute`,o,`NodeAttribute::${X(c)}`,f,e.children);t.set(o,u),n.push({id:o,node:u,source:`legacySyntheticAttribute`,legacyName:c,synthetic:!0}),ep(a,r,i,s,`OO`,o,l)}}}}if(p)for(let e of p.children){if(e.name!==`C`&&e.name!==`Connect`)continue;let n=o.length,c=Y(e,0),l=e.properties[1],u=e.properties[2],f;c===`PO`&&typeof e.properties[2]?.value==`string`&&e.properties.length>3&&(c=`OP`,f=e.properties[2].value,l=e.properties[3],u=e.properties[1]);let p={source:e.name,rawType:c,accepted:!1};if(o.push(p),c!==`OO`&&c!==`OP`){let e=b(l),t=b(u);s.push({reason:`unsupported-connection-type`,message:`Unsupported FBX connection type '${c??``}' was not added to the graph.`,connectionIndex:n,type:c,childId:e,parentId:t});continue}if(l===void 0||u===void 0){s.push({reason:`missing-connection-endpoint`,message:`FBX connection is missing a child or parent endpoint.`,connectionIndex:n,type:c});continue}let m=b(l),h=b(u);if(m!==void 0&&h!==void 0&&t.get(m)?.name===`Deformer`&&(h=d.get(h)??h),m===void 0||h===void 0){s.push({reason:`unresolved-legacy-endpoint`,message:`FBX connection references a legacy string endpoint that is not present in the object table.`,connectionIndex:n,type:c});continue}let g=f??(c===`OP`&&e.properties.length>3?Y(e,3):void 0);p.childId=m,p.parentId=h,p.propertyName=g,m===h&&s.push({reason:`self-loop`,message:`FBX connection references the same object as child and parent.`,connectionIndex:n,type:c,childId:m,parentId:h,propertyName:g}),t.has(m)||s.push({reason:`unresolved-object-reference`,message:`FBX connection child ID is not present in the object table.`,connectionIndex:n,type:c,childId:m,parentId:h,propertyName:g}),h!==0&&!t.has(h)&&s.push({reason:`unresolved-object-reference`,message:`FBX connection parent ID is not present in the object table.`,connectionIndex:n,type:c,childId:m,parentId:h,propertyName:g}),ep(a,r,i,s,c,m,h,g,n),p.accepted=!0}return{objects:t,objectEntries:n,childrenOf:r,parentOf:i,connections:a,connectionEntries:o,diagnostics:s}}function Zf(e,t,n){let r=e.childrenOf.get(t)??[],i=[];for(let t of r){let r=e.objects.get(t.id);r&&(!n||r.name===n)&&i.push({id:t.id,node:r,propertyName:t.propertyName})}return i}function Qf(e){return{name:`Version`,properties:[{type:`int32`,value:e}],children:[]}}function $f(e,t,n,r,i){return{name:e,properties:[{type:`int64`,value:t},{type:`string`,value:n},{type:`string`,value:r}],children:i}}function ep(e,t,n,r,i,a,o,s,c){e.push({type:i,childId:a,parentId:o,propertyName:s}),t.has(o)||t.set(o,[]),t.get(o).push({id:a,propertyName:s}),n.get(a)&&r.push({reason:`duplicate-parent`,message:`FBX object has multiple parents; preserving the existing last-parent behavior.`,connectionIndex:c,type:i,childId:a,parentId:o,propertyName:s}),n.set(a,{id:o,propertyName:s})}function tp(e,t){let n=X(Y(e,0)??e.name),r=Y(e,1)??``;return{...e,properties:[{type:`int64`,value:t},{type:`string`,value:n},{type:`string`,value:r}]}}function np(e,t){let n=X(Y(e,0)??`Geometry`);return{name:`Geometry`,properties:[{type:`int64`,value:t},{type:`string`,value:n},{type:`string`,value:`Mesh`}],children:e.children}}function rp(e,t){let n=X(Y(e,1)??`Geometry`),r=J(e,`Vertices`),i=r?bp(Sp(r)):new Float64Array,a=J(e,`PolygonVertexIndex`),o=a?xp(Sp(a)):new Int32Array,s=[],c=ip(o),l=ap(c,i,s),u=pp(c),d=J(e,`LayerElementNormal`),f=null;d&&(f=hp(d,`Normals`,`NormalsIndex`,u,i.length/3,3,s));let p=jf(e,`LayerElementUV`),m=[];for(let e of p){let t=J(e,`Name`),n=t?Y(t,0)??`UVSet${m.length}`:`UVSet${m.length}`,r=hp(e,`UV`,`UVIndex`,u,i.length/3,2,s);r&&m.push({name:n,data:r})}let h=m.length>0?m[0].data:null,g=J(e,`LayerElementColor`),_=null;if(g){let e=hp(g,`Colors`,`ColorIndex`,u,i.length/3,4,s);if(e){_=new Float32Array(e.length);for(let t=0;t<e.length;t++)_[t]=e[t]}}let v=J(e,`LayerElementTangent`),y=J(e,`LayerElementBinormal`),b=y?hp(y,`Binormals`,`BinormalsIndex`,u,i.length/3,3,s):null,x=v?gp(v,u,i.length/3,f,b,s):null,S=J(e,`LayerElementMaterial`),C=null;S&&(C=mp(S,c.length));let w=yp(i,l,u,f,h,m,_,x,b),T=null;if(C){let e=!0,t=C[0];for(let n=1;n<C.length;n++)if(C[n]!==t){e=!1;break}if(!e||t!==0){let e=w.indices.length/3;T=new Int32Array(e);for(let e=0;e<l.length;e++)T[e]=C[l[e].polyIndex]??0}}return{id:t,name:n,positions:w.positions,indices:w.indices,normals:w.normals,uvs:w.uvs,uvSets:w.uvSets,colors:w.colors,tangents:w.tangents,binormals:w.binormals,controlPointIndices:w.controlPointIndices,materialIndices:T,diagnostics:s}}function ip(e){let t=[],n=[],r=0;for(let i=0;i<e.length;i++){let a=e[i];a<0?(n.push(-(a+1)),t.push({indices:n,startIndex:r}),n=[],r=i+1):n.push(a)}return t}function ap(e,t,n){let r=[];for(let i=0;i<e.length;i++){let a=e[i];
8r.push(...op(a,i,t,n))}return r}function op(e,t,n,r){if(e.indices.length<3)return r.push({type:`degenerate-polygon`,message:`Polygon ${t} has fewer than three vertices.`,polygonIndex:t}),[];if(e.indices.length===3)return[{vertices:[e.startIndex,e.startIndex+1,e.startIndex+2],polyIndex:t}];let i=lp(e,n);if(!i)return r.push({type:`degenerate-polygon`,message:`Polygon ${t} has a near-zero normal; using fan triangulation.`,polygonIndex:t}),cp(e,t);let a=dp(i);if(Math.abs(a)<1e-12)return r.push({type:`degenerate-polygon`,message:`Polygon ${t} projects to near-zero area; using fan triangulation.`,polygonIndex:t}),cp(e,t);let o=sp(i,a>0,a);return o?o.map(([n,r,i])=>({vertices:[e.startIndex+n,e.startIndex+r,e.startIndex+i],polyIndex:t})):(r.push({type:`triangulation-fallback`,message:`Polygon ${t} could not be fully ear-clipped; using fan triangulation.`,polygonIndex:t}),cp(e,t))}function sp(e,t,n){let r=e.length,i=new Int32Array(r),a=new Int32Array(r);for(let e=0;e<r;e++)i[e]=(e+r-1)%r,a[e]=(e+1)%r;let o=Math.abs(n)*1e-12+1e-300,s=t?1:-1,c=t=>s*fp(e[i[t]],e[t],e[a[t]]),l=new Uint8Array(r);for(let e=0;e<r;e++)l[e]=+(c(e)<-o);let u=(e,t,n,r)=>s*fp(t,n,e)>=-o&&s*fp(n,r,e)>=-o&&s*fp(r,t,e)>=-o,d=[],f=r,p=0,m=0;for(;f>3;){let t=i[p],n=a[p],r=!1;if(!l[p]){if(c(p)<=o)r=!0,d.push([t,p,n]);else{r=!0;for(let i=a[n];i!==t;i=a[i])if(l[i]&&u(e[i],e[t],e[p],e[n])){r=!1;break}r&&d.push([t,p,n])}}if(r){a[t]=n,i[n]=t,f--,l[t]=+(c(t)<-o),l[n]=+(c(n)<-o),p=n,m=0;continue}if(p=n,++m>f)return null}let h=p;return d.push([i[h],h,a[h]]),d}function cp(e,t){let n=[];for(let r=1;r<e.indices.length-1;r++)n.push({vertices:[e.startIndex,e.startIndex+r,e.startIndex+r+1],polyIndex:t});return n}function lp(e,t){let n=up(e,t),r=Math.abs(n[0]),i=Math.abs(n[1]),a=Math.abs(n[2]);if(r+i+a<1e-12)return null;let o=r>i&&r>a?0:i>a?1:2;return e.indices.map(e=>{let r=t[e*3],i=t[e*3+1],a=t[e*3+2];return o===0?n[0]>=0?[i,a]:[a,i]:o===1?n[1]>=0?[a,r]:[r,a]:n[2]>=0?[r,i]:[i,r]})}function up(e,t){let n=0,r=0,i=0;for(let a=0;a<e.indices.length;a++){let o=e.indices[a]*3,s=e.indices[(a+1)%e.indices.length]*3,c=t[o],l=t[o+1],u=t[o+2],d=t[s],f=t[s+1],p=t[s+2];n+=(l-f)*(u+p),r+=(u-p)*(c+d),i+=(c-d)*(l+f)}return[n,r,i]}function dp(e){let t=0;for(let n=0;n<e.length;n++){let r=e[n],i=e[(n+1)%e.length];t+=r[0]*i[1]-i[0]*r[1]}return t/2}function fp(e,t,n){return(t[0]-e[0])*(n[1]-e[1])-(t[1]-e[1])*(n[0]-e[0])}function pp(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n];for(let e=0;e<r.indices.length;e++)t.push({polyIndex:n,vertexInPoly:e,controlPointIndex:r.indices[e],globalIndex:r.startIndex+e})}return t}function mp(e,t){let n=J(e,`MappingInformationType`),r=J(e,`ReferenceInformationType`);if(!n||!r)return null;let i=Y(n,0)??``,a=Y(r,0)??``;if(i===`AllSame`){let n=J(e,`Materials`),r=n?xp(Sp(n)):null,i=r&&r.length>0?r[0]:0,a=new Int32Array(t);return i!==0&&a.fill(i),a}if(i===`ByPolygon`){let t=J(e,`Materials`);if(!t)return null;let n=xp(Sp(t));if(a===`Direct`||a===`IndexToDirect`)return n}return null}function hp(e,t,n,r,i,a,o){let s=J(e,`MappingInformationType`),c=J(e,`ReferenceInformationType`);if(!s||!c)return null;let l=Y(s,0)??``,u=Y(c,0)??``,d=J(e,t);if(!d)return null;let f=bp(Sp(d)),p=null;if(u===`IndexToDirect`){let t=J(e,n);t&&(p=xp(Sp(t)))}let m=new Float64Array(r.length*a);for(let t=0;t<r.length;t++){let n=r[t],i;i=l===`ByPolygonVertex`?u===`IndexToDirect`&&p?p[n.globalIndex]:n.globalIndex:l===`ByControlPoint`||l===`ByVertice`?u===`IndexToDirect`&&p?p[n.controlPointIndex]:n.controlPointIndex:l===`ByPolygon`?u===`IndexToDirect`&&p?p[n.polyIndex]:n.polyIndex:l===`AllSame`?0:n.globalIndex;for(let n=0;n<a;n++){let r=i*a+n;i<0||r>=f.length?(o.push({type:r>=f.length?`layer-data-too-short`:`layer-index-out-of-bounds`,message:`Layer '${e.name}' references unavailable element ${i}.`,layerName:e.name,index:i}),m[t*a+n]=0):m[t*a+n]=f[r]}}return m}function gp(e,t,n,r,i,a){let o=_p(e,`Tangents`,`TangentsIndex`,t,n,a),s=hp(e,`Tangents`,`TangentsIndex`,t,n,o,a);if(!s)return null;let c=new Float64Array(t.length*4);for(let e=0;e<t.length;e++){let t=e*o,n=e*4;c[n]=s[t],c[n+1]=s[t+1],c[n+2]=s[t+2],c[n+3]=o>=4?s[t+3]:vp(e,c,r,i)}return c}function _p(e,t,n,r,i,a){let o=J(e,t);if(!o)return 3;let s=bp(Sp(o)),c=Y(J(e,`MappingInformationType`)??{name:``,properties:[],children:[]},0)??``,l=Y(J(e,`ReferenceInformationType`)??{name:``,properties:[],children:[]},0)??``,u=J(e,n),d=u?xp(Sp(u)):null,f=l===`IndexToDirect`&&d?Math.max(...Array.from(d),0)+1:c===`ByControlPoint`||c===`ByVertice`?i:c===`AllSame`?1:r.length;if(f>0&&s.length%f===0){let e=s.length/f;if(e===3||e===4)return e}return a.push({type:`layer-data-too-short`,message:`Could not infer stride for layer '${e.name}', defaulting to 3.`,layerName:e.name}),3}function vp(e,t,n,r){if(!n||!r)return 1;let i=e*4,a=e*3,o=n[a],s=n[a+1],c=n[a+2],l=t[i],u=t[i+1],d=t[i+2],f=r[a],p=r[a+1],m=r[a+2],h=s*d-c*u,g=c*l-o*d,_=o*u-s*l;return h*f+g*p+_*m<0?-1:1}function yp(e,t,n,r,i,a,o,s,c){let l=n.length,u=new Uint32Array(l),d=[],f=new Map,p=a.length;for(let e=0;e<l;e++){let t=String(n[e].controlPointIndex);r&&(t+=`|${r[e*3]},${r[e*3+1]},${r[e*3+2]}`);for(let n=0;n<p;n++){let r=a[n].data;t+=`|${r[e*2]},${r[e*2+1]}`}o&&(t+=`|${o[e*4]},${o[e*4+1]},${o[e*4+2]},${o[e*4+3]}`),s&&(t+=`|${s[e*4]},${s[e*4+1]},${s[e*4+2]},${s[e*4+3]}`);let i=f.get(t);i===void 0&&(i=d.length,f.set(t,i),d.push(e)),u[e]=i}let m=d.length,h=new Float64Array(m*3),g=new Uint32Array(m),_=(e,t,n
8)=>{if(!e)return null;let r=new n(m*t);for(let n=0;n<m;n++){let i=d[n]*t;for(let a=0;a<t;a++)r[n*t+a]=e[i+a]}return r};for(let t=0;t<m;t++){let r=n[d[t]].controlPointIndex;h[t*3]=e[r*3],h[t*3+1]=e[r*3+1],h[t*3+2]=e[r*3+2],g[t]=r}let v=t.length*3,y=new Uint32Array(v);for(let e=0;e<t.length;e++)y[e*3]=u[t[e].vertices[0]],y[e*3+1]=u[t[e].vertices[1]],y[e*3+2]=u[t[e].vertices[2]];let b=a.map(e=>({name:e.name,data:_(e.data,2,Float64Array)}));return{positions:h,indices:y,normals:_(r,3,Float64Array),uvs:b.length>0?b[0].data:_(i,2,Float64Array),uvSets:b,colors:_(o,4,Float32Array),tangents:_(s,4,Float64Array),binormals:_(c,3,Float64Array),controlPointIndices:g}}function bp(e){if(e instanceof Float64Array)return e;if(e instanceof Float32Array||e instanceof Int32Array||e instanceof Uint8Array)return new Float64Array(e);if(Array.isArray(e)){let t=new Float64Array(e.length);for(let n=0;n<e.length;n++)t[n]=Number(e[n]);return t}throw Error(`Cannot convert ${typeof e} to Float64Array`)}function xp(e){if(e instanceof Int32Array)return e;if(e instanceof Float64Array){let t=new Int32Array(e.length);for(let n=0;n<e.length;n++)t[n]=Math.round(e[n]);return t}if(e instanceof Float32Array||e instanceof Uint8Array){let t=new Int32Array(e.length);for(let n=0;n<e.length;n++)t[n]=Math.round(e[n]);return t}if(Array.isArray(e)){let t=new Int32Array(e.length);for(let n=0;n<e.length;n++)t[n]=Math.round(Number(e[n]));return t}throw Error(`Cannot convert ${typeof e} to Int32Array`)}function Sp(e){return Pf(e)??new Float64Array}var Cp=128,wp=4,Tp=16,Ep=64;function Dp(e){return e===`Closed`?`closed`:e===`Periodic`?`periodic`:`open`}function Op(e,t,n){let r={order:e,topology:Dp(t),knots:n,tMin:0,tMax:0,spans:new Float64Array,valid:!1};if(e>1&&e<=Cp){let t=e-1;if(n.length>=2*t+1){r.tMin=n[t],r.tMax=n[n.length-t-1];let e=n.length-2*t,i=[],a=-1/0;for(let r=0;r<e;r++){let e=n[t+r];e!==a&&(i.push(e),a=e)}r.spans=Float64Array.from(i),r.valid=!0;for(let e=1;e<n.length;e++)if(!(n[e-1]<=n[e])){r.valid=!1;break}}}return r}function kp(e,t,n,r){if(t<0||t>=e.length||e.length-t<n)return 0;let i=e[t],a=e[t+n];return i>=a||r<=i?0:r>=a?1:(r-i)/(a-i)}function Ap(e,t,n){if(t<0||t>=e.length||e.length-t<n)return 0;let r=e[t],i=e[t+n];return r>=i?0:n/(i-r)}function jp(e,t,n,r){if(e.order<=1||!e.valid)return-1;let i=e.order-1,a=e.knots,o;if(t<=e.tMin)o=i,t=e.tMin;else if(t>=e.tMax)o=a.length-i-2,t=e.tMax;else{let e=0,n=a.length-1;for(;e<n;){let r=e+n>>1;a[r+1]<=t?e=r+1:n=r}if(!(a[e]<=t&&t<a[e+1]))return-1;o=e}if(o<i)return-1;n[0]=1;for(let e=1;e<=i;e++){let s=0,c=1-kp(a,o-e+1,e,t),l=0,u=r!==null&&e===i;u&&(l=Ap(a,o-e+1,e));for(let i=e;i>0;i--){let d=kp(a,o-e+i,e,t),f=n[i-1];if(n[i]=d*f+c*s,u){let t=Ap(a,o-e+i,e);r[i]=t*f-l*s,l=t}s=f,c=1-d}n[0]=c*s,u&&(r[0]=-l*s)}return o-i}function Mp(e,t,n,r,i){let a=jp(e.basis,t,r,i);if(a<0||e.numControlPoints===0)return!1;let o=e.basis.order,s=0,c=0,l=0,u=0,d=0,f=0,p=0,m=0,h=e.controlPoints;for(let t=0;t<o;t++){let n=(a+t)%e.numControlPoints*4,o=r[t]*h[n+3],g=i[t]*h[n+3];s+=h[n]*o,c+=h[n+1]*o,l+=h[n+2]*o,u+=o,d+=h[n]*g,f+=h[n+1]*g,p+=h[n+2]*g,m+=g}let g=u===0?0:1/u;return n[0]=s*g,n[1]=c*g,n[2]=l*g,n[3]=(d-m*n[0])*g,n[4]=(f-m*n[1])*g,n[5]=(p-m*n[2])*g,!0}function Np(e,t,n,r,i){let a=jp(e.basisU,t,i.wu,i.du),o=jp(e.basisV,n,i.wv,i.dv);if(a<0||o<0||e.numU===0||e.numV===0)return!1;let s=e.basisU.order,c=e.basisV.order,l=e.controlPoints,u=0,d=0,f=0,p=0,m=0,h=0,g=0,_=0,v=0,y=0,b=0,x=0;for(let t=0;t<c;t++){let n=(o+t)%e.numV,r=i.wv[t],c=i.dv[t];for(let t=0;t<s;t++){let o=(a+t)%e.numU,s=i.wu[t],S=i.du[t],C=(n*e.numU+o)*4,w=l[C+3],T=s*r*w,E=S*r*w,D=c*s*w,ee=l[C],te=l[C+1],O=l[C+2];u+=ee*T,d+=te*T,f+=O*T,p+=T,m+=ee*E,h+=te*E,g+=O*E,_+=E,v+=ee*D,y+=te*D,b+=O*D,x+=D}}let S=p===0?0:1/p;return r[0]=u*S,r[1]=d*S,r[2]=f*S,r[3]=(m-_*r[0])*S,r[4]=(h-_*r[1])*S,r[5]=(g-_*r[2])*S,r[6]=(v-x*r[0])*S,r[7]=(y-x*r[1])*S,r[8]=(b-x*r[2])*S,!0}function Pp(e,t=wp){let n=e.basis;if(!n.valid||e.numControlPoints===0||n.spans.length===0)return null;let r=Math.max(1,Math.floor(t)),i=n.spans.length,a=n.topology===`open`,o=i+(i-1)*(r-1),s=o-+!a,c=new Float64Array(o*3),l=new Float64Array(n.order+1),u=new Float64Array(n.order+1),d=new Float64Array(6);for(let t=0;t<i;t++){let a=t+1===i?1:r;for(let i=0;i<a;i++){let a=t*r+i;if(a<s){let o=n.spans[t];if(i>0){let e=i/r;o=o*(1-e)+e*n.spans[t+1]}Mp(e,o,d,l,u)&&(c[a*3]=d[0],c[a*3+1]=d[1],c[a*3+2]=d[2])}else c[a*3]=c[0],c[a*3+1]=c[1],c[a*3+2]=c[2]}}return c}function Fp(e,t){return t!==void 0&&Number.isFinite(t)&&t>0?Math.min(Ep,Math.max(1,Math.floor(t))):e>0?Math.min(Tp,Math.floor(e)):wp}function Ip(e,t,n){let r=e.basisU,i=e.basisV;if(!r.valid||!i.valid||e.numU===0||e.numV===0||r.spans.length<2||i.spans.length<2)return null;let a=r.topology===`open`,o=i.topology===`open`,s=r.spans.length,c=i.spans.length,l=(s-1)*t,u=(c-1)*n,d=s+(s-1)*(t-1),f=d*(c+(c-1)*(n-1)),p=l*u;if(f>1073741823||p>1073741823)return null;let m=new Uint32Array(f),h=new Float64Array(f*3),g=0,_=new Float64Array(f*2),v={wu:new Float64Array(r.order+1),wv:new Float64Array(i.order+1),du:new Float64Array(r.order+1),dv:new Float64Array(i.order+1)},y=new Float64Array(9);for(let l=0;l<c;l++){let u=l+1===c?1:n;for(let f=0;f<u;f++){let p=l*n+f,b=i.spans[l];if(f>0){let e=f/u;b=b*(1-e)+e*i.spans[l+1]}let x=b;l+1===c&&!o&&(b=i.spans[0]);for(let n=0;n<s;n++){let i=n+1===s?1:t;for(let o=0;o<i;o++){let u=n*t+o,S=r.spans[n];if(o>0){let e=o/i;S=S*(1-e)+e*r.spans[n+1]}let C=S;n+1===s&&!a&&(S=r.spans[0]);let w=0,T=0,E=0;Np(e,S,b,y,v)&&(w=y[0],T=y[1],E=y[2]);let D=[];(l===0&&(n>0||o>0)||n===0&&(l>0||f>0))&&D.push(0),l+1===c&&(D.push(u),(n>0||o>0)&&D.push(p*d)),n+1===s&&(D.push(p*d),(l>0||f>0)&&D.push(d-1));let ee=p*d+u,te=g;for(let e of D){if(e>=ee)continue;let t=m[e],n=h[t*3]-w,r=h[t*3+1]-T,i=h[t*3+2]-E;if(n*n+r*r+i*i<1e-7){te=t;break}}m[ee]=te,te===g&&(h[te*3]=w,h[te*3+1]=T,h[te*3+2]=E,g++),_[ee*2]=C,_[ee*2+1]=x}}}}let b=[],x=[0,0,0,0],S=[0,0,0,0];for(let e=0;e<u;e++)for(let t=0;t<l;t++){x[0]=e*d+t,x[1]=e*d+t+1,x[2]=(e+1)*d+t+1,x[3]=(e+1)*d+t;for(let e=0;e<4;e++)S[e]=m[x[e]];let n=4;for(let e=0;e<4;e++){let t=(e+1)%4;if(S[e]===S[t]){for(let e=t;e<3;
8e++)x[e]=x[e+1],S[e]=S[e+1];n=3;break}}b.push(x[0],x[1],x[2]),n===4&&b.push(x[0],x[2],x[3])}let C=new Float64Array(g*3);for(let e=0;e<b.length;e+=3){let t=m[b[e]]*3,n=m[b[e+1]]*3,r=m[b[e+2]]*3,i=h[n]-h[t],a=h[n+1]-h[t+1],o=h[n+2]-h[t+2],s=h[r]-h[t],c=h[r+1]-h[t+1],l=h[r+2]-h[t+2],u=a*l-o*c,d=o*s-i*l,f=i*c-a*s;for(let e of[t,n,r])C[e]+=u,C[e+1]+=d,C[e+2]+=f}let w=e.flipNormals?-1:1;for(let e=0;e<g;e++){let t=C[e*3],n=C[e*3+1],r=C[e*3+2],i=Math.hypot(t,n,r);i>0&&(C[e*3]=t/i*w,C[e*3+1]=n/i*w,C[e*3+2]=r/i*w)}let T=new Float64Array(f*3),E=new Float64Array(f*3);for(let e=0;e<f;e++){let t=m[e]*3;T[e*3]=h[t],T[e*3+1]=h[t+1],T[e*3+2]=h[t+2],E[e*3]=C[t],E[e*3+1]=C[t+1],E[e*3+2]=C[t+2]}return{positions:T,indices:Uint32Array.from(b),normals:E,uvs:_}}function Lp(e,t){let n=J(e,t);if(!n)return null;let r=Pf(n);return r?r instanceof Float64Array?r:Float64Array.from(r):null}function Rp(e){let t=Uf(e).find(e=>e.name===`Color`);return!t||typeof t.values[0]!=`number`||typeof t.values[1]!=`number`||typeof t.values[2]!=`number`?null:[t.values[0],t.values[1],t.values[2]]}function zp(e){let t=J(e,`Order`),n=J(e,`Form`),r=t?Y(t,0)??0:0,i=n?Y(n,0):void 0,a=Lp(e,`Points`),o=Lp(e,`KnotVector`);return!a||!o||a.length%4!=0?null:{basis:Op(r,i,o),controlPoints:a,numControlPoints:a.length/4}}function Bp(e){let t=J(e,`NurbsSurfaceOrder`),n=J(e,`Dimensions`),r=J(e,`Step`),i=J(e,`Form`),a=J(e,`FlipNormals`),o=t?Y(t,0)??0:0,s=t?Y(t,1)??0:0,c=n?Y(n,0)??0:0,l=n?Y(n,1)??0:0,u=r?Y(r,0)??0:0,d=r?Y(r,1)??0:0,f=i?Y(i,0):void 0,p=i?Y(i,1):void 0,m=a?Y(a,0):0,h=Lp(e,`Points`),g=Lp(e,`KnotVectorU`),_=Lp(e,`KnotVectorV`);return!h||!g||!_||h.length%4!=0||h.length/4!==c*l||c<=0||l<=0?null:{basisU:Op(o,f,g),basisV:Op(s,p,_),numU:c,numV:l,controlPoints:h,flipNormals:m===!0||m===1,stepU:typeof u==`number`?u:0,stepV:typeof d==`number`?d:0}}function Vp(e,t,n){let r=X(Y(e,1)??`NurbsSurface`),i=Bp(e),a=[];if(!i)return null;let o=Ip(i,Fp(i.stepU,n),Fp(i.stepV,n));return o?{id:t,name:r,positions:o.positions,indices:o.indices,normals:o.normals,uvs:o.uvs,uvSets:[{name:`map1`,data:o.uvs}],colors:null,tangents:null,binormals:null,controlPointIndices:null,materialIndices:null,diagnostics:a}:(a.push({type:`nurbs-invalid`,message:`NURBS surface '${r}' has an invalid basis and was skipped.`}),{id:t,name:r,positions:new Float64Array,indices:new Uint32Array,normals:null,uvs:null,uvSets:[],colors:null,tangents:null,binormals:null,controlPointIndices:null,materialIndices:null,diagnostics:a})}function Hp(e,t,n=wp){let r=X(Y(e,1)??`NurbsCurve`),i=[],a=zp(e),o=a?Pp(a,n):null;return o||i.push({type:`nurbs-invalid`,message:`NURBS curve '${r}' has an invalid basis and was skipped.`}),{id:t,name:r,kind:`nurbsCurve`,polylines:o?[o]:[],color:Rp(e),diagnostics:i}}function Up(e,t){let n=X(Y(e,1)??`Line`),r=[],i=Lp(e,`Points`),a=J(e,`PointsIndex`),o=a?Pf(a):null,s=[];if(i&&i.length%3==0){let e=i.length/3,t=o?Array.from(o):Array.from({length:e},(e,t)=>t),a=[],c=()=>{a.length>=2?s.push(Float64Array.from(a)):a.length===1&&r.push({type:`degenerate-polygon`,message:`Line '${n}' has a single-point segment that was skipped.`}),a=[]};for(let o=0;o<t.length;o++){let s=t[o],l=s<0;l&&(s=~s),s>=0&&s<e?a.push(i[s*3],i[s*3+1],i[s*3+2]):r.push({type:`layer-index-out-of-bounds`,message:`Line '${n}' references point ${s} outside its ${e} points.`,index:o}),l&&c()}c()}return{id:t,name:n,kind:`line`,polylines:s,color:Rp(e),diagnostics:r}}var Z=e=>({type:`string`,value:e}),Wp=e=>({type:`float64`,value:e}),Gp=e=>({type:`int32`,value:e}),Q=(e,t=[],n=[])=>({name:e,properties:t,children:n});function Kp(e,t,n,...r){return Q(`Property`,[Z(e),Z(t),Z(n),...r.map(e=>typeof e==`string`?Z(e):Wp(e))])}function qp(e,t,n,...r){return Q(`P`,[Z(e),Z(t),Z(``),Z(n),...r.map(e=>typeof e==`string`?Z(e):Wp(e))])}var Jp=(e,t)=>Q(e,[{type:t instanceof Int32Array?`int32[]`:`float64[]`,value:t}]);function Yp(e){return!Mf(e,`Objects`)&&e.nodes.some(e=>e.name===`Model`)}function Xp(e,t=0){let n=e?.properties[t]?.value;
8return typeof n==`number`?n:typeof n==`boolean`?+!!n:void 0}function Zp(e){if(!e)return[];let t=Pf(e);return t?Array.from(t):[]}function Qp(e){let t=e?Pf(e):null;return t?t instanceof Float64Array?t:Float64Array.from(t):null}function $p(e){let t=e?Pf(e):null;return t?t instanceof Int32Array?t:Int32Array.from(t,e=>Math.trunc(e)):null}function em(e,t){if(e)for(let n of e.children){if(n.name!==`Channel`)continue;let e=Y(n,0),r=e===`T`?`t`:e===`R`?`r`:e===`S`?`s`:void 0;if(!r||t[r])continue;let i=[0,0,0],a=!1;for(let e of n.children){if(e.name!==`Channel`)continue;let t=Y(e,0),n=t===`X`?0:t===`Y`?1:t===`Z`?2:-1,r=Xp(J(e,`Default`));n>=0&&r!==void 0&&(i[n]=r,a=!0)}a&&(t[r]=i)}}function tm(e){let t=J(e,`Key`);return t&&t.properties.length>0?!0:e.children.some(e=>e.name===`Channel`&&tm(e))}function nm(e,t){let n=e.usedNames.get(t)??0;return e.usedNames.set(t,n+1),n===0?t:`${t} (${n+1})`}function rm(e,t,n){e.connections.push(Q(`C`,[Z(`OO`),Z(t),Z(n)]))}function im(e){let t=new Float64Array(e.length);for(let n=0;n+2<e.length;n+=3){let r=e[n],i=e[n+1],a=e[n+2],o=Math.hypot(r,i,a);o>0&&(t[n]=r/o,t[n+1]=i/o,t[n+2]=a/o)}return t}function am(e,t){let n=Qp(J(e,`Vertices`)),r=$p(J(e,`PolygonVertexIndex`));if(!n||!r)return[];let i=Math.floor(n.length/3),a=r.length;a>0&&r[a-1]>=0&&(r[a-1]=~r[a-1]);let o=[Q(`GeometryVersion`,[Gp(124)]),Jp(`Vertices`,n),Jp(`PolygonVertexIndex`,r)],s=Qp(J(e,`Normals`));if(s){let e=Math.floor(s.length/3),n=e===i,r=e===a,c=n&&(!r||t===5e3)?`ByVertice`:r?`ByPolygonVertex`:void 0;c&&o.push(Q(`LayerElementNormal`,[Gp(0)],[Q(`Version`,[Gp(101)]),Q(`Name`,[Z(``)]),Q(`MappingInformationType`,[Z(c)]),Q(`ReferenceInformationType`,[Z(`Direct`)]),Jp(`Normals`,im(s))]))}let c=J(e,`GeometryUVInfo`),l=c?Qp(J(c,`TextureUV`)):null;if(c&&l){let e=$p(J(c,`TextureUVVerticeIndex`)),t=Math.floor(l.length/2),n,r=[Q(`Version`,[Gp(101)]),Q(`Name`,[Z(``)])];e&&e.length===a?n=Q(`LayerElementUV`,[Gp(0)],[...r,Q(`MappingInformationType`,[Z(`ByPolygonVertex`)]),Q(`ReferenceInformationType`,[Z(`IndexToDirect`)]),Jp(`UV`,l),Jp(`UVIndex`,e)]):t===a?n=Q(`LayerElementUV`,[Gp(0)],[...r,Q(`MappingInformationType`,[Z(`ByPolygonVertex`)]),Q(`ReferenceInformationType`,[Z(`Direct`)]),Jp(`UV`,l)]):t===i&&(n=Q(`LayerElementUV`,[Gp(0)],[...r,Q(`MappingInformationType`,[Z(`ByVertice`)]),Q(`ReferenceInformationType`,[Z(`Direct`)]),Jp(`UV`,l)])),n&&o.push(n)}let u=Y(J(e,`MaterialAssignation`)??Q(`x`),0),d=$p(J(e,`Materials`));if(d&&d.length>0){let e=u===`ByPolygon`?`ByPolygon`:`AllSame`;o.push(Q(`LayerElementMaterial`,[Gp(0)],[Q(`Version`,[Gp(101)]),Q(`Name`,[Z(``)]),Q(`MappingInformationType`,[Z(e)]),Q(`ReferenceInformationType`,[Z(`IndexToDirect`)]),Jp(`Materials`,e===`AllSame`?Int32Array.of(d[0]):d)]))}for(let t of e.children)t.name===`Shape`&&o.push(t);return o}function om(e,t,n){for(let r of t.children){if(r.name!==`Material`)continue;let t=Y(r,0)??`Material`,i=nm(e,t.includes(`::`)?t:`Material::${t}`),a=(e,t)=>{let n=Zp(J(r,e));return n.length>=3?Kp(t,`ColorRGB`,``,n[0],n[1],n[2]):null},o=(e,t)=>{let n=Xp(J(r,e));return n===void 0?null:Kp(t,`double`,``,n)},s=[a(`Ambient`,`AmbientColor`),a(`Diffuse`,`DiffuseColor`),a(`Specular`,`SpecularColor`),a(`Emissive`,`EmissiveColor`),o(`Shininess`,`Shininess`),o(`Alpha`,`Opacity`),o(`Reflectivity`,`ReflectionFactor`)].filter(e=>e!==null),c=J(r,`ShadingModel`);e.objects.push(Q(`Material`,[Z(i),Z(``)],[Q(`Version`,[Gp(100)]),c??Q(`ShadingModel`,[Z(`phong`)]),Q(`Properties60`,[],s)])),rm(e,i,n)}}function sm(e,t,n){let r=t.children.filter(e=>e.name===`Link`);if(r.length===0)return;let i=nm(e,`Deformer::Skin ${X(n)}`);e.objects.push(Q(`Deformer`,[Z(i),Z(`Skin`)],[Q(`Version`,[Gp(100)]),Q(`Link_DeformAcuracy`,[Wp(50)])])),rm(e,i,n);for(let t of r){let r=Y(t,0)??``,a=nm(e,`SubDeformer::Cluster ${X(n)} ${X(r)}`),o=[Q(`Version`,[Gp(100)]),Q(`Mode`,[Z(`Normalize`)])];for(let e of[`Indexes`,`Weights`,`Transform`,`TransformLink`]){let n=J(t,e);if(!n)continue;let r=e===`Indexes`?$p(n):Qp(n);r&&o.push(Jp(e,r))}e.objects.push(Q(`Deformer`,[Z(a),Z(`Cluster`)],o)),rm(e,a,i),rm(e,r,a)}}function cm(e){let t=[],n=Xp(J(e,`LightType`));n!==void 0&&t.push(Kp(`LightType`,`enum`,``,n));let r=Zp(J(e,`Color`));r.length>=3&&t.push(Kp(`Color`,`ColorRGB`,``,r[0],r[1],r[2]));for(let[n,r]of[[`Intensity`,`Intensity`],[`ConeAngle`,`OuterAngle`],[`HotSpot`,`InnerAngle`]]){let i=Xp(J(e,n));i!==void 0&&t.push(Kp(r,`double`,``,i))}let i=Xp(J(e,`CastShadows`));return i!==void 0&&t.push(Kp(`CastShadows`,`bool`,``,i)),t}function lm(e){let t=[];for(let[n,r]of[[`Aperture`,`FieldOfView`],[`FieldOfViewXProperty`,`FieldOfViewX`],[`FieldOfViewYProperty`,`FieldOfViewY`],[`SqueezeRatio`,`FilmSqueezeRatio`],[`FocalLength`,`FocalLength`],[`AspectType`,`AspectRatioMode`],[`AspectW`,`AspectWidth`],[`AspectH`,`AspectHeight`],[`ApertureMode`,`ApertureMode`],[`NearPlane`,`NearPlane`],[`FarPlane`,`FarPlane`],[`Roll`,`Roll`]]){let i=Xp(J(e,n));i!==void 0&&t.push(Kp(r,r===`AspectRatioMode`||r===`ApertureMode`?`enum`:`double`,``,i))}let n=Zp(J(e,`CameraAperture`));return n.length>=2&&(t.push(Kp(`FilmWidth`,`double`,``,n[0])),t.push(Kp(`FilmHeight`,`double`,``,n[1]))),t}function um(e,t){let n=Y(t,0)??`Model`,r=Y(J(t,`Type`)??Q(`x`),0),i=!!J(t,`Vertices`),a=r===`Light`?`Light`:r===`Camera`?`Camera`:r===`LimbNode`?`LimbNode`:i?`Mesh`:`Null`,o={};em(t.children.find(e=>e.name===`Channel`&&Y(e,0)===`Transform`),o),em(e.takeDefaults.get(n),o);let s=o.t??[0,0,0],c=o.r??[0,0,0],l=o.s??[1,1,1],u=[Kp(`Lcl Translation`,`Lcl Translation`,`A+`,s[0],s[1],s[2]),Kp(`Lcl Rotation`,`Lcl Rotation`,`A+`,c[0],c[1],c[2]),Kp(`Lcl Scaling`,`Lcl Scaling`,`A+`,l[0],l[1],l[2])],d=Xp(J(t.children.find(e=>e.name===`Channel`&&Y(e,0)===`Visibility`)??Q(`x`),`Default`));if(d!==void 0&&d<=0&&u.push(Kp(`Visibility`,`Visibility`,`A+`,0)),a===`Light`)u.push(...cm(t));else if(a===`Camera`)u.push(...lm(t));else if(a===`LimbNode`){let e=Xp(J(J(t,`Properties`)??Q(`x`),`Size`));e!==void 0&&u.push(Kp(`Size`,`double`,``,e))}let f=[Q(`Version`,[Gp(232)]),Q(`Properties60`,[],u)];for(let e of[`Culling`,`Position`,`Up`,`LookAt`]){let n=J(t,e);n&&f.push(n)}a===`Mesh`&&f.push(...am(t,e.version)),e.objects.push(Q(`Model`,[Z(n),Z(a)],f)),om(e,t,n),sm(e,t,n);let p=J(t,`Children`);for(let t of p?.properties??[])typeof t.value==`string`&&rm(e,t.value,n)}function dm(e){let t=Xp(J(Mf(e,`FBXHeaderExtension`)??Q(`x`),`FBXVersion`)),n=Math.max(e.version,t??0),r={version:n,objects:[],connections:[],usedNames:new Map,takeDefaults:new Map},i=Mf(e,`Takes`);for(let e of i?.children??[])if(e.name===`Take`)for(let t of e.children){if(t.name!==`Model`)continue;let e=Y(t,0),n=t.children.find(e=>e.name===`Channel`&&Y(e,0)===`Transform`);e&&n&&!r.takeDefaults.has(e)&&r.takeDefaults.set(e,n)}let a=e.nodes.filter(e=>e.name===`Model`);for(let e of a)um(r,e);let o=[];for(let e of a){let t=e.children.filter(e=>e.name===`Channel`&&tm(e));t.length>0&&o.push(Q(`Model`,[Z(Y(e,0)??``)],t))}let s=i;if(o.length>0){let e=Q(`Take`,[Z(`(internal)`)],o);s=i?Q(`Takes`,i.properties,[...i.children,e]):Q(`Takes`,[],[e])}let c=Mf(e,`Settings`)??J(Mf(e,`Version5`)??Q(`x`),`Settings`),l=(c?J(c,`FrameRate`):void 0)?.properties[0]?.value,u=typeof l==`number`?l:typeof l==`string`?Number.parseFloat(l):NaN,d=[],f=!1;
8if(Number.isFinite(u)&&u>0){let t=Mf(e,`GlobalSettings`);if(t){let e=J(t,`Properties70`),n=e??J(t,`Properties60`)??Q(`Properties60`),r=n.children.some(e=>Y(e,0)===`TimeMode`),i=e?qp:Kp,a=r?[]:[i(`TimeMode`,`enum`,``,14),i(`CustomFrameRate`,`double`,``,u)],o=t.children.filter(e=>e!==n);d.push(Q(`GlobalSettings`,t.properties,[...o,Q(n.name,n.properties,[...n.children,...a])]))}else d.push(Q(`GlobalSettings`,[],[Q(`Version`,[Gp(1e3)]),Q(`Properties60`,[],[Kp(`TimeMode`,`enum`,``,14),Kp(`CustomFrameRate`,`double`,``,u)])]));f=!0}let p=[...e.nodes.filter(e=>e.name!==`Model`&&e.name!==`Takes`&&e.name!==`Settings`&&(e.name!==`GlobalSettings`||!f)),...d,Q(`Objects`,[],r.objects),Q(`Connections`,[],r.connections)];return s&&p.push(s),{...e,version:n,nodes:p}}var fm={Aim:`aim`,"Parent-Child":`parent`,"Position From Positions":`position`,"Rotation From Rotations":`rotation`,"Scale From Scales":`scale`,"Single Chain IK":`singleChainIK`};function pm(e,t){return e&&typeof e[0]==`number`&&typeof e[1]==`number`&&typeof e[2]==`number`?[e[0],e[1],e[2]]:t}function mm(e,t){let n=e?.[0];
8return typeof n==`number`?n:typeof n==`boolean`?+!!n:t}function hm(e){let t=[];for(let[n,r]of Array.from(e.objects))r.name===`Constraint`&&t.push(gm(n,r,e));return t}function gm(e,t,n){let r=t.children.find(e=>e.name===`Type`),i=(r?Y(r,0):void 0)??Y(t,2)??``,a=fm[i]??`unknown`,o=new Map;for(let e of Uf(t))o.set(e.name,e.values);let s=(e,t)=>[mm(o.get(`${e}X`),+!!t)!==0,mm(o.get(`${e}Y`),+!!t)!==0,mm(o.get(`${e}Z`),+!!t)!==0],c={id:e,name:X(Y(t,1)??`Constraint`),type:a,typeName:i,targets:[],weight:mm(o.get(`Weight`),100)/100,active:mm(o.get(`Active`),1)!==0,affectTranslation:[!0,!0,!0],affectRotation:[!0,!0,!0],affectScale:[!1,!1,!1],offsetTranslation:[0,0,0],offsetRotation:[0,0,0],offsetScale:[1,1,1],aimVector:pm(o.get(`AimVector`),[1,0,0]),upVector:pm(o.get(`UpVector`),[0,1,0]),worldUpVector:pm(o.get(`WorldUpVector`),[0,1,0]),worldUpType:mm(o.get(`WorldUpType`),0),ikPoleVector:pm(o.get(`PoleVector`),[0,0,0])};switch(a){case`aim`:c.affectRotation=s(`Affect`,!0),c.offsetRotation=pm(o.get(`RotationOffset`),[0,0,0]);break;case`parent`:c.affectTranslation=s(`AffectTranslation`,!0),c.affectRotation=s(`AffectRotation`,!0),c.affectScale=s(`AffectScale`,!1);break;case`position`:c.affectTranslation=s(`Affect`,!0),c.offsetTranslation=pm(o.get(`Translation`),[0,0,0]);break;case`rotation`:c.affectRotation=s(`Affect`,!0),c.offsetRotation=pm(o.get(`Rotation`),[0,0,0]);break;case`scale`:c.affectScale=s(`Affect`,!0),c.offsetScale=pm(o.get(`Scaling`),[1,1,1])}let l=a===`singleChainIK`?1:100;for(let t of n.connections){if(t.parentId!==e||t.type!==`OP`||!t.propertyName)continue;
8let r=n.objects.get(t.childId);if(!r||r.name!==`Model`)continue;let i=t.propertyName,a=X(Y(r,1)??``);switch(i){case`Constrained Object`:case`Constrained object (Child)`:c.nodeId=t.childId;break;case`Source`:case`Source (Parent)`:case`Aim At Object`:case`Pole Vector Object`:c.targets.push({modelId:t.childId,weight:mm(o.get(`${a}.Weight`),l)/l,offsetTranslation:pm(o.get(`${a}.Offset T`),[0,0,0]),offsetRotation:pm(o.get(`${a}.Offset R`),[0,0,0]),offsetScale:pm(o.get(`${a}.Offset S`),[1,1,1])});break;case`World Up Object`:c.worldUpNodeId=t.childId;break;case`First Joint`:c.ikFirstJointId=t.childId;break;case`End Joint`:c.ikEndJointId=t.childId;break;case`Effector`:c.ikEffectorId=t.childId}}return c}var _m;(function(e){e[e.DefaultW1=1]=`DefaultW1`,e[e.WidenToRgb=2]=`WidenToRgb`,e[e.MultiplyValue=4]=`MultiplyValue`})(_m||={});var vm;(function(e){e[e.None=0]=`None`,e[e.InvertX=1]=`InvertX`,e[e.UnknownShininess=2]=`UnknownShininess`})(vm||={});var ym;(function(e){e[e.Inverted=1]=`Inverted`,e[e.IfExists=2]=`IfExists`,e[e.IfTexture=4]=`IfTexture`,e[e.IfAround1=8]=`IfAround1`})(ym||={});var bm=[[`diffuseColor`,1,0,`Diffuse`],[`diffuseColor`,1,0,`DiffuseColor`],[`diffuseFactor`,0,0,`DiffuseFactor`],[`specularColor`,1,0,`Specular`],[`specularColor`,1,0,`SpecularColor`],[`specularFactor`,0,0,`SpecularFactor`],[`specularExponent`,0,0,`Shininess`],[`specularExponent`,0,0,`ShininessExponent`],[`reflectionColor`,1,0,`Reflection`],[`reflectionColor`,1,0,`ReflectionColor`],[`reflectionFactor`,0,0,`ReflectionFactor`],[`transparencyColor`,1,0,`Transparent`],[`transparencyColor`,1,0,`TransparentColor`],[`transparencyFactor`,0,0,`TransparentFactor`],[`transparencyFactor`,0,0,`TransparencyFactor`],[`emissionColor`,1,0,`Emissive`],[`emissionColor`,1,0,`EmissiveColor`],[`emissionFactor`,0,0,`EmissiveFactor`],[`ambientColor`,1,0,`Ambient`],[`ambientColor`,1,0,`AmbientColor`],[`ambientFactor`,0,0,`AmbientFactor`],[`normalMap`,0,0,`NormalMap`],[`bump`,0,0,`Bump`],[`bumpFactor`,0,0,`BumpFactor`],[`displacement`,0,0,`Displacement`],[`displacementFactor`,0,0,`DisplacementFactor`],[`vectorDisplacement`,0,0,`VectorDisplacement`],[`vectorDisplacementFactor`,0,0,`VectorDisplacementFactor`]],xm=[[`baseColor`,1,0,`Diffuse`],[`baseColor`,1,0,`DiffuseColor`],[`baseFactor`,0,0,`DiffuseFactor`],[`transmissionColor`,1,0,`Transparent`],[`transmissionColor`,1,0,`TransparentColor`],[`transmissionFactor`,0,0,`TransparentFactor`],[`transmissionFactor`,0,0,`TransparencyFactor`],[`emissionColor`,1,0,`Emissive`],[`emissionColor`,1,0,`EmissiveColor`],[`emissionFactor`,0,0,`EmissiveFactor`],[`normalMap`,0,0,`NormalMap`]],Sm=[[`baseColor`,1,0,`Diffuse`],[`baseColor`,1,0,`DiffuseColor`],[`baseFactor`,0,0,`DiffuseFactor`],[`specularColor`,1,0,`Specular`],[`specularColor`,1,0,`SpecularColor`],[`specularFactor`,0,0,`SpecularFactor`],[`roughness`,0,2,`Shininess`],[`roughness`,0,2,`ShininessExponent`],[`transmissionColor`,1,0,`Transparent`],[`transmissionColor`,1,0,`TransparentColor`],[`transmissionFactor`,0,0,`TransparentFactor`],[`transmissionFactor`,0,0,`TransparencyFactor`],[`emissionColor`,1,0,`Emissive`],[`emissionColor`,1,0,`EmissiveColor`],[`emissionFactor`,0,0,`EmissiveFactor`],[`normalMap`,0,0,`NormalMap`]],Cm=[[`baseFactor`,0,0,`base`],[`baseColor`,1,0,`base_color`],[`roughness`,0,0,`specular_roughness`],[`diffuseRoughness`,0,0,`diffuse_roughness`],[`metalness`,0,0,`metalness`],[`specularFactor`,0,0,`specular`],[`specularColor`,1,0,`specular_color`],[`specularIor`,0,0,`specular_IOR`],[`specularAnisotropy`,0,0,`specular_anisotropy`],[`specularRotation`,0,0,`specular_rotation`],[`transmissionFactor`,0,0,`transmission`],[`transmissionColor`,1,0,`transmission_color`],[`transmissionDepth`,0,0,`transmission_depth`],[`transmissionScatter`,2,0,`transmission_scatter`],[`transmissionScatterAnisotropy`,0,0,`transmission_scatter_anisotropy`],[`transmissionDispersion`,0,0,`transmission_dispersion`],[`transmissionExtraRoughness`,0,0,`transmission_extra_roughness`],[`subsurfaceFactor`,0,0,`subsurface`],[`subsurfaceColor`,1,0,`subsurface_color`],[`subsurfaceRadius`,2,0,`subsurface_radius`],[`subsurfaceScale`,0,0,`subsurface_scale`],[`subsurfaceAnisotropy`,0,0,`subsurface_anisotropy`],[`sheenFactor`,0,0,`sheen`],[`sheenColor`,1,0,`sheen_color`],[`sheenRoughness`,0,0,`sheen_roughness`],[`coatFactor`,0,0,`coat`],[`coatColor`,1,0,`coat_color`],[`coatRoughness`,0,0,`coat_roughness`],[`coatIor`,0,0,`coat_IOR`],[`coatAnisotropy`,0,0,`coat_anisotropy`],[`coatRotation`,0,0,`coat_rotation`],[`coatNormal`,0,0,`coat_normal`],[`coatAffectBaseColor`,1,0,`coat_affect_color`],[`coatAffectBaseRoughness`,0,0,`coat_affect_roughness`],[`thinFilmThickness`,0,0,`thin_film_thickness`],[`thinFilmIor`,0,0,`thin_film_IOR`],[`emissionFactor`,0,0,`emission`],[`emissionColor`,1,0,`emission_color`],[`opacity`,2,0,`opacity`],[`normalMap`,0,0,`NormalMap`],[`normalMap`,0,0,`normalCamera`],[`tangentMap`,0,0,`tangent`]],wm=[[`thinWalled`,0,`thin_walled`]],Tm=[[`baseFactor`,0,0,`base`],[`baseColor`,1,0,`baseColor`],[`roughness`,0,0,`specularRoughness`],[`diffuseRoughness`,0,0,`diffuseRoughness`],[`metalness`,0,0,`metalness`],[`specularFactor`,0,0,`specular`],[`specularColor`,1,0,`specularColor`],[`specularIor`,0,0,`specularIOR`],[`specularAnisotropy`,0,0,`specularAnisotropy`],[`specularRotation`,0,0,`specularRotation`],[`transmissionFactor`,0,0,`transmission`],[`transmissionColor`,1,0,`transmissionColor`],[`transmissionDepth`,0,0,`transmissionDepth`],[`transmissionScatter`,2,0,`transmissionScatter`],[`transmissionScatterAnisotropy`,0,0,`transmissionScatterAnisotropy`],[`transmissionDispersion`,0,0,`transmissionDispersion`],[`transmissionExtraRoughness`,0,0,`transmissionExtraRoughness`],[`subsurfaceFactor`,0,0,`subsurface`],[`subsurfaceColor`,1,0,`subsurfaceColor`],[`subsurfaceRadius`,2,0,`subsurfaceRadius`],[`subsurfaceScale`,0,0,`subsurfaceScale`],[`subsurfaceAnisotropy`,0,0,`subsurfaceAnisotropy`],[`sheenFactor`,0,0,`sheen`],[`sheenColor`,1,0,`sheenColor`],[`sheenRoughness`,0,0,`sheenRoughness`],[`coatFactor`,0,0,`coat`],[`coatColor`,1,0,`coatColor`],[`coatRoughness`,0,0,`coatRoughness`],[`coatIor`,0,0,`coatIOR`],[`coatAnisotropy`,0,0,`coatAnisotropy`],[`coatRotation`,0,0,`coatRotation`],[`coatNormal`,0,0,`coatNormal`],[`thinFilmThickness`,0,0,`thinFilmThickness`],[`thinFilmIor`,0,0,`thinFilmIOR`],[`emissionFactor`,0,0,`emission`],[`emissionColor`,1,0,`emissionColor`],[`opacity`,2,0,`opacity`],[`indirectDiffuse`,0,0,`indirectDiffuse`],[`indirectSpecular`,0,0,`indirectSpecular`],[`normalMap`,0,0,`NormalMap`],[`normalMap`,0,0,`normalCamera`],[`tangentMap`,0,0,`tangent`],[`matteColor`,1,0,`aiMatteColor`],[`matteFactor`,0,0,`aiMatteColorA`],[`subsurfaceType`,0,0,`subsurfaceType`],[`transmissionPriority`,0,0,`dielectricPriority`],[`transmissionEnableInAov`,0,0,`transmitAovs`]],Em=[[`matte`,0,`aiEnableMatte`],[`thinWalled`,0,`thinWalled`],[`caustics`,0,`caustics`],[`internalReflections`,0,`internalReflections`],[`exitToBackgroun
8d`,0,`exitToBackground`]],Dm=[[`baseFactor`,0,0,`base_weight`],[`baseColor`,1,0,`base_color`],[`roughness`,0,0,`roughness`],[`diffuseRoughness`,0,0,`diff_rough`],[`diffuseRoughness`,0,0,`diff_roughness`],[`metalness`,0,0,`metalness`],[`specularFactor`,0,0,`reflectivity`],[`specularColor`,1,0,`refl_color`],[`specularAnisotropy`,0,0,`anisotropy`],[`specularRotation`,0,0,`aniso_angle`],[`specularRotation`,0,0,`anisoangle`],[`specularIor`,0,0,`trans_ior`],[`transmissionFactor`,0,0,`transparency`],[`transmissionColor`,1,0,`trans_color`],[`transmissionDepth`,0,0,`trans_depth`],[`transmissionRoughness`,0,0,`trans_rough`],[`transmissionRoughness`,0,0,`trans_roughness`],[`subsurfaceFactor`,0,0,`scattering`],[`subsurfaceTintColor`,1,0,`sss_color`],[`subsurfaceColor`,1,0,`sss_scatter_color`],[`subsurfaceRadius`,2,0,`sss_depth`],[`subsurfaceScale`,0,0,`sss_scale`],[`coatFactor`,0,0,`coat`],[`coatFactor`,0,0,`coating`],[`coatColor`,1,0,`coat_color`],[`coatRoughness`,0,0,`coat_rough`],[`coatRoughness`,0,0,`coat_roughness`],[`coatIor`,0,0,`coat_ior`],[`coatNormal`,0,0,`coat_bump`],[`coatNormal`,0,0,`clearcoat_bump_map_amt`],[`coatAffectBaseColor`,1,0,`coat_affect_color`],[`coatAffectBaseRoughness`,0,0,`coat_affect_roughness`],[`emissionFactor`,0,0,`emission`],[`emissionColor`,1,0,`emit_color`],[`opacity`,2,0,`cutout`],[`normalMap`,0,0,`bump`],[`normalMap`,0,0,`bump_map_amt`],[`displacementMap`,0,0,`displacement`],[`displacementMap`,0,0,`displacement_map_amt`],[`subsurfaceType`,0,0,`subsurfaceType`]],Om=[[`thinWalled`,0,`thin_walled`],[`specular`,0,`material_mode`],[`diffuseRoughness`,0,`material_mode`],[`transmissionRoughness`,1,`trans_roughness_lock`],[`roughnessAsGlossiness`,0,`roughness_inv`],[`transmissionRoughnessAsGlossiness`,0,`trans_roughness_inv`],[`coatRoughnessAsGlossiness`,0,`coat_roughness_inv`]],km=[[`baseColor`,1,0,`main|baseColor`],[`roughness`,0,0,`main|roughness`],[`metalness`,0,0,`main|metalness`],[`normalMap`,0,0,`main|normal`],[`ambientOcclusion`,0,0,`main|ambientOcclusion`],[`emissionColor`,1,0,`main|emission`],[`emissionColor`,1,0,`main|emissionColor`],[`opacity`,2,0,`main|Alpha`],[`coatFactor`,0,0,`extension|clearcoat`],[`coatRoughness`,0,0,`extension|clearcoatRoughness`],[`coatNormal`,0,0,`extension|clearcoatNormal`],[`sheenColor`,1,0,`extension|sheenColor`],[`sheenRoughness`,0,0,`extension|sheenRoughness`],[`specularFactor`,0,0,`extension|specular`],[`specularFactor`,0,0,`extension|Specular`],[`specularColor`,1,0,`extension|specularcolor`],[`specularColor`,1,0,`extension|specularColor`],[`transmissionFactor`,0,0,`extension|transmission`],[`specularIor`,0,0,`extension|indexOfRefraction`]],Am=[[`doubleSided`,0,`main|DoubleSided`],[`sheen`,0,`extension|enableSheen`],[`coat`,0,`extension|enableClearCoat`],[`transmission`,0,`extension|enableTransmission`],[`ior`,0,`extension|enableIndexOfRefraction`],[`specular`,0,`extension|enableSpecular`],[`unlit`,0,`extension|unlit`]],jm=[[`baseFactor`,0,0,`base_weight`],[`baseColor`,1,0,`base_color`],[`roughness`,0,0,`specular_roughness`],[`diffuseRoughness`,0,0,`base_diffuse_roughness`],[`metalness`,0,0,`base_metalness`],[`specularFactor`,0,0,`specular_weight`],[`specularColor`,1,0,`specular_color`],[`specularAnisotropy`,0,0,`specular_roughness_anisotropy`],[`specularIor`,0,0,`specular_ior`],[`transmissionFactor`,0,0,`transmission_weight`],[`transmissionColor`,1,0,`transmission_color`],[`transmissionDepth`,0,0,`transmission_depth`],[`transmissionScatter`,2,0,`transmission_scatter`],[`transmissionScatterAnisotropy`,0,0,`transmission_scatter_anisotropy`],[`transmissionDispersion`,0,0,`transmission_dispersion_scale`],[`subsurfaceFactor`,0,0,`subsurface_weight`],[`subsurfaceColor`,1,0,`subsurface_color`],[`subsurfaceRadius`,2,0,`subsurface_radius_scale`],[`subsurfaceScale`,0,0,`subsurface_radius`],[`subsurfaceAnisotropy`,0,0,`subsurface_scatter_anisotropy`],[`coatFactor`,0,0,`coat_weight`],[`coatColor`,1,0,`coat_color`],[`coatRoughness`,0,0,`coat_roughness`],[`coatAnisotropy`,0,0,`coat_roughness_anisotropy`],[`coatIor`,0,0,`coat_ior`],[`coatNormal`,0,0,`coat_normal_map`],[`sheenFactor`,0,0,`fuzz_weight`],[`sheenColor`,1,0,`fuzz_color`],[`sheenRoughness`,0,0,`fuzz_roughness`],[`emissionFactor`,0,0,`emission_weight`],[`emissionFactor`,4,0,`emission_luminance`],[`emissionColor`,1,0,`emission_color`],[`thinFilmFactor`,0,0,`thin_film_weight`],[`thinFilmThickness`,0,0,`thin_film_thickness`],[`thinFilmIor`,0,0,`thin_film_ior`],[`normalMap`,0,0,`bump`],[`normalMap`,0,0,`bump_map_amt`],[`displacementMap`,0,0,`displacement`],[`displacementMap`,0,0,`displacement_map_amt`],[`coatNormal`,0,0,`coat_bump`],[`coatNormal`,0,0,`coat_bump_map_amt`],[`tangentMap`,0,0,`geometry_tangent_map`],[`opacity`,2,0,`geometry_opacity`]],Mm=[[`thinWalled`,0,`geometry_thin_walled`]],Nm=[[`baseColor`,1,0,`base_color`],[`baseColor`,1,0,`baseColor`],[`roughness`,0,0,`roughness`],[`roughness`,0,0,`Roughness_Map`],[`metalness`,0,0,`metalness`],[`ambientOcclusion`,0,0,`ao`],[`normalMap`,0,0,`norm`],[`emissionColor`,1,0,`emit_color`],[`displacementMap`,0,0,`displacement`],[`displacementMap`,0,0,`displacement_amt`],[`opacity`,2,0,`opacity`]],Pm=[[`baseColor`,1,0,`base_color`],[`baseColor`,1,0,`baseColor`],[`specularColor`,1,0,`Specular`],[`specularColor`,1,0,`specular`],[`roughness`,0,0,`glossiness`],[`ambientOcclusion`,0,0,`ao`],[`normalMap`,0,0,`norm`],[`emissionColor`,1,0,`emit_color`],[`displacementMap`,0,0,`displacement`],[`displacementMap`,0,0,`displacement_amt`],[`opacity`,2,0,`opacity`]],Fm=[[`roughnessAsGlossiness`,8,`useGlossiness`]],Im=[[`baseColor`,1,0,`color`],[`baseColor`,1,0,`base_color`],[`roughness`,0,0,`roughness`],[`metalness`,0,0,`metallic`],[`normalMap`,0,0,`normal`],[`emissionFactor`,0,0,`emissive_intensity`],[`emissionColor`,1,0,`emissive`],[`ambientOcclusion`,0,0,`ao`]],Lm=[`pbr`,`metalness`,`diffuse`,`specular`,`coat`,`sheen`,`transmission`,`opacity`,`ior`,`diffuseRoughness`],Rm={unknown:{maps:Sm,features:[],defaultFeatures:[`diffuse`,`specular`,`emission`,`transmission`]},fbxLambert:{maps:xm,features:[],defaultFeatures:[`diffuse`,`emission`,`transmission`]},fbxPhong:{maps:Sm,features:[],defaultFeatures:[`diffuse`,`specular`,`emission`,`transmission`]},oslStandardSurface:{maps:Cm,features:wm,defaultFeatures:Lm},arnoldStandardSurface:{maps:Tm,features:Em,defaultFeatures:Lm},"3dsMaxPhysicalMaterial":{maps:Dm,features:Om,defaultFeatures:[`pbr`,`metalness`,`diffuse`,`coat`,`sheen`,`transmission`,`opacity`,`ior`],textureSuffix:`_map`,textureEnabledSuffix:`_map_on`},"3dsMaxPbrMetalRough":{maps:Nm,features:Fm,defaultFeatures:[`pbr`,`metalness`,`diffuse`,`opacity`],textureSuffix:`_map`},"3dsMaxPbrSpecGloss":{maps:Pm,features:Fm,defaultFeatures:[`pbr`,`specular`,`diffuse`,`opacity`],textureSuffix:`_map`},gltfMaterial:{maps:km,features:Am,defaultFeatures:[`pbr`,`metalness`,`diffuse`,`emission`,`opacity`,`ambientOcclusion`],textureSuffix:`Map`},openPbrMaterial:{maps:jm,features:Mm,defaultFeatures:Lm,textureSuffix:`_map`,textureEnabledSuffix:`_map_on`},shaderFxGraph:{maps:Im,features:[],defaultFeatures:[`pbr`,`metalness`,`diffuse`,`emission`,`ambientOcclusion`],texturePrefix:`TEX_`,textureSuffix:`_map`,textureEnabledPrefix:`use_`,textureEnabledSuffix:`_map`}};function zm(e){return e!==`unknown`&&e!==`fbxLambert`&&e!==`fbxPhong`}function Bm(e,t){switch(e){case 1:t[0]=1-t[0];break;case 2:t[0]>=0&&(t[0]=1-Math.sqrt(t[0])*.1,t[0]<0&&(t[0]=0))}}function Vm(e){let t=[];
8for(let n of e)if(typeof n==`number`)t.push(n);else if(typeof n==`boolean`)t.push(+!!n);else break;return t}function Hm(e){let t=`unknown`,n=e.shadingModelName.toLowerCase();if(n===`lambert`?t=`fbxLambert`:n===`phong`&&(t=`fbxPhong`),e.shader)switch(e.shader.renderApi){case`ARNOLD_SHADER_ID`:return{shaderType:`arnoldStandardSurface`,shaderPropPrefix:``};case`OSL`:return{shaderType:`oslStandardSurface`,shaderPropPrefix:``};case`SFX_PBS_SHADER`:return{shaderType:`shaderFxGraph`,shaderPropPrefix:``};default:return{shaderType:`unknown`,shaderPropPrefix:``}}if(t===`unknown`){let t=(Vm(e.props.get(`3dsMax|ClassIDa`)?.values??[])[0]??0)>>>0,n=(Vm(e.props.get(`3dsMax|ClassIDb`)?.values??[])[0]??0)>>>0;if(t===1030429932&&n===3735928833)return{shaderType:`3dsMaxPhysicalMaterial`,shaderPropPrefix:`3dsMax|Parameters|`};if(t===4048887347&&n===939201335)return{shaderType:`openPbrMaterial`,shaderPropPrefix:`3dsMax|Parameters|`};if(t===943849874&&n===1174294043)return{shaderType:`gltfMaterial`,shaderPropPrefix:`3dsMax|`};if(t===3490651648&&n===3195528448)return{shaderType:`3dsMaxPbrMetalRough`,shaderPropPrefix:`3dsMax|main|`};if(t===3490651648&&n===31173939)return{shaderType:`3dsMaxPbrSpecGloss`,shaderPropPrefix:`3dsMax|main|`}}return{shaderType:t,shaderPropPrefix:``}}function Um(e){var t;let{shaderType:n,shaderPropPrefix:r}=Hm(e),i=Rm[n],a={shaderType:n,shaderPropPrefix:r,fbx:{},pbr:{},features:{}};for(let e of i.defaultFeatures)a.features[e]={enabled:!0,explicit:!1};let o=t=>{let n=e.shader?.bindings.get(t);return n&&n.length>0?n:[t]},s=e.shader?``:r,c=(t,n,r,i,a,c,l)=>{for(let[u,d,f,p]of t){let t=s+r+p+i;for(let r of o(t)){let t=e.props.get(r),i=n[u]??(n[u]={valueComponents:0,textureEnabled:!1});if(a&&t&&t.type!==`Reference`){let e=Vm(t.values);if(e.length>0){let t=e.slice(0,4);d&4?(t[0]*=i.value?.[0]??1,i.value=[t[0],...i.value?.slice(1)??[]]):i.value=t,Bm(f,i.value);let n=e.length>=4?4:e.length===3?3:e.length===2?2:1;d&1&&n<4&&(i.value[3]=1),d&2&&n===1&&(i.value[1]=i.value[0],i.value[2]=i.value[0]),i.valueComponents=n}}if(c){let t=e.texturesByProp.get(r);t&&(i.texture=t,i.textureEnabled=!0)}if(l&&t){let e=Vm(t.values);e.length>0&&(i.textureEnabled=e[0]!==0)}}}};c(bm,a.fbx,``,``,!0,!0,!1),(i.texturePrefix||i.textureSuffix)&&c(i.maps,a.pbr,i.texturePrefix??``,i.textureSuffix??``,!1,!0,!1),c(i.maps,a.pbr,``,``,!0,!0,!1),(i.textureEnabledPrefix||i.textureEnabledSuffix)&&c(i.maps,a.pbr,i.textureEnabledPrefix??``,i.textureEnabledSuffix??``,!1,!1,!0);for(let[n,r,c]of i.features){let i=s+c;for(let s of o(i)){let i=e.props.get(s),o=(t=a.features)[n]??(t[n]={enabled:!1,explicit:!1});if(i&&i.type!==`Reference`){let e=Vm(i.values);e.length>0&&(o.enabled=e[0]!==0,o.explicit=!0,r&8&&(o.enabled=e[0]>=.5&&e[0]<=1.5),r&1&&(o.enabled=!o.enabled),r&2&&(o.enabled=!0))}r&4&&e.texturesByProp.has(s)&&(o.enabled=!0)}}let l=(e,t,n)=>{let r=e[t]??(e[t]={valueComponents:0,textureEnabled:!1});if(r.value)return;let i=e[n];r.value=[i?.value&&i.value.some(e=>e!==0)?1:0],r.valueComponents=1};l(a.fbx,`diffuseFactor`,`diffuseColor`),l(a.fbx,`specularFactor`,`specularColor`),l(a.fbx,`reflectionFactor`,`reflectionColor`),l(a.fbx,`transparencyFactor`,`transparencyColor`),l(a.fbx,`emissionFactor`,`emissionColor`),l(a.fbx,`ambientFactor`,`ambientColor`),l(a.pbr,`baseFactor`,`baseColor`),l(a.pbr,`specularFactor`,`specularColor`),l(a.pbr,`emissionFactor`,`emissionColor`),l(a.pbr,`sheenFactor`,`sheenColor`),l(a.pbr,`thinFilmFactor`,`thinFilmThickness`),l(a.pbr,`transmissionFactor`,`transmissionColor`),!a.pbr.transmissionRoughness?.value&&a.pbr.roughness?.value&&a.pbr.transmissionExtraRoughness?.value&&(a.pbr.transmissionRoughness={value:[a.pbr.roughness.value[0]+a.pbr.transmissionExtraRoughness.value[0]],valueComponents:1,textureEnabled:!1});for(let[e,t,n]of[[`roughnessAsGlossiness`,`roughness`,`glossiness`],[`coatRoughnessAsGlossiness`,`coatRoughness`,`coatGlossiness`],[`transmissionRoughnessAsGlossiness`,`transmissionRoughness`,`transmissionGlossiness`]]){let r=a.pbr[t];a.features[e]?.enabled?r&&(a.pbr[n]=r,a.pbr[t]=r.value?{value:[1-r.value[0]],valueComponents:1,textureEnabled:!1}:{valueComponents:0,textureEnabled:!1}
8):r?.value&&(a.pbr[n]={value:[1-r.value[0]],valueComponents:1,textureEnabled:!1})}return a}function Wm(e){if(!e?.value)return;let t=e.value;return e.valueComponents===1?[t[0],t[0],t[0]]:[t[0],t[1]??t[0],t[2]??t[0]]}function Gm(e){return e?.value?e.value[0]:void 0}function Km(e,t,n,r){let i=X(Y(e,1)??`Material`),a=Zm(e,r),o=J(e,`ShadingModel`),s=o?Y(o,0)??`Lambert`:Lf(e,a,`ShadingModel`)??`Lambert`,c=s.toLowerCase()===`phong`?`Phong`:`Lambert`,l=Jm(e,a),u=Ym(t,n,r?If(r,`Texture`,`FbxFileTexture`)??If(r,`Texture`):void 0),d=new Map;for(let e of a?.properties.values()??[])d.set(e.name,{type:e.propertyType,values:e.values});for(let t of Uf(e))d.set(t.name,{type:t.type,values:t.values});let f=new Map;for(let e of u)f.has(e.propertyName)||f.set(e.propertyName,e);return{id:t,name:i,type:c,properties:l,textures:u,model:Um({shadingModelName:s,props:d,texturesByProp:f,shader:qm(t,n)}),userProperties:Wf(e)}}function qm(e,t){let n=t.connections.filter(n=>n.type===`OO`&&n.childId===e&&t.objects.get(n.parentId)?.name===`Implementation`).map(e=>({id:e.parentId,node:t.objects.get(e.parentId)}));if(n.length===0)return;let r=n[0],i=Uf(r.node).find(e=>e.name===`RenderAPI`)?.values[0],a=new Map,o=(e,t)=>{let n=a.get(e);n?n.push(t):a.set(e,[t])};for(let e of Zf(t,r.id,`BindingTable`))for(let t of e.node.children){if(t.name!==`Entry`)continue;let e=Y(t,0),n=Y(t,1),r=Y(t,2),i=Y(t,3);typeof e==`string`&&typeof r==`string`&&(n===`FbxPropertyEntry`&&i===`FbxSemanticEntry`?o(r,e):n===`FbxSemanticEntry`&&i===`FbxPropertyEntry`&&o(e,r))}return{renderApi:typeof i==`string`?i:``,bindings:a}}function Jm(e,t){let n={};return n.diffuseColor=Qm(e,t,`DiffuseColor`)??Qm(e,t,`Diffuse`),n.diffuseFactor=$m(e,t,`DiffuseFactor`),n.ambientColor=Qm(e,t,`AmbientColor`)??Qm(e,t,`Ambient`),n.ambientFactor=$m(e,t,`AmbientFactor`),n.specularColor=Qm(e,t,`SpecularColor`)??Qm(e,t,`Specular`),n.specularFactor=$m(e,t,`SpecularFactor`),n.shininess=$m(e,t,`Shininess`)??$m(e,t,`ShininessExponent`),n.emissiveColor=Qm(e,t,`EmissiveColor`)??Qm(e,t,`Emissive`),n.emissiveFactor=$m(e,t,`EmissiveFactor`),n.opacity=$m(e,t,`Opacity`),n.transparencyFactor=$m(e,t,`TransparencyFactor`),n}function Ym(e,t,n){let r=[],i=Zf(t,e,`Texture`);for(let{id:e,node:a,propertyName:o}of i)r.push(Xm(e,a,o,t,n));for(let{id:i,propertyName:a}of Zf(t,e,`LayeredTexture`)){let e=Zf(t,i,`Texture`);if(e.length===0)continue;let o=Xm(e[0].id,e[0].node,a,t,n);o.layeredTextureId=i,r.push(o)}return r}function Xm(e,t,n,r,i){{let a=J(t,`FileName`),o=J(t,`RelativeFilename`),s=a?Y(a,0)??``:``,c=o?Y(o,0)??``:``,l,u,d=$m(t,i,`UVRotation`)??$m(t,i,`Rotation`),f;l=eh(t,i,`UVTranslation`)??eh(t,i,`Translation`),u=eh(t,i,`UVScaling`)??eh(t,i,`Scaling`);let p=Lf(t,i,`UVSet`);p&&p.length>0&&(f=p),l??=nh(t,`ModelUVTranslation`),u??=nh(t,`ModelUVScaling`);let m=$m(t,i,`WrapModeU`),h=$m(t,i,`WrapModeV`),g=null,_=Zf(r,e,`Video`);for(let{node:e}of _){let t=J(e,`Content`);if(t&&t.properties.length>0){let e=t.properties[0].value;e instanceof Uint8Array&&e.length>0?g=e:e instanceof ArrayBuffer&&e.byteLength>0&&(g=new Uint8Array(e))}}return{propertyName:n??`DiffuseColor`,fileName:s,relativeFileName:c,id:e,embeddedData:g,uvTranslation:l,uvScaling:u,uvRotation:d,uvSetName:f,wrapU:m,wrapV:h}}}function Zm(e,t){if(!t)return;let n=J(e,`ShadingModel`),r=n?Y(n,0):void 0;return r?.toLowerCase()===`phong`?If(t,`Material`,`FbxSurfacePhong`)??If(t,`Material`):r?.toLowerCase()===`lambert`?If(t,`Material`,`FbxSurfaceLambert`)??If(t,`Material`):If(t,`Material`)}function Qm(e,t,n){let r=Bf(e,t,n);if(!r||r.length<3)return;let i=th(r[0]),a=th(r[1]),o=th(r[2]);if(i!==void 0&&a!==void 0&&o!==void 0)return[i,a,o]}function $m(e,t,n){return th(Lf(e,t,n))}function eh(e,t,n){let r=Bf(e,t,n);if(!r)return;let i=th(r[0]),a=th(r[1]);return i!==void 0&&a!==void 0?[i,a]:void 0}function th(e){if(typeof e==`number`)return e}function nh(e,t){let n=J(e,t);if(!n)return;let r=th(n.properties[0]?.value),i=th(n.properties[1]?.value);return r!==void 0&&i!==void 0?[r,i]:void 0}var rh=8,ih;function ah(e,t){ih=t?If(t,`Model`,`FbxNode`)??If(t,`Model`):void 0;let n=[];for(let[t,r]of Array.from(e.objects))if(r.name===`Deformer`&&Y(r,2)===`Skin`){let i=oh(t,r,e);i&&n.push(i)}return n}function oh(e,t,n){let r=n.parentOf.get(e);if(!r)return null;let i=r.id,a=n.objects.get(i);if(!a||a.name!==`Geometry`)return null;let o=n.parentOf.get(i),s=(o?n.objects.get(o.id):void 0)?.name===`Model`?o.id:void 0,c=Zf(n,e,`Deformer`);if(c.length===0)return null;let l=new Map;for(let{id:e,node:t}of c){if(Y(t,2)!==`Cluster`)continue;let r=Zf(n,e,`Model`);r.length>0&&l.set(r[0].id,{clusterId:e,clusterNode:t})}let u=ch(i,n),d=[],f=sh(l,u,n,d);if(f.length===0)return null;let{boneIndices:p,boneWeights:m}=_h(f,l,n);
8return{id:e,geometryId:i,meshBindPoseMatrix:s===void 0?null:u.get(s)??null,bones:f,boneIndices:p,boneWeights:m,diagnostics:d}}function sh(e,t,n,r){let i=[],a=new Set,o=uh(e,n),s=dh(o,n),c=lh(o,s),l=Array.from(o).filter(e=>!s.has(e)).map(e=>({modelId:e,parentIndex:-1}));for(;l.length>0;){let{modelId:o,parentIndex:s}=l.shift();if(a.has(o))continue;a.add(o);let u=n.objects.get(o);if(!u)continue;let d=i.length,f=e.get(o),p=mh(u),{bindPoseMatrix:m,transformLinkMatrix:h,transformAssociateModelMatrix:g,clusterMode:_}=f?hh(f.clusterNode):{bindPoseMatrix:null,transformLinkMatrix:null,transformAssociateModelMatrix:null,clusterMode:`Unknown`},v=gh(o,X(Y(u,1)??`Bone${d}`),f!==void 0,_,m,h,g,t.get(o)??null);r.push(...v),i.push({modelId:o,name:X(Y(u,1)??`Bone${d}`),index:d,parentIndex:s,isCluster:f!==void 0,translation:p.translation,rotation:p.rotation,preRotation:p.preRotation,postRotation:p.postRotation,rotationPivot:p.rotationPivot,scalingPivot:p.scalingPivot,rotationOffset:p.rotationOffset,scalingOffset:p.scalingOffset,scale:p.scale,rotationOrder:p.rotationOrder,inheritType:p.inheritType,clusterMode:_,bindPoseMatrix:m,transformLinkMatrix:h,transformAssociateModelMatrix:g,modelBindPoseMatrix:t.get(o)??null,diagnostics:v});for(let e of c.get(o)??[])a.has(e)||l.push({modelId:e,parentIndex:d})}return i}function ch(e,t){let n=t.parentOf.get(e),r=(n?t.objects.get(n.id):void 0)?.name===`Model`?n.id:void 0;if(r===void 0)return new Map;for(let[,e]of Array.from(t.objects)){if(e.name!==`Pose`||Y(e,2)!==`BindPose`)continue;let t=new Map;for(let n of e.children){if(n.name!==`PoseNode`)continue;let e=J(n,`Node`),r=J(n,`Matrix`),i=e?.properties[0]?.value,a=Pf(r);if(typeof i!=`number`)continue;let o=yh(a);o?.length===16&&t.set(i,o)}if(t.has(r))return t}return new Map}function lh(e,t){let n=new Map;for(let r of Array.from(e)){let e=t.get(r);e!==void 0&&(n.has(e)||n.set(e,[]),n.get(e).push(r))}return n}function uh(e,t){let n=new Set(Array.from(e.keys()));for(let r of Array.from(e.keys())){let e=fh(r,t);for(;e!==void 0;){let r=t.objects.get(e);if(!r||r.name!==`Model`)break;n.add(e),e=fh(e,t)}}return n}function dh(e,t){let n=new Map;for(let r of Array.from(e)){let i=fh(r,t);for(;i!==void 0;){if(e.has(i)){n.set(r,i);break}i=fh(i,t)}}return n}function fh(e,t){return t.connections.find(n=>n.type===`OO`&&n.childId===e&&t.objects.get(n.parentId)?.name===`Model`)?.parentId}function ph(e){let t=Y(e,2);return t===`Root`||t===`LimbNode`}function mh(e,t){return Yf(e,t??ih)}function hh(e){let t=null,n=null,r=null,i=`Normalize`,a=J(e,`Transform`);if(a&&a.properties[0]){let e=Pf(a);e instanceof Float64Array&&e.length===16?t=e:e instanceof Float32Array&&e.length===16&&(t=new Float64Array(e))}let o=J(e,`TransformLink`);if(o&&o.properties[0]){let e=Pf(o);e instanceof Float64Array&&e.length===16?n=e:e instanceof Float32Array&&e.length===16&&(n=new Float64Array(e))}let s=J(e,`TransformAssociateModel`);if(s&&s.properties[0]){let e=Pf(s);e instanceof Float64Array&&e.length===16?r=e:e instanceof Float32Array&&e.length===16&&(r=new Float64Array(e))}let c=J(e,`Mode`),l=c?Y(c,0):void 0;return l===`Normalize`||l===`Additive`||l===`TotalOne`?i=l:l&&(i=`Unknown`),{bindPoseMatrix:t,transformLinkMatrix:n,transformAssociateModelMatrix:r,clusterMode:i}}function gh(e,t,n,r,i,a,o,s){if(!n)return[];let c=[];return(r===`Additive`||r===`TotalOne`)&&c.push({type:`cluster-mode-runtime-unsupported`,message:`Cluster mode '${r}' is preserved but not applied by Babylon linear blend skinning.`,boneModelId:e,boneName:t,clusterMode:r}),i||c.push({type:`missing-cluster-transform`,message:`Cluster is missing Transform matrix; falling back to rest/bind-pose data.`,boneModelId:e,boneName:t,clusterMode:r}),a||c.push({type:`missing-cluster-transform-link`,message:`Cluster is missing TransformLink matrix; falling back to model bind pose or rest transform.`,boneModelId:e,boneName:t,clusterMode:r}),s||c.push({type:`missing-bind-pose-matrix`,message:`No BindPose matrix was found for this bone model.`,boneModelId:e,boneName:t,clusterMode:r}),o&&c.push({type:`associate-model-present`,message:`TransformAssociateModel is preserved for future associate-model skinning semantics.`,boneModelId:e,boneName:t,clusterMode:r}),c}function _h(e,t,n){let r=0;for(let n of e){let e=t.get(n.modelId);if(!e)continue;let i=J(e.clusterNode,`Indexes`);if(!i)continue;let a=vh(Pf(i));if(a)for(let e=0;e<a.length;e++)a[e]>r&&(r=a[e])}let i=r+1,a=Array(i),o=Array(i);for(let e=0;e<i;e++)a[e]=[],o[e]=[];for(let n of e){let e=t.get(n.modelId);if(!e)continue;let r=J(e.clusterNode,`Indexes`),i=J(e.clusterNode,`Weights`);if(!r||!i)continue;let s=vh(Pf(r)),c=yh(Pf(i));if(s&&c)for(let e=0;e<s.length;e++){let t=s[e];a[t].push(n.index),o[t].push(c[e])}}for(let e=0;e<i;e++){if(a[e].length===0)continue;let t=a[e].map((t,n)=>({index:t,weight:o[e][n]}));t.sort((e,t)=>
8t.weight-e.weight);let n=t.slice(0,rh);a[e]=n.map(e=>e.index),o[e]=n.map(e=>e.weight)}for(let e=0;e<i;e++){let t=o[e].reduce((e,t)=>e+t,0);if(t>0)for(let n=0;n<o[e].length;n++)o[e][n]/=t}return{boneIndices:a,boneWeights:o}}function vh(e){if(e instanceof Int32Array)return e;if(e instanceof Float64Array){let t=new Int32Array(e.length);for(let n=0;n<e.length;n++)t[n]=Math.round(e[n]);return t}return null}function yh(e){return e instanceof Float64Array?e:e instanceof Float32Array?new Float64Array(e):null}function bh(e,t){if(t.length===0)return[];let n=new Map;for(let r of t){let t=r.bones.filter(e=>e.isCluster).map(e=>e.modelId);if(t.length===0)continue;let i=Ch(t,e),a=n.get(i);a?a.push(r):n.set(i,[r])}return Array.from(n.entries()).sort(([e],[t])=>Nh(e,t)).map(([t,n])=>xh(t,n,e))}function xh(e,t,n){let r=new Set,i=new Set,a=new Map,o=new Map;for(let e of t)for(let t of e.bones){o.has(t.modelId)||o.set(t.modelId,o.size);let e=a.get(t.modelId);if(e||(e=[],a.set(t.modelId,e)),e.push(t),t.isCluster){r.add(t.modelId);for(let e of Th(t.modelId,n))i.add(e)}}let s=Array.from(i);for(;s.length>0;){let e=s.pop();for(let t of n.connections){if(t.type!==`OO`||t.parentId!==e||i.has(t.childId))continue;
8let r=n.objects.get(t.childId);r&&r.name===`Model`&&ph(r)&&(i.add(t.childId),s.push(t.childId))}}let c=Ah(a),l=new Map;for(let[e,t]of Array.from(a))l.set(e,kh(t));let u=Eh(i,n),d=Dh(i,u,o),f=[],p=new Map;for(let e of d){let t=l.get(e)??Mh(e,n);if(!t)continue;let i=u.get(e),a=i===void 0?-1:p.get(i)??-1,o=f.length,s={...t,index:o,parentIndex:a,isCluster:r.has(e)};f.push(s),p.set(e,o)}let m=t.map(t=>Sh(t,`rig_${e.toString()}`,p));return{id:`rig_${e.toString()}`,rootModelIds:f.filter(e=>e.parentIndex<0).map(e=>e.modelId),bones:f,modelIdToBoneIndex:p,clusterModelIds:r,skinBindings:m,warnings:c}}function Sh(e,t,n){let r=e.bones.map(e=>{let r=n.get(e.modelId);if(r===void 0&&e.isCluster)throw Error(`FBX rig resolver: cluster bone ${e.name} is missing from resolved rig ${t}`);return r??-1});return{skinId:e.id,geometryId:e.geometryId,rigId:t,skinBoneIndexToRigBoneIndex:r,clusterModelIds:new Set(e.bones.filter(e=>e.isCluster).map(e=>e.modelId))}}function Ch(e,t){let n=wh(e,t)??e[0],r=Oh(n,t);for(;r!==void 0;){let e=t.objects.get(r);if(!e||e.name!==`Model`||!ph(e))break;n=r,r=Oh(r,t)}return n}function wh(e,t){if(e.length===0)return;let n=e.map(e=>Th(e,t)),r=new Set(n[0]);for(let e of n.slice(1))for(let t of Array.from(r))e.includes(t)||r.delete(t);return n[0].find(e=>r.has(e))}function Th(e,t){let n=[],r=e;for(;r!==void 0;){let e=t.objects.get(r);if(!e||e.name!==`Model`)break;n.push(r),r=Oh(r,t)}return n}function Eh(e,t){let n=new Map;for(let r of Array.from(e)){let i=Oh(r,t);i!==void 0&&e.has(i)&&n.set(r,i)}return n}function Dh(e,t,n){let r=new Map;for(let n of Array.from(e)){let e=t.get(n);if(e===void 0)continue;let i=r.get(e);i||(i=[],r.set(e,i)),i.push(n)}
8for(let e of Array.from(r.values()))e.sort((e,t)=>Ph(e,t,n));let i=Array.from(e).filter(e=>!t.has(e)).sort((e,t)=>Ph(e,t,n)),a=[],o=[...i];for(;o.length>0;){let e=o.shift();a.push(e),o.push(...r.get(e)??[])}return a}function Oh(e,t){return t.connections.find(n=>n.type===`OO`&&n.childId===e&&t.objects.get(n.parentId)?.name===`Model`)?.parentId}function kh(e){return e.find(e=>e.isCluster&&e.transformLinkMatrix)??e.find(e=>e.isCluster)??e.find(e=>e.modelBindPoseMatrix)??e[0]}function Ah(e){let t=[];for(let[n,r]of Array.from(e)){let e=r.filter(e=>e.isCluster&&e.transformLinkMatrix).map(e=>e.transformLinkMatrix);if(e.length<2)continue;let i=e[0];e.some(e=>!jh(i,e,1e-5))&&t.push(`Model ${n.toString()} has differing Cluster.TransformLink matrices across skins`)}return t}function jh(e,t,n){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(Math.abs(e[r]-t[r])>n)return!1;return!0}function Mh(e,t){let n=t.objects.get(e);if(!n||n.name!==`Model`)return null;let r=mh(n);return{modelId:e,name:X(Y(n,1)??`Bone${e.toString()}`),index:-1,parentIndex:-1,isCluster:!1,translation:r.translation,rotation:r.rotation,preRotation:r.preRotation,postRotation:r.postRotation,rotationPivot:r.rotationPivot,scalingPivot:r.scalingPivot,rotationOffset:r.rotationOffset,scalingOffset:r.scalingOffset,scale:r.scale,rotationOrder:r.rotationOrder,inheritType:r.inheritType,clusterMode:`Unknown`,bindPoseMatrix:null,transformLinkMatrix:null,transformAssociateModelMatrix:null,modelBindPoseMatrix:null,diagnostics:[]}}function Nh(e,t){return e<t?-1:+(e>t)}function Ph(e,t,n){return(n.get(e)??2**53-1)-(n.get(t)??2**53-1)||Nh(e,t)}var Fh=46186158e3,Ih=2,Lh=8,Rh=512,zh=1024,Bh=256,Vh=4096,Hh=8192,Uh=16384,Wh=16777216,Gh=33554432,Kh=.333333,qh=1e-5;function Jh(e,t,n){let r=Math.min(e.length,t.length),i=[];if(r===0)return i;let a=0,o=Kh,s=0,c=Number(e[0])/Fh;for(let l=0;l<r;l++){let u=c,d=t[l];l+1<r&&(c=Number(e[l+1])/Fh);let f=l>0?t[l-1]:d,p=l+1<r?t[l+1]:d,m=n(l),h=m.flags,g=m.data[0],_=Kh,v=m.data[1],y=Kh;if(h&50331648){let e=Zh(m.data[2]);h&Wh&&(_=(e&65535)*1e-4),h&Gh&&(y=(e>>>16)*1e-4)}let b,x=`standard`;if(h&Ih)b=`constant`,x=h&Bh?`next`:`standard`,_=y=Kh,g=v=0;else if(h&Lh){if(b=`cubic`,h&Rh){let e=0,t=0,n=!1;l>0&&u>s?e=(d-f)/(u-s):n=!0,l+1<r&&c>u?t=(p-d)/(c-u):n=!0;let i=Qh(m.data[0],m.data[1],m.data[2],e,t,n);a=i.left,g=i.right,v=0,y=Kh}else h&zh||(l>0&&l+1<r&&u>s&&c>u?Math.abs(a+g)<=1e-4?a=g=$h(s,u,c,f,d,p,o,_,g,h):(a=$h(s,u,c,f,d,p,o,_,-a,h),g=$h(s,u,c,f,d,p,o,_,g,h)):a=g=l>0&&u>s?eg(s,u,f,d,-a,h):l+1<r&&c>u?eg(u,c,d,p,g,h):0)}else{b=`linear`,_=Kh,y=Kh;let e=c-u;g=v=e>0?(p-d)/e:0}let S={time:u,value:d,interpolation:b,constantMode:x,leftDx:0,leftDy:0,rightDx:0,rightDy:0};u>s&&(S.leftDx=o*(u-s),S.leftDy=S.leftDx*a),c>u&&(S.rightDx=_*(c-u),S.rightDy=S.rightDx*g),S.rightSlope=g,i.push(S),a=v,o=y,s=u}for(let e=0;e+1<i.length;e++){let t=i[e+1];i[e].nextLeftSlope=t.leftDx>0?t.leftDy/t.leftDx:0}return i}var Yh=new Float32Array(1),Xh=new Uint32Array(Yh.buffer);function Zh(e){return Yh[0]=e,Xh[0]}function Qh(e,t,n,r,i,a){let o=a?1:.5,s=o*(1-e)*(1+n)*(1-t),c=o*(1-e)*(1-n)*(1+t),l=o*(1-e)*(1+n)*(1+t),u=o*(1-e)*(1-n)*(1-t);return{left:s*r+c*i,right:l*r+u*i}}function $h(e,t,n,r,i,a,o,s,c,l){if(l&Vh&&Math.min(Math.abs(r-i),Math.abs(a-i))<=qh)return 0;let u=(a-r)/(n-e);if((l&Hh)===0){let o=(i-r)/(t-e),s=(a-i)/(n-t),l=(t-e)/(n-e);u=u*.5+(o*(1-l)+s*l)*.5;let d=Math.abs(c)/100;if(d>1e-4){let e=c>0?s:o,t=e-u;u=u*(1-d)+e*d;let n=d-5;if(n>0){let e=Math.abs(t)>1e-5?t:c;e=e>0?1:-1,u+=n*n*e*40}}}if(l&Uh){let c=u>=0?1:-1,l=c*u,d=o*(t-e),f=s*(n-t),p=d>0?c*(i-r)/d:0,m=f>0?c*(a-i)/f:0;p>0||(p=0),m>0||(m=0),l=Math.min(l,p,m),u=c*l}return u}function eg(e,t,n,r,i,a){if(a&Uh||a&Vh&&Math.abs(r-n)<=qh)return 0;let o=(r-n)/(t-e);if((a&Hh)===0){let e=Math.abs(i)/100-5;e>0&&(o+=e*e*(i>0?1:-1)*40)}return o}function tg(e,t,n,r,i,a,o,s){let c=[];for(let l=0;l<e.length;l++){let u={time:e[l],value:t[l],interpolation:n[l],constantMode:r[l]?`next`:`standard`,leftDx:0,leftDy:0,rightDx:0,rightDy:0,rightSlope:a[l],nextLeftSlope:l+1<e.length?i[l+1]:void 0};l>0&&e[l]>e[l-1]&&(u.leftDx=(o?.[l]??Kh)*(e[l]-e[l-1]),u.leftDy=u.leftDx*i[l]),l+1<e.length&&e[l+1]>e[l]&&(u.rightDx=(s?.[l]??Kh)*(e[l+1]-e[l]),u.rightDy=u.rightDx*a[l]),c.push(u)}return c}function ng(e,t){let n=typeof e==`string`?e.charCodeAt(0):typeof e==`number`?e:0,r;switch(String.fromCharCode(n)){case`A`:r=`repeatRelative`;break;case`K`:r=`slope`;break;case`M`:r=`mirror`;break;case`R`:r=`repeat`;break;default:r=`constant`}let i=typeof t==`number`?t:-1;return i<0&&(i=-1),{mode:r,repeatCount:i}}function rg(e,t,n){let r=e*3,i=t*3,a=r-i+1,o=i-r-r,s=r,c=3*a,l=2*o,u=n,d;for(let e=0;e<11;e++){let t=u*u;d=t*u*a+o*t+s*u-n;let r=c*t+l*u+s;if(r===0||(u-=d/r,e>=2&&Math.abs(d)<=8881784197001252e-31))break}return u}function ig(e,t){let n=t.time-e.time;if(Number.isFinite(e.rightDx)&&Number.isFinite(e.rightDy)&&Number.isFinite(t.leftDx)&&Number.isFinite(t.leftDy)&&(e.rightDx>0||t.leftDx>0))return{rightDx:e.rightDx,rightDy:e.rightDy,leftDx:t.leftDx,leftDy:t.leftDy};let r=e.rightSlope??0,i=e.nextLeftSlope??(t.leftDx>0?t.leftDy/t.leftDx:r);return{rightDx:n/3,rightDy:n/3*r,leftDx:n/3,leftDy:n/3*i}}function ag(e,t,n,r=!1){if(!e||e.keys.length===0)return n;let i=e.keys;if(i.length===1)return i[0].value;let a=i[0].time,o=i[i.length-1].time;if(!r&&(t<a||t>o))return og(e,t);let s=0,c=i.length;for(;c-s>=8;){let e=s+c>>1;i[e].time<=t?s=e+1:c=e}for(c=i.length;s<c;s++){let e=i[s];if(e.time<=t)continue;if(s===0)return e.value;let n=i[s-1];if(n.time===t)return n.value;let r=1/(e.time-n.time),a=(t-n.time)*r;switch(n.interpolation){case`constant`:return n.constantMode===`next`?e.value:n.value;case`linear`:return n.value*(1-a)+e.value*a;default:{let t=ig(n,e);a=rg(t.rightDx*r,1-t.leftDx*r,a);let i=a*a,o=i*a,s=1-a,c=s*s,l=c*s,u=n.value,d=e.value,f=u+t.rightDy,p=d-t.leftDy;return l*u+3*(c*a*f+s*i*p)+o*d}}}return i[i.length-1].value}function og(e,t){let n=e.keys,r=n[0].time,i=n[n.length-1].time,a=t<r,o=a?n[0]:n[n.length-1],s=(a?e.preExtrapolation:e.postExtrapolation)??{mode:`constant`,repeatCount:-1};if(s.mode===`constant`)return o.value;if(s.mode===`slope`){let e=a?o.rightDx:o.leftDx,n=a?o.rightDy:o.leftDy;return e===0?o.value:o.value+n*((t-o.time)/e)}if(s.repeatCount===0)return o.value;
8let c=Fh,l=Math.round(r*c),u=Math.round(i*c),d=t*c,f=a?l-d:d-u,p=u-l;if(!(p>=1))return o.value;let m=f/p,h=Math.floor(m),g=f-h*p;s.repeatCount>0&&h>=s.repeatCount&&(h=s.repeatCount-1,g=p),s.mode===`mirror`&&h*.5-Math.floor(h*.5)<=.25&&(g=p-g),a&&(g=p-g);let _=ag(e,(l+g)/c,o.value,!0);if(s.mode===`repeatRelative`){let e=n[n.length-1].value-n[0].value;a&&(e=-e),_+=e*(h+1)}return _}var sg=Math.PI/180,cg=180/Math.PI;function lg(e,t){let n=e[0]*(sg*.5),r=e[1]*(sg*.5),i=e[2]*(sg*.5),a=Math.cos(n),o=Math.sin(n),s=Math.cos(r),c=Math.sin(r),l=Math.cos(i),u=Math.sin(i);switch(t){case 1:return[a*c*u+s*l*o,a*l*c+s*o*u,a*s*u-l*o*c,a*s*l-o*c*u];case 2:return[-a*c*u+s*l*o,a*l*c-s*o*u,a*s*u+l*o*c,a*s*l+o*c*u];case 3:return[-a*c*u+s*l*o,a*l*c+s*o*u,a*s*u+l*o*c,a*s*l-o*c*u];case 4:return[a*c*u+s*l*o,a*l*c-s*o*u,a*s*u-l*o*c,a*s*l+o*c*u];case 5:return[a*c*u+s*l*o,a*l*c-s*o*u,a*s*u+l*o*c,a*s*l-o*c*u];default:return[-a*c*u+s*l*o,a*l*c+s*o*u,a*s*u-l*o*c,a*s*l+o*c*u]}}function ug(e,t){let n=.999999999,[r,i,a,o]=e,s=0,c=0,l=0,u,d=Math.PI*.5;switch(t){case 1:u=2*(o*a+r*i),Math.abs(u)<n?(l=Math.asin(u),c=Math.atan2(2*(o*i-r*a),2*(o*o+r*r)-1),s=-Math.atan2(-2*(o*r-i*a),2*(o*o+i*i)-1)):(l=Math.sign(u)*d,c=Math.atan2(2*u*(o*r+i*a),-u*(2*r*i-2*o*a)));break;case 2:u=2*(o*a-r*i),Math.abs(u)<n?(l=Math.asin(u),s=Math.atan2(2*(o*r+i*a),2*(o*o+i*i)-1),c=-Math.atan2(-2*(o*i+r*a),2*(o*o+r*r)-1)):(l=Math.sign(u)*d,s=Math.atan2(-2*u*(o*i-r*a),u*(2*o*a+2*r*i)));break;case 3:u=2*(o*r+i*a),Math.abs(u)<n?(s=Math.asin(u),l=Math.atan2(2*(o*a-r*i),2*(o*o+i*i)-1),c=-Math.atan2(-2*(o*i-r*a),2*(o*o+a*a)-1)):(s=Math.sign(u)*d,l=Math.atan2(2*u*(o*i+r*a),-u*(2*i*a-2*o*r)));break;case 4:u=2*(o*r-i*a),Math.abs(u)<n?(s=Math.asin(u),c=Math.atan2(2*(o*i+r*a),2*(o*o+a*a)-1),l=-Math.atan2(-2*(o*a+r*i),2*(o*o+i*i)-1)):(s=Math.sign(u)*d,c=Math.atan2(-2*u*(o*a-r*i),u*(2*o*r+2*i*a)));break;case 5:u=2*(o*i+r*a),Math.abs(u)<n?(c=Math.asin(u),s=Math.atan2(2*(o*r-i*a),2*(o*o+a*a)-1),l=-Math.atan2(-2*(o*a-r*i),2*(o*o+r*r)-1)):(c=Math.sign(u)*d,s=Math.atan2(2*u*(o*a+r*i),-u*(2*r*a-2*o*i)));break;default:u=2*(o*i-r*a),Math.abs(u)<n?(c=Math.asin(u),l=Math.atan2(2*(o*a+r*i),2*(o*o+r*r)-1),s=-Math.atan2(-2*(o*r+i*a),2*(o*o+a*a)-1)):(c=Math.sign(u)*d,l=Math.atan2(-2*u*(o*r-i*a),u*(2*o*i+2*r*a)))}return[s*cg,c*cg,l*cg]}function dg(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 fg(e,t,n){let r=e[0]*t[0]+e[1]*t[1]+e[2]*t[2]+e[3]*t[3],i=t[0],a=t[1],o=t[2],s=t[3];r<0&&(r=-r,i=-i,a=-a,o=-o,s=-s);let c,l;if(r>.9995)c=1-n,l=n;else{let e=Math.acos(Math.min(1,r)),t=1/Math.sin(e);c=Math.sin((1-n)*e)*t,l=Math.sin(n*e)*t}let u=e[0]*c+i*l,d=e[1]*c+a*l,f=e[2]*c+o*l,p=e[3]*c+s*l,m=Math.hypot(u,d,f,p)||1;return[u/m,d/m,f/m,p/m]}function pg(e,t){return e>=0?e**+t:-((-e)**+t)}function mg(e,t,n,r,i){let a=n.weight;if(n.additive)return n.composeScale&&r===`S`?[e[0]*pg(t[0],a),e[1]*pg(t[1],a),e[2]*pg(t[2],a)]:n.composeRotation&&r===`R`?ug(dg(lg(e,i),fg([0,0,0,1],lg(t,i),a)),i):[e[0]+t[0]*a,e[1]+t[1]*a,e[2]+t[2]*a];if(n.blended){let o=1-a;return n.composeScale&&r===`S`?[pg(e[0],o)*pg(t[0],a),pg(e[1],o)*pg(t[1],a),pg(e[2],o)*pg(t[2],a)]:n.composeRotation&&r===`R`?ug(fg(lg(e,i),lg(t,i),a),i):[e[0]*o+t[0]*a,e[1]*o+t[1]*a,e[2]*o+t[2]*a]}return[t[0],t[1],t[2]]}var hg=4;function gg(e,t,n={}){let r=[],i=n.rebaseKeyframes??!0;for(let[t,n]of Array.from(e.objects))if(n.name===`AnimationStack`){let a=_g(t,n,e,i);a&&r.push(a)}return r.length===0&&t&&r.push(...zg(t,e,i)),r}function _g(e,t,n,r){let i=X(Y(t,1)??`Animation`),a=yg(t),o=Zf(n,e,`AnimationLayer`);if(o.length===0)return null;let s=[],c=[],l=[],u=[],d=1/0,f=-1/0;for(let{id:e,node:t}of o){let r=X(Y(t,1)??`Layer`),i=100,a=0,o=0,p=0;for(let e of Uf(t)){let t=e.values[0];typeof t==`number`&&(e.name===`Weight`?i=t:e.name===`BlendMode`?a=t:e.name===`RotationAccumulationMode`?o=t:e.name===`ScaleAccumulationMode`&&(p=t))}let m=l.length,h=Zf(n,e,`AnimationCurveNode`),g=[],_=[],v=[],y;for(let{id:t,node:i}of h){let a=bg(t,i,n,m);if(!a){let a=xg(t,i,n,m);if(a){if(a.targetId===e&&a.propertyName===`Weight`&&a.curves.length>0){y=a.curves[0];continue}Sg(a.curves,e=>{e<d&&(d=e),e>f&&(f=e)}),_.push(a),c.push(a);let n={type:`unsupported-curve-node`,message:`AnimationCurveNode '${a.type}' is preserved as diagnostic data but not evaluated at runtime.`,layerName:r,curveNodeId:t,curveNodeType:a.type,targetId:a.targetId,propertyName:a.propertyName};v.push(n),u.push(n)}continue}for(let e of a.curves)for(let t of e.keys)t.time<d&&(d=t.time),t.time>f&&(f=t.time);g.push(a),s.push(a)}l.push({name:r,weight:i,normalizedWeight:i/100,blendMode:a,blend:Ag(a,i,o,p),weightCurve:y,curveNodes:g,unsupportedCurveNodes:_,diagnostics:v})}
8return s.length===0&&c.length===0?null:vg(i,l,s,c,u,d,f,a,r)}function vg(e,t,n,r,i,a,o,s,c){let l=isFinite(a)&&isFinite(o),u=c&&l&&a>0?a:0;if(u>0){for(let e of n)for(let t of e.curves)for(let e of t.keys)e.time-=u;for(let e of r)for(let t of e.curves)for(let e of t.keys)e.time-=u;o-=u}let d=s?c?Math.max(s.start-u,0):s.start:0,f=s?Math.max(s.stop-u,d):0,p=f>d,m=l?a-u:0,h=l?o:0,g=p?d:c?Math.min(0,m):m,_=p?f:Math.max(h,g);return{name:e,startTime:g,stopTime:_,duration:Math.max(_-g,0),curveNodes:n,layers:t,unsupportedCurveNodes:r,diagnostics:i}}function yg(e){let t=J(e,`Properties70`);if(!t)return null;let n=0,r=null;for(let e of t.children){if(e.name!==`P`)continue;let t=Y(e,0);t===`LocalStart`||t===`ReferenceStart`?n=Pg(e.properties[4]?.value)??n:(t===`LocalStop`||t===`ReferenceStop`)&&(r=Pg(e.properties[4]?.value)??r)}return r===null?null:{start:n,stop:r}}function bg(e,t,n,r){let i=X(Y(t,1)??``),a=Dg(t),o=`d|X`in a||`d|Y`in a||`d|Z`in a?[a[`d|X`]??0,a[`d|Y`]??0,a[`d|Z`]??0]:void 0;if(i===`T`||i===`R`||i===`S`){let t=Cg(e,n);if(t===null)return null;let a=Eg(e,n);return a.length===0&&!o?null:{type:i,targetModelId:t,curves:a,layerIndex:r,defaultValues:o}}let s=wg(e,n);if(s!==null){let t=Eg(e,n);return t.length===0?null:{type:`DeformPercent`,targetModelId:s,curves:t,layerIndex:r,defaultValues:o}}if(i===`DeformPercent`){let t=Tg(e,n);if(t===null)return null;let i=Eg(e,n);return i.length===0?null:{type:`DeformPercent`,targetModelId:t,curves:i,layerIndex:r,defaultValues:o}}return null}function xg(e,t,n,r){let i=X(Y(t,1)??``),a=Eg(e,n),o=Dg(t);if(a.length===0&&Object.keys(o).length===0)return null;let s=null,c;for(let t of n.connections)if(t.childId===e&&t.type===`OP`){s=t.parentId,c=t.propertyName;break}return{type:i,id:e,layerIndex:r,targetId:s,propertyName:c,curveCount:a.length,curves:a,defaultValues:o}}function Sg(e,t){for(let n of e)for(let e of n.keys)t(e.time)}function Cg(e,t){for(let n of t.connections)if(n.childId===e&&n.type===`OP`){let e=t.objects.get(n.parentId);if(e&&e.name===`Model`)return n.parentId}return null}function wg(e,t){for(let n of t.connections){if(n.childId!==e||n.type!==`OP`||!n.propertyName)continue;let r=t.objects.get(n.parentId);if(r&&r.name===`Geometry`){for(let e of Zf(t,n.parentId,`Deformer`))if(Y(e.node,2)===`BlendShape`){for(let r of Zf(t,e.id,`Deformer`))if(Y(r.node,2)===`BlendShapeChannel`&&X(Y(r.node,1)??``)===n.propertyName)return r.id}}}return null}function Tg(e,t){for(let n of t.connections)if(n.childId===e&&n.type===`OP`){let e=t.objects.get(n.parentId);if(e&&e.name===`Deformer`&&Y(e,2)===`BlendShapeChannel`)return n.parentId}for(let n of t.connections)if(n.childId===e&&n.type===`OO`){let e=t.objects.get(n.parentId);if(e&&e.name===`Deformer`&&Y(e,2)===`BlendShapeChannel`)return n.parentId}return null}function Eg(e,t){let n=[];for(let r of t.connections)if(r.parentId===e&&r.type===`OP`){let e=t.objects.get(r.childId);if(!e||e.name!==`AnimationCurve`)continue;let i=r.propertyName??`d|X`,a=Og(e);a.length>0&&n.push({channel:i,keys:a,...kg(e)})}if(n.length===0){let r=Zf(t,e,`AnimationCurve`),i=[`d|X`,`d|Y`,`d|Z`];for(let e=0;e<r.length&&e<3;e++){let t=Og(r[e].node);t.length>0&&n.push({channel:i[e],keys:t,...kg(r[e].node)})}}return n}function Dg(e){let t={},n=J(e,`Properties70`);for(let e of n?.children??[]){if(e.name!==`P`)continue;let n=Y(e,0);if(!n?.startsWith(`d|`))continue;let r=Fg(e.properties[4]?.value);r!==null&&(t[n]=r)}return t}function Og(e){let t=J(e,`KeyTime`),n=J(e,`KeyValueFloat`);if(!t||!n)return[];let r=Mg(Pf(t)),i=Ig(Pf(n)),a=Ng(Pf(J(e,`KeyAttrFlags`))),o=Ig(Pf(J(e,`KeyAttrDataFloat`))),s=Ng(Pf(J(e,`KeyAttrRefCount`)));if(!r||!i||r.length!==i.length)return[];let c=Lg(r.length,a,s);return Jh(r,i,e=>{let t=c[e],n=t>=0?a?.[t]??0:0,r=t*hg;return{flags:n,data:[Rg(o,r)??0,Rg(o,r+1)??0,Rg(o,r+2)??0,Rg(o,r+3)??0]}})}function kg(e){let t=t=>{let n=J(e,t);return ng(J(n??e,`Type`)?.properties[0]?.value,J(n??e,`Repetition`)?.properties[0]?.value)};return{preExtrapolation:t(`Pre-Extrapolation`),postExtrapolation:t(`Post-Extrapolation`)}}function Ag(e,t,n,r){let i=!1,a=!1;switch(e){case 0:i=!0,a=!0;break;case 2:i=!0}let o=t/100;return o<0&&(o=0),o>.99999&&(o=1),{blended:i,additive:a,composeRotation:n===0,composeScale:r===0,weight:o}}function jg(e,t){return!e||e.keys.length===0?null:ag(e,t,e.keys[0].value)}function Mg(e){return e instanceof Float64Array?e:null}function Ng(e){if(e instanceof Int32Array)return e;if(e instanceof Float32Array||e instanceof Float64Array){let t=new Int32Array(e.length);for(let n=0;n<e.length;n++)t[n]=e[n];return t}return null}function Pg(e){return typeof e==`number`?e/Fh:null}function Fg(e){return typeof e==`number`?e:null}function Ig(e){if(e instanceof Float32Array)return e;if(e instanceof Float64Array){let t=new Float32Array(e.length);for(let n=0;n<e.length;n++)t[n]=e[n];return t}return null}function Lg(e,t,n){if(!t||t.length===0)return Array(e).fill(-1);if(n&&n.length>0){let t=0;for(let e of n)t+=e;if(t===e){let e=[];for(let t=0;t<n.length;t++){let r=n[t];for(let n=0;n<r;n++)e.push(t)}return e}}return t.length===e?Array.from({length:e},(e,t)=>t):t.length===1?Array(e).fill(0):Array.from({length:e},(e,n)=>Math.min(n,t.length-1))}function Rg(e,t){if(!e||t<0||t>=e.length)return;let n=e[t];return Number.isFinite(n)?n:void 0}function zg(e,t,n=!0){let r=Mf(e,`Takes`);if(!r)return[];let i=new Map,a=new Map;for(let e of t.objectEntries)if(e.legacyName!==void 0&&!e.synthetic&&!i.has(e.legacyName)){i.set(e.legacyName,e.id);let t=X(e.legacyName);a.has(t)||a.set(t,e.id)}let o=[],s=-1e6;for(let c of r.children){if(c.name!==`Take`)continue;let r=X(Y(c,0)??`Take`),l=Hg(J(c,`LocalTime`))??Hg(J(c,`ReferenceTime`)),u=[],d=[],f=1/0,p=-1/0,m=e=>{for(let t of e)for(let e of t.keys)e.time<f&&(f=e.time),e.time>p&&(p=e.time)};for(let n of c.children){if(n.name!==`Model`)continue;let r=Y(n,0)??``,o=i.get(r)??a.get(X(r));if(o!==void 0)for(let r of n.children){if(r.name!==`Channel`)continue;let n=Y(r,0)??``;if(n===`Transform`)for(let t of r.children){if(t.name!==`Channel`)continue;let n=Y(t,0);if(n!==`T`&&n!==`R`&&n!==`S`)continue;let r=Ug(t,e.version);r.length>0&&(m(r),u.push({type:n,targetModelId:o,curves:r,layerIndex:0}))}else{let i=Ug(r,e.version);if(i.length>0){m(i);let e=Vg(t,o,n);if(e!==void 0){u.push({type:`DeformPercent`,targetModelId:e,curves:i,layerIndex:0});continue}let r=Bg.has(n)?Zf(t,o,`NodeAttribute`)[0]?.id:void 0;d.push({type:n,id:s--,layerIndex:0,targetId:r??o,propertyName:n,curveCount:i.length,curves:i,defaultValues:{}})}}}}if(u.length===0&&d.length===0)continue;let h={name:`BaseLayer`,weight:100,normalizedWeight:1,blendMode:0,blend:Ag(0,100,0,0),curveNodes:u,unsupportedCurveNodes:d,diagnostics:[]};o.push(vg(r,[h],u,d,[],f,p,l,n))}return o}var Bg=new Set([`Color`,`Intensity`,`OuterAngle`,`InnerAngle`,`ConeAngle`,`HotSpot`,`FieldOfView`,`FieldOfViewX`,`FieldOfViewY`,`FocalLength`,`NearPlane`,`FarPlane`,`OrthoZoom`,`Roll`,`FilmWidth`,`FilmHeight`]);function Vg(e,t,n){let r=n.endsWith(` (Shape)`)?n.slice(0,-8):n;for(let n of Zf(e,t,`Geometry`))for(let t of Zf(e,n.id,`Deformer`))if(Y(t.
8node,2)===`BlendShape`){for(let n of Zf(e,t.id,`Deformer`))if(Y(n.node,2)===`BlendShapeChannel`&&X(Y(n.node,1)??``)===r)return n.id}}function Hg(e){if(!e)return null;let t=Pg(e.properties[0]?.value),n=Pg(e.properties[1]?.value);return t!==null&&n!==null?{start:t,stop:n}:null}function Ug(e,t){let n=e=>e.children.some(e=>e.name===`Key`||e.name===`Default`);if(n(e)){let n=Wg(e,t);return n.length>0?[{channel:`d|X`,keys:n,...kg(e)}]:[]}let r=[];for(let i of e.children){if(i.name!==`Channel`||!n(i))continue;let e=Y(i,0)??`X`,a=Wg(i,t);if(a.length>0&&r.push({channel:`d|${e}`,keys:a,...kg(i)}),r.length===3)break}return r}function Wg(e,t){let n=J(e,`Key`);if(!n)return[];let r=n.properties.map(e=>e.value),i=e=>typeof e==`number`?e:typeof e==`boolean`?+!!e:NaN,a=e=>typeof e==`string`?e:typeof e==`number`?String.fromCharCode(e):typeof e==`boolean`?e?`�`:`\0`:`?`,o=Fg(J(e,`KeyVer`)?.properties[0]?.value)??0;o<=0&&(o=t<5e3?4003:t<6e3?4004:4005);let s=Fg(J(e,`KeyCount`)?.properties[0]?.value)??0,c=[],l=[],u=[],d=[],f=[],p=[],m=[],h=[],g=[],_=0,v=1/3,y=0;for(let e=0;e<s&&!(y+3>r.length);e++){let e=i(r[y])/Fh,t=i(r[y+1]),n=a(r[y+2]);y+=3;let s=0,b=0,x=1/3,S=1/3,C=!1,w=`cubic`,T=!1;if(n===`U`){let e=a(r[y]);y+=1;let t=1;if(e===`s`||e===`b`)s=i(r[y]),b=i(r[y+1]),y+=2,o===4003&&(t=0);else if(e===`a`)C=!0,o<=4004&&(t=0);else if(e===`p`||e===`q`)C=!0,y+=2,t=o<=4004?1:2;else if(e===`t`)C=!0,y+=3,t=0;else if(e===`d`)C=!0,y+=1;else break;for(;t>0;t--){let e=a(r[y]);if(y+=1,e!==`n`&&e!==`c`){if(e===`a`)x=i(r[y]),S=i(r[y+1]),y+=2;else if(e===`l`)S=i(r[y]),y+=1;else if(e===`r`)x=i(r[y]),y+=1;else{y=r.length;break}}}}else if(n===`L`)w=`linear`;else if(n===`C`)w=`constant`,o>=4004&&(T=a(r[y])===`n`,y+=1);else break;c.push(e),l.push(t),u.push(w),d.push(T),f.push(_),p.push(s),m.push(v),h.push(x),g.push(C),_=b,v=S}for(let e=0;e<c.length;e++){if(g[e]){let t=e>0&&e+1<c.length?Gg(c[e-1],c[e],c[e+1],l[e-1],l[e],l[e+1],m[e],h[e]):0;f[e]=t,p[e]=t}if(u[e]===`linear`&&e+1<c.length){let t=c[e+1]-c[e],n=t>0?(l[e+1]-l[e])/t:0;p[e]=n,g[e+1]||(f[e+1]=n)}}return tg(c,l,u,d,f,p,m,h)}function Gg(e,t,n,r,i,a,o,s){if(!(n>e))return 0;let c=(a-r)/(n-e),l=c>=0?1:-1,u=l*c,d=o*(t-e),f=s*(n-t),p=d>0?l*(i-r)/d:0,m=f>0?l*(a-i)/f:0;return p>0||(p=0),m>0||(m=0),u=Math.min(u,p,m),l*u}function Kg(e,t,n,r,i,a){let o=[r[0],r[1],r[2]];for(let r=0;r<Math.max(t.length,1);r++){let s=e.find(e=>e.type===n&&e.layerIndex===r);if(!s)continue;let c=s.defaultValues??o,l=[ag(s.curves.find(e=>e.channel===`d|X`),a,c[0]),ag(s.curves.find(e=>e.channel===`d|Y`),a,c[1]),ag(s.curves.find(e=>e.channel===`d|Z`),a,c[2])],u=t[r];if(r===0||!u)o=l;else{let e=u.blend;if(u.weightCurve&&e.blended){let t=ag(u.weightCurve,a,u.weight)/100;t=t<0?0:t>.99999?1:t,e={...e,weight:t}}o=mg(o,l,e,n,i)}}return o}function qg(e,t,n,r,i){let a=n.map((e,t)=>r[t]??0);for(let r=0;r<Math.max(t.length,1);r++){let o=e.find(e=>e.layerIndex===r);if(!o)continue;let s=n.map((e,t)=>ag(o.curves.find(t=>t.channel===e),i,o.defaultValues?.[e]??a[t])),c=t[r];if(r===0||!c){for(let e=0;e<a.length;e++)a[e]=s[e];continue}let l=c.blend;if(c.weightCurve&&l.blended){let e=ag(c.weightCurve,i,c.weight)/100;e=e<0?0:e>.99999?1:e,l={...l,weight:e}}for(let e=0;e<a.length;e++)a[e]=mg([a[e],0,0],[s[e],0,0],l,`other`,0)[0]}return a}function Jg(e,t,n){let r=!1;for(let i of e)if(i.type===t)for(let e of i.curves){let t=e.keys;if(t.length<2)continue;if(r=!0,n<t[0].time||n>=t[t.length-1].time)return!1;let i=0;for(;i+1<t.length&&t[i+1].time<=n;)i++;if(t[i].interpolation!==`constant`)return!1}return r}function Yg(e){let t=[];for(let[n,r]of Array.from(e.objects))if(r.name===`Deformer`&&Y(r,2)===`BlendShape`){let i=Xg(n,r,e);i&&t.push(i)}return t}function Xg(e,t,n){let r=n.parentOf.get(e);if(!r)return null;let i=n.objects.get(r.id);if(!i||i.name!==`Geometry`)return null;let a=r.id,o=[],s=Zf(n,e,`Deformer`);for(let{id:e,node:t}of s){if(Y(t,2)!==`BlendShapeChannel`)continue;let r=X(Y(t,1)??`MorphTarget`),i=0;for(let e of Uf(t))e.name===`DeformPercent`&&typeof e.values[0]==`number`&&(i=e.values[0]);let a=Zg(t),s=[],c=Zf(n,e,`Geometry`);for(let{node:e}of c){if(Y(e,2)!==`Shape`)continue;let t=e_(e);t&&s.push(t)}if(s.length>0){let t=[],n=Qg(a,s,e,r,t);o.push({name:r,id:e,deformPercent:i,shapes:$g(s,n),fullWeights:n?[...n].sort((e,t)=>
8e-t):null,diagnostics:t})}}return o.length===0?null:{id:e,geometryId:a,channels:o}}function Zg(e){let t=Pf(J(e,`FullWeights`));return t&&(t instanceof Float64Array||t instanceof Float32Array||t instanceof Int32Array)?Array.from(t,e=>Number(e)):null}function Qg(e,t,n,r,i){return e?e.length===t.length?e:(t.length===1||i.push({type:`full-weights-mismatch`,message:`FullWeights length ${e.length} does not match shape count ${t.length}; using the first shape for compatibility.`,channelId:n,channelName:r}),null):(t.length>1&&i.push({type:`missing-full-weights`,message:`Blend shape channel has multiple shapes but no FullWeights; using the first shape for compatibility.`,channelId:n,channelName:r}),null)}function $g(e,t){return!t||t.length!==e.length?e.length>1?[e[0]]:e:e.map((e,n)=>({shape:e,weight:t[n]})).sort((e,t)=>e.weight-t.weight).map(e=>e.shape)}function e_(e){let t=J(e,`Indexes`),n=J(e,`Vertices`);if(!t||!n)return null;let r=Pf(t),i=Pf(n);if(!r||!i)return null;let a=t_(r);if(!a)return null;let o;if(i instanceof Float64Array)o=i;else if(i instanceof Float32Array)o=new Float64Array(i);else return null;let s=null,c=J(e,`Normals`);if(c){let e=Pf(c);e instanceof Float64Array?s=e:e instanceof Float32Array&&(s=new Float64Array(e))}return{indices:a,vertices:o,normals:s}}function t_(e){if(e instanceof Uint32Array)return e;if(e instanceof Int32Array||e instanceof Float32Array||e instanceof Float64Array){let t=new Uint32Array(e.length);for(let n=0;n<e.length;n++)t[n]=e[n];return t}return null}var n_=new Set([`Character`,`CharacterPose`,`ControlSet`,`ControlSetPlug`]),r_=new Set([`Camera`,`Light`,`Null`,`LodGroup`,`LimbNode`,`Limb`,`Root`,`Skeleton`,`Marker`,`CameraSwitcher`,`Mesh`,`NurbsCurve`,`NurbsSurface`,`TrimNurbsSurface`,`Line`,`Boundary`]);function i_(e){let t=e.diagnostics.map(t=>({type:`connection-graph`,message:t.message,objectId:t.childId,subType:t.reason,parentCount:t.childId===void 0?void 0:e.connections.filter(e=>e.childId===t.childId).length}));for(let[n,r]of Array.from(e.objects)){let i=Y(r,2)??``;if(r.name===`Constraint`){let a=r.children.find(e=>e.name===`Type`),o=(a?Y(a,0):void 0)??i;new Set([`Aim`,`Parent-Child`,`Position From Positions`,`Rotation From Rotations`,`Scale From Scales`]).has(o)||t.push(o_(e,n,r,`unsupported-constraint`,`Constraint '${o||X(Y(r,1)??``)}' is preserved as metadata but not evaluated at runtime.`));continue}if(n_.has(r.name)){t.push(o_(e,n,r,`unsupported-helper`,`${r.name} helper data is preserved as diagnostic data but not evaluated at runtime.`));continue}if(r.name===`LayeredTexture`){t.push(o_(e,n,r,`unsupported-layered-texture`,`LayeredTexture is preserved as diagnostic data; runtime texture layer blending is not implemented.`));continue}if(r.name===`Pose`&&i!==`BindPose`){t.push(o_(e,n,r,`unsupported-pose`,`Pose subtype '${i}' is preserved as diagnostic data but not evaluated at runtime.`));continue}if(r.name===`Deformer`&&!a_(i)){t.push(o_(e,n,r,`unsupported-deformer`,`Deformer subtype '${i}' is preserved as diagnostic data but not evaluated at runtime.`));continue}r.name===`NodeAttribute`&&i&&!r_.has(i)&&t.push(o_(e,n,r,`unsupported-node-attribute`,`NodeAttribute subtype '${i}' is preserved as diagnostic data but not converted to a Babylon object.`))}return t}function a_(e){return e===`Skin`||e===`Cluster`||e===`BlendShape`||e===`BlendShapeChannel`}function o_(e,t,n,r,i){return{type:r,message:i,objectId:t,objectName:X(Y(n,1)??n.name),nodeName:n.name,subType:Y(n,2)??``,parentCount:e.connections.filter(e=>e.childId===t).length,childCount:e.childrenOf.get(t)?.length??0}}function s_(e,t,n){let r=Zf(e,t,`Deformer`).map(e=>Y(e.node,2)??``).filter(e=>e===`Skin`||e===`BlendShape`);r.length!==0&&n.diagnostics.push({type:`nurbs-deformer-ignored`,message:`${Array.from(new Set(r)).join(` and `)} deformer on NURBS surface '${n.name}' is ignored: the tessellated mesh has no control point mapping.`})}function c_(e,t={}){Yp(e)&&(e=dm(e));let n=Xf(e),r=Ff(e),i=g_(e),a=[];for(let[e,t]of Array.from(n.objects))t.name===`Material`&&a.push(Km(t,e,n,r));l_(n,a,r);let o=[],s=[];for(let[e,r]of Array.from(n.objects))if(r.name===`Geometry`){let i=Y(r,2);if(i===`Mesh`){let t=rp(r,e);t.positions.length>0&&t.indices.length>0&&o.push(t)}else if(i===`NurbsSurface`){let i=Vp(r,e,t.nurbsSubdivision);i&&(s_(n,e,i),o.push(i))}else if(i===`TrimNurbsSurface`){let r=Zf(n,e,`Geometry`).find(e=>Y(e.node,2)===`NurbsSurface`),i=r?Vp(r.node,e,t.nurbsSubdivision):null;i&&(s_(n,e,i),i.diagnostics.push({type:`nurbs-trim-ignored`,message:`Trim curves of NURBS surface '${i.name}' are ignored; the surface is rendered untrimmed.`}),o.push(i))}else i===`NurbsCurve`?s.push(Hp(r,e)):i===`Line`&&s.push(Up(r,e))}let c=ah(n,r),l=bh(n,c),u=Yg(n),d=gg(n,e,{rebaseKeyframes:t.rebaseKeyframes??!0}),f=x_(n,r),p=S_(n,r),m=i_(n),h=hm(n),g=d_(n,o,s,a,r),{displayLayers:_,selectionSets:v}=p_(n,g);return{rootModels:g,displayLayers:_,selectionSets:v,constraints:h,geometries:o,curves:s,materials:a,skins:c,rigs:l,blendShapes:u,animations:d,cameras:f,lights:p,diagnostics:m,...i}}function l_(e,t,n){let r=new Map(t.map(e=>[e.id,e])),i=If(n,`Texture`,`FbxFileTexture`)??If(n,`Texture`);for(let[t,n]of Array.from(e.objects)){if(n.name!==`Model`)continue;let a=Zf(e,t,`Texture`);if(a.length===0)continue;let o=Zf(e,t,`Material`).filter(e=>!e.propertyName).map(e=>r.get(e.id)).filter(e=>e!==void 0);if(o.length===0)continue;let s=Zf(e,t,`Geometry`)[0]?.node??n,c=J(s,`LayerElementMaterial`),l=c?Pf(J(c,`Materials`)):null,u=e=>{switch(e.replace(/^LayerElement/,``).replace(/Textures?$/,``)){case``:case`Diffuse`:return{prop:`DiffuseColor`,fbx:`diffuseColor`,pbr:`baseColor`};case`Emissive`:return{prop:`EmissiveColor`,fbx:`emissionColor`,pbr:`emissionColor`};case`Specular`:return{prop:`SpecularColor`,fbx:`specularColor`,pbr:`specularColor`};case`Ambient`:return{prop:`AmbientColor`,fbx:`ambientColor`,pbr:`ambientOcclusion`};case`Bump`:case`NormalMap`:return{prop:`NormalMap`,fbx:`normalMap`,pbr:`normalMap`};case`Transparent`:return{prop:`TransparentColor`,fbx:`transparencyColor`,pbr:`opacity`};case`Reflection`:return{prop:`ReflectionColor`,fbx:`reflectionColor`,pbr:`specularColor`};case`Shininess`:return{prop:`ShininessExponent`,fbx:`specularExponent`,pbr:`roughness`};case`Displacement`:return{prop:`DisplacementColor`,fbx:`displacement`,pbr:`displacementMap`};default:return null}},d=s.children.filter(e=>/^LayerElement\w*Textures?$/.test(e.name)),f=a.map(({id:t,node:n})=>Xm(t,n,void 0,e,i)),p=(e,t,n)=>{var r,i,a,s;let c=o[e],l=f[t];if(!c||!l||c.textures.some(e=>e.propertyName===n.prop))return;let u={...l,propertyName:n.prop};c.textures.push(u);let d=(r=c.model.fbx)[i=n.fbx]??(r[i]={valueComponents:0,textureEnabled:!1});d.texture=u,d.textureEnabled=!0;let p=(a=c.model.pbr)[s=n.pbr]??(a[s]={valueComponents:0,textureEnabled:!1});p.texture=u,p.textureEnabled=!0};if(d.length===0){o.length===1&&f.length===1&&p(0,0,u(`LayerElementTexture`));continue}for(let e of d){let t=u(e.name),n=Pf(J(e,`TextureId`));if(!t||!n||n.length===0)continue;let r=Math.max(n.length,l?.length??0);for(let e=0;e<r;e++){let r=n[Math.min(e,n.length-1)],i=l&&l.length>0?l[Math.min(e,l.length-1)]:0;r>=0&&p(i,r,t)}}}}var u_=512;function d_(e,t,n,r,i){let a=new Map;for(let e of t)a.set(e.id,e);let o=new Map;for(let e of n)o.set(e.id,e);let s=new Map;for(let e of r)s.set(e.id,e);let c=e.childrenOf.get(0)??[],l=[],u=new Set,d=new Set;for(let{id:t}of c){let n=e.objects.get(t);n&&n.name===`Model`&&!u.has(t)&&(u.add(t),l.push(f_(t,n,e,a,o,s,i,d)))}let f=new Set;for(let t of e.connections){if(t.type!==`OO`)continue;let n=e.objects.get(t.parentId);
8(t.parentId===0||n?.name===`Model`)&&f.add(t.childId)}for(let[t,n]of Array.from(e.objects))n.name===`Model`&&!f.has(t)&&!u.has(t)&&(u.add(t),l.push(f_(t,n,e,a,o,s,i,d)));return l}function f_(e,t,n,r,i,a,o,s){let c=X(Y(t,1)??`Model`);s.add(e);let l=Y(t,2)??`Null`,u=Zf(n,e,`Geometry`),d=u.map(e=>r.get(e.id)).find(e=>e!==void 0),f=u.map(e=>i.get(e.id)).find(e=>e!==void 0),p=Zf(n,e,`Material`),m=[];for(let{id:e}of p){let t=a.get(e);t&&m.push(t)}let h=m_(t,If(o,`Model`,`FbxNode`)??If(o,`Model`)),g=Zf(n,e,`Model`).filter(e=>!e.propertyName),_=[],v=[];for(let{id:e,node:t}of g){if(s.size>u_){v.push(`Model hierarchy deeper than ${u_} levels; deeper children were skipped.`);break}if(s.has(e)){v.push(`Model connection cycle detected at '${X(Y(t,1)??``)}'; the recursive child was skipped.`);continue}_.push(f_(e,t,n,r,i,a,o,s))}s.delete(e);let y=t.children.find(e=>e.name===`Culling`),b=y?Y(y,0)===`CullingOff`:!1,x=v_(t),S;if(l===`LodGroup`){let t=Zf(n,e,`NodeAttribute`).find(e=>Y(e.node,2)===`LodGroup`),r=t?Uf(t.node):[],i=[],a=[];for(let e=0;;e++){let t=r.find(t=>t.name===`Thresholds|Level${e}`);if(!t)break;i.push(typeof t.values[0]==`number`?t.values[0]:0)}for(let e=0;;e++){let t=r.find(t=>t.name===`DisplayLevels|Level${e}`);if(!t)break;a.push(typeof t.values[0]==`number`?t.values[0]:0)}let o=r.find(e=>e.name===`ThresholdsUsedAsPercentage`);S={thresholds:i,relative:!!o&&o.values[0]!==0&&o.values[0]!==!1,displayLevels:a}}return{id:e,name:c,subType:l,geometry:d,materials:m,children:_,cullingOff:b,customProperties:x,lodGroup:S,curve:f,...h,diagnostics:[...h.diagnostics,...v]}}function p_(e,t){let n=new Map,r=e=>{for(let t of e)n.set(t.id,t),r(t.children)};r(t);let i=[],a=[];for(let[t,r]of Array.from(e.objects))if(r.name===`CollectionExclusive`){let a=Uf(r),o=(e,t)=>{let n=a.find(t=>t.name===e)?.values[0];
8return typeof n==`number`?n:typeof n==`boolean`?+!!n:t},s=a.find(e=>e.name===`Color`)?.values,c=s&&typeof s[0]==`number`&&typeof s[1]==`number`&&typeof s[2]==`number`?[s[0],s[1],s[2]]:[.8,.8,.8],l={id:t,name:X(Y(r,1)??`DisplayLayer`),show:o(`Show`,1)!==0,freeze:o(`Freeze`,0)!==0,color:c,modelIds:Zf(e,t,`Model`).map(e=>e.id)};i.push(l);for(let e of l.modelIds){let t=n.get(e);t&&(t.displayLayer=l)}}else if(r.name===`SelectionSet`||r.name===`Collection`&&Y(r,2)===`SelectionSet`){let n=[];for(let r of Zf(e,t))if(r.node.name===`Model`)n.push({modelId:r.id,includeNode:!0});else if(r.node.name===`SelectionNode`){let t=e=>{let t=J(r.node,e);if(t)return Array.from(Pf(t))},i=J(r.node,`IsTheNodeInSet`)?.properties[0]?.value;for(let a of Zf(e,r.id,`Model`))n.push({modelId:a.id,includeNode:i===void 0||i===1||i===!0,vertices:t(`VertexIndexArray`),edges:t(`EdgeIndexArray`),faces:t(`PolygonIndexArray`)})}a.push({id:t,name:X(Y(r,1)??`SelectionSet`),members:n})}return{displayLayers:i,selectionSets:a}}function m_(e,t){return Yf(e,t)}var h_=[30,120,100,60,50,48,30,30,29.97,29.97,25,24,1e3,23.976,24,96,72,59.94];function g_(e){let t={upAxis:1,upAxisSign:1,frontAxis:2,frontAxisSign:1,coordAxis:0,coordAxisSign:1,unitScaleFactor:1,frameRate:30},n=Mf(e,`GlobalSettings`);if(!n)return t;let r=0,i=24;for(let{name:e,values:a}of Uf(n)){let n=C_(a[0]);if(e&&n!==void 0)switch(e){case`UpAxis`:t.upAxis=n;break;case`UpAxisSign`:t.upAxisSign=n;break;case`FrontAxis`:t.frontAxis=n;break;case`FrontAxisSign`:t.frontAxisSign=n;break;case`CoordAxis`:t.coordAxis=n;break;case`CoordAxisSign`:t.coordAxisSign=n;break;case`UnitScaleFactor`:t.unitScaleFactor=n;break;case`TimeMode`:r=n;break;case`CustomFrameRate`:i=n}}return t.frameRate=r===14?i>0?i:24:h_[r]??30,t}var __=new Set([`Lcl Translation`,`Lcl Rotation`,`Lcl Scaling`,`PreRotation`,`PostRotation`,`RotationPivot`,`ScalingPivot`,`RotationOffset`,`ScalingOffset`,`RotationOrder`,`GeometricTranslation`,`GeometricRotation`,`GeometricScaling`,`Visibility`,`InheritType`,`ScalingMax`,`DefaultAttributeIndex`,`currentUVSet`,`lockInfluenceWeights`]);function v_(e){let t=Wf(e);if(!t)return;let n=!1,r={};for(let e of Object.keys(t))__.has(e)||(r[e]=t[e],n=!0);return n?r:void 0}var y_=new Set([`FieldOfView`,`FieldOfViewX`,`FieldOfViewY`,`NearPlane`,`FarPlane`,`AspectWidth`,`AspectHeight`,`FilmAspectRatio`,`FocalLength`,`FilmWidth`,`FilmHeight`,`ApertureWidth`,`ApertureHeight`,`CameraProjectionType`,`ProjectionType`,`OrthoZoom`,`Roll`,`ApertureMode`]),b_=new Set([`LightType`,`Color`,`Intensity`,`InnerAngle`,`OuterAngle`,`ConeAngle`,`DecayType`,`DecayStart`,`EnableNearAttenuation`,`EnableFarAttenuation`,`CastShadow`,`Shadow`]);function x_(e,t){let n=[],r=If(t,`NodeAttribute`,`FbxCamera`)??If(t,`NodeAttribute`);for(let[t,i]of Array.from(e.objects)){if(i.name!==`NodeAttribute`||Y(i,2)!==`Camera`)continue;let a=e.parentOf.get(t);if(!a)continue;let o=e.objects.get(a.id);if(!o||o.name!==`Model`)continue;let s=X(Y(o,1)??`Camera`),c=Rf(i,r,`NearPlane`,.1),l=Rf(i,r,`FarPlane`,1e4),u=Rf(i,r,`CameraProjectionType`,0)===1||Rf(i,r,`ProjectionType`,0)===1?`orthographic`:`perspective`,d=C_(Lf(i,r,`FocalLength`)),f=C_(Lf(i,r,`FilmWidth`))??C_(Lf(i,r,`ApertureWidth`)),p=C_(Lf(i,r,`FilmHeight`))??C_(Lf(i,r,`ApertureHeight`)),m=C_(Lf(i,r,`OrthoZoom`)),h=C_(Lf(i,r,`Roll`)),g=E_(i,r),_=g.aspectRatio,v=g.fovDegY,y=[];u===`orthographic`&&m===void 0&&y.push(`Orthographic camera has no OrthoZoom; runtime orthographic bounds use a fallback.`),d!==void 0&&p===void 0&&Lf(i,r,`FieldOfView`)===void 0&&y.push(`FocalLength is present without FilmHeight; default field of view fallback may be used.`),n.push({modelId:a.id,attributeId:t,userProperties:Wf(i),name:s,fieldOfView:v,fieldOfViewX:g.fovDegX,apertureMode:g.apertureMode,apertureSizeInch:g.apertureSizeInch,orthographicSize:g.orthographicSize,nearPlane:c,farPlane:l,aspectRatio:_,projectionType:u,focalLength:d,filmWidth:f,filmHeight:p,orthoZoom:m,roll:h,unknownProperties:D_(i,y_),diagnostics:y})}return n}function S_(e,t){let n=[],r=If(t,`NodeAttribute`,`FbxLight`)??If(t,`NodeAttribute`);for(let[t,i]of Array.from(e.objects)){if(i.name!==`NodeAttribute`||Y(i,2)!==`Light`)continue;let a=e.parentOf.get(t);if(!a)continue;let o=e.objects.get(a.id);if(!o||o.name!==`Model`)continue;let s=X(Y(o,1)??`Light`),c=Rf(i,r,`LightType`,0),l=zf(i,r,`Color`,[1,1,1]),u=Rf(i,r,`Intensity`,100)/100,d=C_(Lf(i,r,`OuterAngle`))??C_(Lf(i,r,`ConeAngle`)),f=C_(Lf(i,r,`InnerAngle`)),p=d??45,m=Rf(i,r,`DecayType`,2),h=C_(Lf(i,r,`DecayStart`)),g=w_(Lf(i,r,`EnableNearAttenuation`)),_=w_(Lf(i,r,`EnableFarAttenuation`)),v=w_(Lf(i,r,`CastShadow`))??w_(Lf(o,void 0,`CastShadow`))??w_(Lf(o,void 0,`Shadow`)),y=[];m!==2&&y.push(`DecayType ${m} is preserved as metadata; Babylon falloff is not remapped in this pass.`),h!==void 0&&y.push(`DecayStart is preserved as metadata and is not mapped to Babylon light range.`),n.push({modelId:a.id,attributeId:t,userProperties:Wf(i),nearAttenuationStart:C_(Lf(i,r,`NearAttenuationStart`)),nearAttenuationEnd:C_(Lf(i,r,`NearAttenuationEnd`)),farAttenuationStart:C_(Lf(i,r,`FarAttenuationStart`)),farAttenuationEnd:C_(Lf(i,r,`FarAttenuationEnd`)),areaLightShape:C_(Lf(i,r,`AreaLightShape`)),name:s,lightType:c,color:l,intensity:u,coneAngle:p,decayType:m,innerAngle:f,outerAngle:d,decayStart:h,enableNearAttenuation:g,enableFarAttenuation:_,castShadows:v,unknownProperties:D_(i,b_),diagnostics:y})}return n}function C_(e){if(typeof e==`number`)return e}function w_(e){if(typeof e==`boolean`)return e;if(typeof e==`number`)return e!==0}var T_=[[1e3,1e3],[404,295],[493,292],[864,630],[816,612],[980,735],[825,446],[864,732],[2066,906],[1485,991],[2080,1480],[2772,2072]];function E_(e,t){let n=(n,r)=>C_(Lf(e,t,n))??r,r=n(`AspectRatioMode`,0),i=n(`ApertureMode`,2),a=Math.max(0,Math.min(T_.length-1,Math.round(n(`ApertureFormat`,0)))),o=n(`GateFit`,0),s=n(`AspectW`,0),c=n(`AspectH`,0);s=n(`AspectWidth`,s),c=n(`AspectHeight`,c);let l=n(`FieldOfView`,0),u=n(`FieldOfViewX`,0),d=n(`FieldOfViewY`,0),f=n(`FocalLength`,0),p=30*n(`OrthoZoom`,1),m=T_[a],h=n(`FilmWidth`,m[0]*.001),g=n(`FilmHeight`,m[1]*.001),_=n(`FilmSqueezeRatio`,a===7?2:1);s<=0&&c<=0?(s=h>0?h:1,c=g>0?g:1):s<=0?s=h>0&&g>0?c/g*h:c:c<=0&&(c=h>0&&g>0?s/h*g:s),g*=_;let v=s,y=c;switch(r){case 3:v=s,y=s*c;break;case 4:v=c*s,y=c}let b=y===0?1:v/y,x=g===0?1:h/g,S=o;S===3?S=b>x?2:1:S===4&&(S=b<x?2:1);let C=h,w=g,T=p,E=p;switch(S){case 1:C=g*b,w=g,T=p*b;break;case 2:C=h,w=h/b,E=p/b}h=C;let D=Math.PI/180,ee=180/Math.PI,te,O;switch(i){case 0:te=Math.tan(u*D*.5),O=Math.tan(d*D*.5);break;case 1:te=Math.tan(l*D*.5),O=te/b;break;case 3:{let e=f/25.4;te=e>0?C/e*.5:Math.tan(l*D*.5)*b,O=e>0?w/e*.5:Math.tan(l*D*.5);break}default:O=Math.tan(l*D*.5),te=O*b}return{fovDegX:Math.atan(te)*ee*2,fovDegY:Math.atan(O)*ee*2,aspectRatio:b,apertureMode:i,apertureSizeInch:[C,w],orthographicSize:[T,E]}}function D_(e,t){let n=new Set;for(let r of[`Properties70`,`Properties60`]){let i=J(e,r);for(let e of i?.children??[]){if(e.name!==`P`&&e.name!==`Property`)continue;let r=Y(e,0);r&&!t.has(r)&&n.add(r)}}return Array.from(n).sort()}rr();function O_(e,t,n){let r=L.RotationX(e),i=L.RotationY(t),a=L.RotationZ(n);return r.multiply(i).multiply(a)}function k_(e,t,n,r){let i=L.RotationX(e),a=L.RotationY(t),o=L.RotationZ(n);switch(r){case 0:return i.multiply(a).multiply(o);case 1:return i.multiply(o).multiply(a);case 2:return a.multiply(o).multiply(i);case 3:return a.multiply(i).multiply(o);case 4:return o.multiply(i).multiply(a);case 5:return o.multiply(a).multiply(i);default:return i.multiply(a).multiply(o)}}function A_(e,t,n){let r=L.Translation(e[0],e[1],e[2]);return j_(t,n).multiply(r)}function j_(e,t){let n=Math.PI/180,r=L.Scaling(t[0],t[1],t[2]),i=O_(e[0]*n,e[1]*n,e[2]*n);return r.multiply(i)}function M_(e,t){let n=Math.PI/180,r=L.Scaling(t[0]===0?0:1/t[0],t[1]===0?0:1/t[1],t[2]===0?0:1/t[2]),i=O_(e[0]*n,e[1]*n,e[2]*n);return r.multiply(i)}function N_(e){let{translation:t,rotation:n,scale:r,preRotation:i,postRotation:a,rotationPivot:o,scalingPivot:s,rotationOffset:c,scalingOffset:l,rotationOrder:u}=e,d=Math.PI/180,f=o[0]!==0||o[1]!==0||o[2]!==0||s[0]!==0||s[1]!==0||s[2]!==0,p=c[0]!==0||c[1]!==0||c[2]!==0||l[0]!==0||l[1]!==0||l[2]!==0,m=a[0]!==0||a[1]!==0||a[2]!==0;if(!f&&!p&&!m){let e=O_(i[0]*d,i[1]*d,i[2]*d),a=k_(n[0]*d,n[1]*d,n[2]*d,u),o=L.Translation(t[0],t[1],t[2]),s=a.multiply(e);return L.Scaling(r[0],r[1],r[2]).multiply(s).multiply(o)}let h=L.Translation(t[0],t[1],t[2]),g=L.Translation(c[0],c[1],c[2]),_=L.Translation(o[0],o[1],o[2]),v=L.Translation(-o[0],-o[1],-o[2]),y=L.Translation(l[0],l[1],l[2]),b=L.Translation(s[0],s[1],s[2]),x=L.Translation(-s[0],-s[1],-s[2]),S=O_(i[0]*d,i[1]*d,i[2]*d),C=k_(n[0]*d,n[1]*d,n[2]*d,u),w=L.Scaling(r[0],r[1],r[2]),T;if(m){let e=O_(a[0]*d,a[1]*d,a[2]*d);
8T=new L,e.invertToRef(T)}else T=L.Identity();let E=x;return E=E.multiply(w),E=E.multiply(b),E=E.multiply(y),E=E.multiply(v),E=E.multiply(T),E=E.multiply(C),E=E.multiply(S),E=E.multiply(_),E=E.multiply(g),E=E.multiply(h),E}zn();var P_=Math.PI/180,$={invRoot:new L,parent:new L,invParent:new L,world:new L,local:new L,mA:new L,mB:new L,mC:new L,mD:new L,position:new R,scale:new R,translation:new R,decomposedScale:new R,localValue:new R,up:new R,forward:new R,origin:new R,axisA:new R,axisB:new R,axisC:new R,eulerA:new R,eulerB:new R,rotation:new z,decomposedRotation:new z,result:new z},F_=new WeakMap,I_=class e{constructor(e){this._behaviors=[],this._ordered=[],this._cyclic=[],this._dirty=!1,this._beforeAnimations=null,this._afterAnimations=null,this._scene=e}static Get(e){return F_.get(e)}static GetOrCreate(t){let n=F_.get(t);return n||(n=new e(t),F_.set(t,n)),n}get constraints(){return this._ensureOrder(),this._ordered}get cyclicConstraints(){return this._ensureOrder(),this._cyclic}register(e){this._behaviors.indexOf(e)>=0||(this._behaviors.push(e),this._dirty=!0,this._beforeAnimations||(this._beforeAnimations=this._scene.onBeforeAnimationsObservable.add(()=>this.beginFrame()),this._afterAnimations=this._scene.onAfterAnimationsObservable.add(()=>this.solve())))}unregister(e){let t=this._behaviors.indexOf(e);t<0||(this._behaviors.splice(t,1),this._dirty=!0,this._behaviors.length===0&&(this._scene.onBeforeAnimationsObservable.remove(this._beforeAnimations),this._scene.onAfterAnimationsObservable.remove(this._afterAnimations),this._beforeAnimations=null,this._afterAnimations=null,F_.delete(this._scene)))}invalidateOrder(){this._dirty=!0}beginFrame(){for(let e of this._behaviors)e.restoreBase()}solve(){this._ensureOrder();for(let e of this._behaviors)e.captureBase();for(let e of this._ordered)e.evaluate()}_ensureOrder(){if(!this._dirty)return;this._dirty=!1;let t=this._behaviors,n=t.length,r=t.map(()=>[]);for(let i=0;i<n;i++){let a=t[i].dependencyNodes();for(let o=0;o<n;o++){if(i===o)continue;let n=t[o].attachedNode;n&&a.some(t=>e._IsAncestorOrSelf(n,t))&&r[i].push(o)}}let i=r.map(e=>e.length),a=t.map(()=>!1),o=[],s=!0;for(;s;){s=!1;for(let e=0;e<n;e++)if(!(a[e]||i[e]>0)){a[e]=!0,o.push(t[e]),s=!0;for(let t=0;t<n;t++)!a[t]&&r[t].indexOf(e)>=0&&i[t]--}}let c=[];for(let e=0;e<n;e++)a[e]||(c.push(t[e]),o.push(t[e]));this._ordered=o,this._cyclic=c}static _IsAncestorOrSelf(e,t){let n=t;for(;n;){if(n===e)return!0;n=n.parent}return!1}},L_=class e{constructor(t,n){this.constraint=t,this._options=n,this.attachedNode=null,this.enabled=!0,this._base={position:new R,rotation:new z,scaling:new R},this._hasBase=!1,this.name=`fbxConstraint:${t.name}`,this._offsetTranslation=new R(t.offsetTranslation[0],t.offsetTranslation[1],t.offsetTranslation[2]),this._offsetRotation=O_(t.offsetRotation[0]*P_,t.offsetRotation[1]*P_,t.offsetRotation[2]*P_),this._offsetScale=new R(t.offsetScale[0],t.offsetScale[1],t.offsetScale[2]);let r=new L;this._localBasisTransposed=e._OrthonormalBasisToRef(new R(t.aimVector[0],t.aimVector[1],t.aimVector[2]),new R(t.upVector[0],t.upVector[1],t.upVector[2]),r)?r.transpose():null}init(){}attach(e){this.attachedNode=e,I_.GetOrCreate(e.getScene()).register(this),this.captureBase(),this.evaluate()}detach(){this.attachedNode&&I_.Get(this.attachedNode.getScene())?.unregister(this),this.attachedNode=null,this._hasBase=!1}captureBase(){let e=this.attachedNode;e&&(e.rotationQuaternion||=z.FromEulerVector(e.rotation),this._base.position.copyFrom(e.position),this._base.rotation.copyFrom(e.rotationQuaternion),this._base.scaling.copyFrom(e.scaling),this._hasBase=!0)}restoreBase(){let e=this.attachedNode;e&&this._hasBase&&(e.position.copyFrom(this._base.position),e.rotationQuaternion.copyFrom(this._base.rotation),e.scaling.copyFrom(this._base.scaling))}dependencyNodes(){let e=this._options.targets.map(e=>e.node);return e.push(this._options.upNode),e.push(this.attachedNode?this.attachedNode.parent:null),e}evaluate(){let e=this.attachedNode,t=this.constraint;if(!e||!this.enabled||!t.active||t.weight<=0||this._options.targets.length===0)return;this._hasBase||this.captureBase(),this._options.root.computeWorldMatrix(!0).invertToRef($.invRoot);let n=e.parent;switch(n&&typeof n.computeWorldMatrix==`function`?this._fbxWorld(n,$.parent):L.IdentityToRef($.parent),$.parent.invertToRef($.invParent),t.type){case`position`:this._solvePosition(e);break;case`rotation`:this._solveRotation(e);break;case`scale`:this._solveScale(e);break;case`parent`:this._solveParent(e);break;case`aim`:this._solveAim(e)}}_fbxWorld(e,t){return e.computeWorldMatrix(!0).multiplyToRef($.invRoot,t),t}_blendTargets(e,t,n){e.set(0,0,0),n.set(0,0,0),t.set(0,0,0,1);let r=0;for(let i of this._options.targets){if(i.weight<=0)continue;i.offset.multiplyToRef(this._fbxWorld(i.node,$.world),$.local),$.local.decompose($.decomposedScale,$.decomposedRotation,$.translation);let a=r+i.weight;e.addInPlace($.translation.scaleInPlace(i.weight)),n.addInPlace($.decomposedScale.scaleInPlace(i.weight)),r===0?t.copyFrom($.decomposedRotation):z.SlerpToRef(t,$.decomposedRotation,i.weight/a,t),r=a}return r>0&&(e.scaleInPlace(1/r),n.scaleInPlace(1/r)),r}_applyWeighted(e,t,n,r){let i=this.constraint.weight;r.set(n[0]?e.x+(t.x-e.x)*i:e.x,n[1]?e.y+(t.y-e.y)*i:e.y,n[2]?e.z+(t.z-e.z)*i:e.z)}_applyRotation(e,t,n){let r=this._base.rotation,i=$.result;i.copyFrom(t),n[0]&&n[1]&&n[2]||(r.toEulerAnglesToRef($.eulerA),t.toEulerAnglesToRef($.eulerB),z.FromEulerAnglesToRef(n[0]?$.eulerB.x:$.eulerA.x,n[1]?$.eulerB.y:$.eulerA.y,n[2]?$.eulerB.z:$.eulerA.z,i)),this.constraint.weight<1&&z.SlerpToRef(r,i,this.constraint.weight,i),e.rotationQuaternion.copyFrom(i)}_writePosition(e,t){this._applyWeighted(this._base.position,t,this.constraint.affectTranslation,e.position)}_writeScaling(e,t){this._applyWeighted(this._base.scaling,t,this.constraint.affectScale,e.scaling)}_solvePosition(e){this._blendTargets($.position,$.rotation,$.scale)!==0&&(R.TransformCoordinatesToRef($.position,$.invParent,$.localValue),$.localValue.addInPlace(this._offsetTranslation),this._writePosition(e,$.localValue))}_solveRotation(e){this._blendTargets($.position,$.rotation,$.scale)!==0&&(L.FromQuaternionToRef($.rotation,$.mA),this._offsetRotation.multiplyToRef($.mA,$.mB),$.mB.multiplyToRef($.invParent,$.mC),$.mC.decompose($.decomposedScale,$.decomposedRotation,$.translation),this._applyRotation(e,$.decomposedRotation,this.constraint.affectRotation))}
8_solveScale(e){if(this._blendTargets($.position,$.rotation,$.scale)===0)return;$.parent.decompose($.decomposedScale,$.decomposedRotation,$.translation);let t=$.decomposedScale,n=$.scale;$.localValue.set((t.x===0?n.x:n.x/t.x)*this._offsetScale.x,(t.y===0?n.y:n.y/t.y)*this._offsetScale.y,(t.z===0?n.z:n.z/t.z)*this._offsetScale.z),this._writeScaling(e,$.localValue)}_solveParent(e){this._blendTargets($.position,$.rotation,$.scale)!==0&&(L.ComposeToRef($.scale,$.rotation,$.position,$.mA),$.mA.multiplyToRef($.invParent,$.mB),$.mB.decompose($.decomposedScale,$.decomposedRotation,$.translation),this._writePosition(e,$.translation),this._applyRotation(e,$.decomposedRotation,this.constraint.affectRotation),this._writeScaling(e,$.decomposedScale))}_solveAim(t){let n=this.constraint;if(!this._localBasisTransposed||this._blendTargets($.position,$.rotation,$.scale)===0)return;let r=this._fbxWorld(t,$.world);if(r.getTranslationToRef($.origin),$.position.subtractToRef($.origin,$.forward),$.forward.lengthSquared()<1e-20)return;$.forward.normalize();let i=$.up;switch(n.worldUpType){case 1:this._options.upNode?(this._fbxWorld(this._options.upNode,$.local).getTranslationToRef(i),i.subtractInPlace($.origin)):i.copyFrom(this._options.sceneUp);break;case 2:this._options.upNode?(this._fbxWorld(this._options.upNode,$.local).decompose($.decomposedScale,$.decomposedRotation,$.translation),i.set(n.worldUpVector[0],n.worldUpVector[1],n.worldUpVector[2]),i.rotateByQuaternionToRef($.decomposedRotation,i)):i.copyFrom(this._options.sceneUp);break;case 3:i.set(n.worldUpVector[0],n.worldUpVector[1],n.worldUpVector[2]);break;case 4:$.localValue.set(n.upVector[0],n.upVector[1],n.upVector[2]),R.TransformNormalToRef($.localValue,r,i);break;default:i.copyFrom(this._options.sceneUp)}(i.lengthSquared()<1e-20||Math.abs(R.Dot(i.normalizeToRef($.localValue),$.forward))>.9999)&&(Math.abs($.forward.y)<.9?i.set(0,1,0):i.set(1,0,0)),e._OrthonormalBasisToRef($.forward,i,$.mA)&&(this._localBasisTransposed.multiplyToRef($.mA,$.mB),this._offsetRotation.multiplyToRef($.mB,$.mC),$.mC.multiplyToRef($.invParent,$.mD),$.mD.decompose($.decomposedScale,$.decomposedRotation,$.translation),this._applyRotation(t,$.decomposedRotation,n.affectRotation))}static _OrthonormalBasisToRef(e,t,n){let r=$.axisA,i=$.axisB,a=$.axisC;return e.normalizeToRef(r),t.subtractToRef(r.scaleToRef(R.Dot(r,t),i),i),r.lengthSquared()<1e-20||i.lengthSquared()<1e-20?!1:(i.normalize(),R.CrossToRef(r,i,a),L.FromValuesToRef(r.x,r.y,r.z,0,i.x,i.y,i.z,0,a.x,a.y,a.z,0,0,0,0,1,n),!0)}},R_=e({FBXFileLoader:()=>H_});Rn(),ct(),at(),se(),Rt(),pr(),_(),zn(),g(),Un(),kn(),ne(),Ln(),dn(),Ne(),Wt(),vr(),_r(),Je(),We(),Mt();var z_=`; FBX`,B_=`Kaydara FBX Binary`,V_=10,H_=class e{constructor(e={}){this.name=i.name,this.extensions=i.extensions,this._bindRestBones=new WeakSet,this._sourceBonesBySkeleton=new WeakMap,this._scaleCompensationHelpersBySkeleton=new WeakMap,this._frameRate=30,this._activeLayers=[],this._parentModelById=new Map,this._curveNodesByModelId=new Map,this._inheritScaleHelpers=new Map,this._meshByGeometryKey=new Map,this._instanceSource=new Map,this._evaluatedCurveNodeIds=new Set,this._rigBoneModelIds=new Set;let t=e.preset===`full`;this._options={preset:t?`full`:`compatible`,normalMapCoordinateSystem:e.normalMapCoordinateSystem??`y-up`,materials:e.materials??(t?`auto`:`standard`),unitScale:e.unitScale??`preserve`,shareGeometry:e.shareGeometry??t,onWarning:e.onWarning??(()=>{}),nurbsSubdivision:e.nurbsSubdivision??0,curves:e.curves??(t?`lines`:`skip`),constraints:e.constraints??(t?`apply`:`metadata`),rebaseAnimations:e.rebaseAnimations??!t,attachCamerasAndLights:e.attachCamerasAndLights??t}}createPlugin(t){return new e(t[i.name])}async importMeshAsync(e,t,n,r,i,a){let o=this._parseAndInterpret(n);return this._buildScene(o,t,r,e)}async loadAsync(e,t,n,r,i){let a=this._parseAndInterpret(t);this._buildScene(a,e,n,null)}async loadAssetContainerAsync(e,t,n,r,i){let a=this._parseAndInterpret(t),o=new bt(e),s=this._buildScene(a,e,n,null);for(let e of s.meshes)o.meshes.push(e);for(let e of s.skeletons)o.skeletons.push(e);for(let e of s.animationGroups)o.animationGroups.push(e);for(let e of s.transformNodes)o.transformNodes.push(e);for(let e of s.lights)o.lights.push(e);for(let e of s.cameras)o.cameras.push(e);for(let e of s.materials)this._addMaterialToContainer(e,o);for(let e of s.textures)this._addTextureToContainer(e,o);for(let e of s.meshes)e instanceof Cr||this._addMaterialToContainer(e.material,o);return this._setAssetContainer(o),o.removeAllFromScene(),o}_parseAndInterpret(e){return c_(this._parse(e),{nurbsSubdivision:this._options.nurbsSubdivision>0?this._options.nurbsSubdivision:void 0,rebaseKeyframes:this._options.rebaseAnimations})}_parse(e){if(e instanceof ArrayBuffer)return this._parseFromArrayBuffer(e);if(ArrayBuffer.isView(e)){let t=e,n=t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength);return this._parseFromArrayBuffer(n)}if(typeof e==`string`)return bf(e);throw Error(`FBXFileLoader: unsupported data type`)}_parseFromArrayBuffer(e){let t=new Uint8Array(e,0,Math.min(21,e.byteLength));if(String.fromCharCode(...t).startsWith(B_))return cf(e);let n=new TextDecoder(`utf-8`).decode(e),r=n.substring(0,4096);if(r.trimStart().startsWith(z_)||/^\s*(?:;[^\n]*\n\s*)*(?:FBXHeaderExtension|Definitions|Objects|Connections)\s*:/.test(r))return bf(n);throw Error(`FBXFileLoader: unrecognized FBX format`)}_buildScene(t,n,r,i){let a=this._buildNameFilter(i);this._frameRate=t.frameRate>0?t.frameRate:30,this._inheritScaleHelpers=new Map;let o=new Map;for(let e of t.materials){let t=this._createMaterial(e,n,r);o.set(e.id,t)}let s=[],c=new Map,l=new Map,u=new Map,d=new Map,f=new Map;for(let e of t.skins)f.set(e.id,e);this._rigBoneModelIds=new Set;for(let e of t.rigs)for(let t of e.bones)this._rigBoneModelIds.add(t.modelId);for(let e of t.rigs){let t=this._createSkeleton(e.id,e.bones,n);s.push(t),c.set(e.id,t);for(let n of e.skinBindings){let e=f.get(n.skinId);e&&(l.set(n.geometryId,t),u.set(n.geometryId,e),d.set(n.geometryId,n))}}let p=new Map;this._parentModelById=new Map;let m=(e,t)=>
8{for(let n of e)p.set(n.id,n),t&&this._parentModelById.set(n.id,t),m(n.children,n)};m(t.rootModels,null);let h=e._collectCullingConflictMaterialIds(t.rootModels),g=new Map,_=new Ge(`__fbx_root__`,n);n.useRightHandedSystem||(_.rotation.y=Math.PI,_.scaling.z=-1);let v=this._options.unitScale,y=v===`preserve`?0:v===`meters`?100:v;if(y>0&&t.unitScaleFactor>0){let e=t.unitScaleFactor/y;_.scaling.scaleInPlace(e)}_.metadata={..._.metadata??{},fbxUnitScaleFactor:t.unitScaleFactor,fbxFrameRate:t.frameRate},this._meshByGeometryKey=new Map,this._instanceSource=new Map,this._evaluatedCurveNodeIds=new Set;let b=[],x=[_],S=_,C=e._computeFBXAxisConversionMatrix(t);C.equals(L.Identity())||(S=new Ge(`__fbx_axis_conversion__`,n),S.parent=_,e._applyMatrixToTransform(S,C),x.push(S));let w=new Map,T=L.Identity();for(let e of t.rootModels)this._buildModel(e,n,S,S,T,o,a,b,x,l,u,d,w,h,g);this._linkSkeletonsToTransformNodes(t.rigs,c,w,x,n);for(let e of t.rigs){let t=c.get(e.id);if(!t)continue;b.find(e=>e.skeleton===t);let n=new Set;for(let e of t.bones){let t=e.getTransformNode();t&&n.add(t)}}if(t.blendShapes.length>0){this._applyBlendShapes(t.blendShapes,b,n);for(let[e,t]of Array.from(this._instanceSource))t.morphTargetManager&&!e.morphTargetManager&&(e.morphTargetManager=t.morphTargetManager)}let E=[],D=new Map;for(let e of t.cameras){let t=this._createCamera(e,w,n);t&&(E.push(t),D.set(e.attributeId,t))}let ee=[],te=new Map;for(let e of t.lights){let t=this._createLight(e,w,n);t&&(ee.push(t),te.set(e.attributeId,t))}this._applyConstraints(t,w,_,n);let O=[];for(let e of t.animations){let r=this._createAnimationGroup(e,t.rigs,c,n,w,p,b,{cameraByAttributeId:D,lightByAttributeId:te,materialCache:o});r&&O.push(r)}return this._reportDiagnostics(t,_,w),{meshes:b,particleSystems:[],skeletons:s,animationGroups:O,transformNodes:x,geometries:[],lights:ee,spriteManagers:[],materials:Array.from(o.values()),textures:Array.from(new Set(Array.from(o.values()).flatMap(e=>e.getActiveTextures()))),cameras:E}}_addMaterialToContainer(e,t){if(e){if(e instanceof er){t.multiMaterials.includes(e)||t.multiMaterials.push(e);for(let n of e.subMaterials)this._addMaterialToContainer(n,t)}else t.materials.includes(e)||t.materials.push(e);for(let n of e.getActiveTextures())this._addTextureToContainer(n,t)}}_addTextureToContainer(e,t){t.textures.includes(e)||t.textures.push(e)}_setAssetContainer(e){for(let t of e.meshes)t._parentContainer=e;for(let t of e.transformNodes)t._parentContainer=e;for(let t of e.skeletons)t._parentContainer=e;for(let t of e.animationGroups)t._parentContainer=e;for(let t of e.lights)t._parentContainer=e;for(let t of e.cameras)t._parentContainer=e;for(let t of e.materials)t._parentContainer=e;for(let t of e.multiMaterials)t._parentContainer=e;for(let t of e.textures)t._parentContainer=e}static _computeFBXAxisConversionMatrix(e){let t=[[0,0,0],[0,0,0],[0,0,0]],n=(e,n,r)=>{if(e<0||e>2)return;let i=[0,0,0];i[r]=n>=0?1:-1,t[e]=i};return n(e.coordAxis,e.coordAxisSign,0),n(e.upAxis,e.upAxisSign,1),n(e.frontAxis,e.frontAxisSign,2),t.some(e=>e.every(e=>e===0))?L.Identity():L.FromValues(t[0][0],t[0][1],t[0][2],0,t[1][0],t[1][1],t[1][2],0,t[2][0],t[2][1],t[2][2],0,0,0,0,1)}_buildModel(t,n,r,i,a,o,s,c,l,u,d,f,p,m,h){let g=r,_=e._computeFBXModelLocalMatrix(t).multiply(a),v=this._parentModelById.get(t.id),y=v?p.get(v.id):void 0;if(g&&v&&y&&g===y&&t.inheritType!==1&&!this._isRigBone(t.id)&&!this._isRigBone(v.id)&&!(v.geometry&&d.has(v.geometry.id))){let e=new Ge(`${t.name}__fbx_inheritScale`,n);e.parent=y.parent,e.position.copyFrom(y.position),e.rotationQuaternion=y.rotationQuaternion?y.rotationQuaternion.clone():z.FromEulerVector(y.rotation),e.scaling.set(1,1,1),l.push(e),this._inheritScaleHelpers.set(t.id,e),g=e}if(t.geometry&&t.geometry.indices.length>0&&(!s||s(t.name))){let r=t.geometry.controlPointIndices!==null,a=r?u.get(t.geometry.id):void 0,v=r?d.get(t.geometry.id):void 0,y=r?f.get(t.geometry.id):void 0;a&&v&&(a.needInitialSkinMatrix=!0);let b=`${t.geometry.id}|${t.geometricTranslation.join(`,`)}|${t.geometricRotation.join(`,`)}|${t.geometricScaling.join(`,`)}`,x=!a&&this._options.shareGeometry?this._meshByGeometryKey.get(b):void 0,S;if(x?(S=x.clone(t.name,null,!0),S.sideOrientation=x.sideOrientation,S.metadata={...x.metadata??{},fbxInstanceOf:x.name},this._instanceSource.set(S,x)):(S=this._createMesh(t,t.geometry,n,a,v,y),a||this._meshByGeometryKey.set(b,S)),a&&v){let t=v.meshBindPoseMatr
8ix?L.FromArray(v.meshBindPoseMatrix):_;S.parent=i,e._applyMatrixToTransform(S,t),S.computeWorldMatrix(!0),S.updatePoseMatrix(L.Invert(t)),S.alwaysSelectAsActiveMesh=!0}else g&&(S.parent=g),this._applyRestTRS(S,t);if(t.materials.length>1&&t.geometry?.materialIndices)this._applyMultiMaterial(S,t,o,n,m,h);else if(t.materials.length>0){let n=o.get(t.materials[0].id);n&&(S.material=e._getModelMaterial(n,t,h,m.has(t.materials[0].id)))}t.geometry?.colors&&this._useUnmodulatedVertexColorMaterials(S,n),this._applyMaterialUVSetCoordinates(S.material,t.geometry),c.push(S),p.set(t.id,S),e._applyModelMetadata(S,t);for(let e of t.children)this._buildModel(e,n,S,i,_,o,s,c,l,u,d,f,p,m,h)}else if(t.curve&&this._options.curves!==`skip`&&t.curve.polylines.length>0&&(!s||s(t.name))){let r=this._createLinesMesh(t,t.curve,n);g&&(r.parent=g),this._applyRestTRS(r,t),c.push(r),p.set(t.id,r),e._applyModelMetadata(r,t);for(let e of t.children)this._buildModel(e,n,r,i,_,o,s,c,l,u,d,f,p,m,h)}else{if((t.geometry||t.curve)&&s&&!e._modelSubtreeMatchesNameFilter(t,s))return;let r=new Ge(t.name,n);g&&(r.parent=g),this._applyRestTRS(r,t),l.push(r),p.set(t.id,r),e._applyModelMetadata(r,t);for(let e of t.children)this._buildModel(e,n,r,i,_,o,s,c,l,u,d,f,p,m,h);e._applyLodGroup(t,p)}}_linkSkeletonsToTransformNodes(t,n,r,i,a){for(let o of t){let t=n.get(o.id);if(t)for(let n of o.bones){let o=this._getSourceBone(t,n.index),s=r.get(n.modelId);if(!o||!s)continue;let c=this._getScaleCompensationHelper(t,n.index);if(c){let t=new Ge(c.name,a);t.parent=s.parent,s.parent=t,e._applyMatrixToTransform(t,c.getLocalMatrix()),e._applyMatrixToTransform(s,o.getLocalMatrix()),c.linkTransformNode(t),i.push(t)}else e._applyMatrixToTransform(s,o.getLocalMatrix());o.linkTransformNode(s)}}}static _modelSubtreeMatchesNameFilter(t,n){for(let r of t.children)if(r.geometry&&r.subType===`Mesh`&&n(r.name)||e._modelSubtreeMatchesNameFilter(r,n))return!0;return!1}static _applyModelMetadata(e,t){(t.customProperties||t.diagnostics.length!==0||t.displayLayer||t.lodGroup)&&(e.metadata={...e.metadata??{},...t.customProperties?{fbxCustomProperties:t.customProperties,fbxUserProperties:t.customProperties}:{},...t.diagnostics.length>0?{fbxDiagnostics:t.diagnostics}:{},...t.displayLayer?{fbxDisplayLayer:{name:t.displayLayer.name,show:t.displayLayer.show,freeze:t.displayLayer.freeze,color:t.displayLayer.color}}:{},...t.lodGroup?{fbxLodGroup:t.lodGroup}:{}},t.displayLayer&&!t.displayLayer.show&&e.setEnabled(!1))}static _applyLodGroup(e,t){let n=e.lodGroup;if(!n)return;let r=[];for(let i=0;i<e.children.length;i++){let a=e.children[i],o=n.displayLevels[i]??0;o===2?t.get(a.id)?.setEnabled(!1):o===0&&r.push({child:a,level:i})}if(r.length<2)return;let i=e=>{let n=t.get(e.id);if(!n)return[];let r=n instanceof At?[n]:[];for(let e of n.getChildMeshes(!1))e instanceof At&&r.push(e);return r},a=i(r[0].child);for(let e=1;e<r.length;e++){let t=r[e].level,o=i(r[e].child),s=n.thresholds[t-1]??n.thresholds[n.thresholds.length-1]??0;for(let e=0;e<a.length;e++){let r=o[e]??null;n.relative?(a[e].useLODScreenCoverage=!0,a[e].addLODLevel(s/100,r)):a[e].addLODLevel(s,r),r&&(r.metadata={...r.metadata??{},fbxLodLevel:t})}}}_createLinesMesh(t,n,r){let i=new Cr(t.name,r),a=[],o=[];for(let e of n.polylines){let t=e.length/3;if(t<2)continue;let n=a.length/3;for(let t=0;t<e.length;t++)a.push(e[t]);for(let e=0;e<t-1;e++)o.push(n+e,n+e+1)}let s=e._computeFBXGeometricMatrix(t.geometricTranslation,t.geometricRotation,t.geometricScaling);if(!s.equals(L.Identity()))for(let e=0;e<a.length;e+=3){let t=R.TransformCoordinates(new R(a[e],a[e+1],a[e+2]),s);a[e]=t.x,a[e+1]=t.y,a[e+2]=t.z}let c=new E;return c.positions=a,c.indices=o,c.applyToMesh(i),n.color&&(i.color=new N(n.color[0],n.color[1],n.color[2])),i.metadata={...i.metadata??{},fbxCurveType:n.kind,fbxCurveSegments:n.polylines.length},i}_createMesh(t,n,r,i,a,o){let s=new At(t.name,r);s.sideOrientation=r.useRightHandedSystem?Tn.CounterClockWiseSideOrientation:Tn.ClockWiseSideOrientation;let c=new E,l=U_(n.positions),u=t.geometricTranslation,d=t.geometricRotation,f=t.geometricScaling,p=e._computeFBXGeometricMatrix(u,d,f),m=e._computeFBXGeometricDeltaMatrix(d,f),h=e._computeFBXGeometricNormalMatrix(d,f),g=!p.equals(L.Identity()),_=!m.equals(L.Identity()),v=!h.equals(L.Identity());if(g)for(let e=0;e<l.length;e+=3){let t=R.TransformCoordinates(new R(l[e],l[e+1],l[e+2]),p);l[e]=t.x,l[e+1]=t.y,l[e+2]=t.z}c.positions=l,c.indices=Array.from(n.indices);let y;if(n.normals){if(y=U_(n.normals),v)for(let e=0;e<y.length;e+=3){let t=R.TransformNormal(new R(y[e],y[e+1],y[e+2]),h);t.lengthSquared()>0&&t.normalize(),y[e]=t.x,y[e+1]=t.y,y[e+2]=t.z}c.normals=y}if(n.uvs&&(c.uvs=U_(n.uvs)),n.uvSets.length>1&&(c.uvs2=U_(n.uvSets[1].data)),n.uvSets.length>2&&(c.uvs3=U_(n.uvSets[2].data)),n.uvSets.length>3&&(c.uvs4=U_(n.uvSets[3].data)),n.uvSets.length>4&&(c.uvs5=U_(n.uvSets[4].data)),n.uvSets.length>5&&(c.uvs6=U_(n.uvSets[5].data)),n.tangents){let e=U_(n.tangents);if(v)for(let t=0;t<e.length;t+=4){let n=R.TransformNormal(new R(e[t],e[t+1],e[t+2]),h);n.lengthSquared()>0&&n.normalize(),e[t]=n.x,e[t+1]=n.y,e[t+2]=n.z}W_(e,this._getNormalMapTangentHandednessScale()),c.tangents=e}else y&&c.uvs&&(c.tangents=G_(l,y,c.uvs,n.indices,this._getNormalMapTangentHandednessScale(),n.controlPointIndices,n.materialIndices));if(n.colors){let e=new Float32Array(n.colors.length);for(let t=0;t<e.length;t+=4)e[t]=n.colors[t],e[t+1]=n.colors[t+1],e[t+2]=n.colors[t+2],e[t+3]=1;c.colors=e,s.hasVertexAlpha=!1}if(i&&a){let{matricesIndices:e,matricesWeights:t,matricesIndicesExtra:r,matricesWeightsExtra:i,numBoneInfluencers:l}=this._buildSkinningData(n,a,o);c.matricesIndices=e,c.matricesWeights=t,r&&i&&(c.matricesIndicesExtra=r,c.matricesWeightsExtra=i),s.numBoneInfluencers=l}return c.applyToMesh(s),s.metadata={...s.metadata??{},fbxGeometryId:n.id,fbxControlPointIndices:n.controlPointIndices,fbxGeometryDeltaMatrix:_?m:null,fbxGeometryNormalMatrix:v?h:null,fbxPreRotMatrix:_?m:null},i&&(s.skeleton=i),s}_applyMultiMaterial(t,n,r,i,a,o){let s=n.geometry.materialIndices,c=t.metadata?.fbxSubMeshMaterialIndices;if(c){let s=new er(n.name+`_multi`,i);for(let t of c){let i=n.materials[t],c=i?r.get(i.id):void 0;s.subMaterials.push(c?e._getModelMaterial(c,n,o,a.has(i.id)):null)}t.material=s;return}let l=t.getIndices();if(!l)return;let u=l.length/3,d=new Map;for(let e=0;e<u;e++){let t=e<s.length?s[e]:0,n=d.get(t);n||(n=[],d.set(t,n)),n.push(e)}let f=Array.from(d.keys()).sort((e,t)=>
8e-t),p=[],m=[];for(let e of f){let t=d.get(e),n=p.length;for(let e of t)p.push(l[e*3],l[e*3+1],l[e*3+2]);m.push({start:n,count:t.length*3,matIdx:e})}t.setIndices(p);let h=new er(n.name+`_multi`,i);for(let t of m){let i=n.materials[t.matIdx];if(i){let t=r.get(i.id);t?h.subMaterials.push(e._getModelMaterial(t,n,o,a.has(i.id))):h.subMaterials.push(null)}else h.subMaterials.push(null)}t.material=h,t.subMeshes=[];let g=t.getTotalVertices();for(let e=0;e<m.length;e++){let n=m[e];new it(e,0,g,n.start,n.count,t)}t.metadata={...t.metadata??{},fbxSubMeshMaterialIndices:f}}static _collectCullingConflictMaterialIds(e){let t=new Map,n=e=>{for(let n of e.materials){let r=t.get(n.id)??{cullingOff:!1,cullingOn:!1};e.cullingOff?r.cullingOff=!0:r.cullingOn=!0,t.set(n.id,r)}for(let t of e.children)n(t)};for(let t of e)n(t);let r=new Set;for(let[e,n]of Array.from(t))n.cullingOff&&n.cullingOn&&r.add(e);return r}static _getModelMaterial(e,t,n,r=!0){if(!t.cullingOff||!e.backFaceCulling)return e;if(!r)return e.backFaceCulling=!1,e;let i=n?.get(e);if(i)return i;let a=e.clone(`${e.name}_CullingOff`)??e;return a.backFaceCulling=!1,n?.set(e,a),a}_applyMaterialUVSetCoordinates(e,t){if(e){if(e instanceof er){for(let n of e.subMaterials)(n instanceof he||n instanceof ut)&&this._applyStandardMaterialUVSetCoordinates(n,t);return}(e instanceof he||e instanceof ut)&&this._applyStandardMaterialUVSetCoordinates(e,t)}}_applyStandardMaterialUVSetCoordinates(e,t){for(let n of e instanceof ut?[e.albedoTexture,e.bumpTexture,e.emissiveTexture,e.ambientTexture,e.metallicTexture,e.reflectivityTexture,e.microSurfaceTexture,e.opacityTexture,e.clearCoat.texture,e.clearCoat.bumpTexture,e.sheen.texture]:[e.diffuseTexture,e.bumpTexture,e.emissiveTexture,e.ambientTexture,e.specularTexture,e.opacityTexture,e.reflectionTexture]){if(!n)continue;let e=n.metadata?.fbxUVSetName;if(!e)continue;let r=t.uvSets.findIndex(t=>t.name===e);r>=0&&(n.coordinatesIndex=r)}}_useUnmodulatedVertexColorMaterials(e,t){let n=e.material;if(!n)return;let r=e=>{if(e instanceof he&&!e.diffuseTexture){let t=e.clone(`${e.name}_VertexColor`);return t.diffuseColor=new N(1,1,1),t}if(e instanceof ut&&!e.albedoTexture){let t=e.clone(`${e.name}_VertexColor`);return t.albedoColor=new N(1,1,1),t}return e};if(n instanceof er){let i=new er(`${n.name}_VertexColor`,t);i.subMaterials=n.subMaterials.map(e=>e&&r(e)),e.material=i;return}e.material=r(n)}_buildSkinningData(e,t,n){let r=e.positions.length/3,i=new Float32Array(r*4),a=new Float32Array(r*4),o=null,s=null,c=0;if(e.controlPointIndices){for(let n=0;n<r;n++){let r=e.controlPointIndices[n],i=t.boneIndices[r]??[];c=Math.max(c,Math.min(i.length,8))}c>4&&(o=new Float32Array(r*4),s=new Float32Array(r*4));for(let c=0;c<r;c++){let r=e.controlPointIndices[c],l=t.boneIndices[r]??[],u=t.boneWeights[r]??[];for(let e=0;e<8;e++){let t=e<4?i:o,r=e<4?a:s;if(!t||!r)continue;let d=c*4+e%4;if(e<l.length){let r=l[e],i=n?n.skinBoneIndexToRigBoneIndex[r]:r;if(i===void 0||i<0)throw Error(`FBXFileLoader: missing rig bone mapping for skin bone index ${r}`);t[d]=i}else t[d]=0;r[d]=e<u.length?u[e]:0}}}return{matricesIndices:i,matricesWeights:a,matricesIndicesExtra:o,matricesWeightsExtra:s,numBoneInfluencers:Math.max(c,1)}}_createMaterial(e,t,n){let r=this._options.materials,i=r===`pbr`||r===`auto`&&zm(e.model.shaderType)?this._createPbrMaterial(e,t,n):this._createStandardMaterial(e,t,n);return i.metadata={...i.metadata??{},...e.userProperties?{fbxUserProperties:e.userProperties}:{},fbxShaderType:e.model.shaderType,fbxFeatures:Object.fromEntries(Object.entries(e.model.features).map(([e,t])=>[e,t?.enabled??!1]))},i}_createPbrMaterial(t,n,r){let i=new ut(t.name,n),a=t.model.pbr,o=t.model.features,s=e=>o[e]?.enabled??!1,c=t.model.shaderType===`3dsMaxPbrSpecGloss`,l=(e,t)=>e?new N(e[0]*(t??1),e[1]*(t??1),e[2]*(t??1)):void 0;if(i.albedoColor=l(Wm(a.baseColor),a.baseColor?.texture?1:Gm(a.baseFactor))??N.White(),c)i.metallic=null,i.roughness=null,i.reflectivityColor=l(Wm(a.specularColor),1)??N.White(),i.microSurface=Gm(a.glossiness)??1-(Gm(a.roughness)??.5);else if(i.metallic=s(`metalness`)?Gm(a.metalness)??0:0,i.roughness=Gm(a.roughness)??(a.glossiness?.value?1-a.glossiness.value[0]:.5),s(`specular`)&&a.specularFactor?.value&&(i.metallicF0Factor=Gm(a.specularFactor)??1),s(`specular`)){let e=Wm(a.specularColor);e&&(i.metallicReflectanceColor=new N(e[0],e[1],e[2]))}let u=l(Wm(a.emissionColor),a.emissionColor?.texture?1:Gm(a.emissionFactor));(u&&s(`emission`)||u&&(u.r>0||u.g>0||u.b>0))&&(i.emissiveColor=u);let d=Wm(a.opacity);d&&s(`opacity`)?i.alpha=(d[0]+d[1]+d[2])/3:zm(t.model.shaderType)||(i.alpha=e._alphaFromClassicTransparency(t)),i.alpha<1&&(i.transparencyMode=Tn.MATERIAL_ALPHABLEND);let f=Gm(a.transmissionFactor)??0;if(s(`transmission`)&&zm(t.model.shaderType)&&f>0){i.subSurface.isRefractionEnabled=!0,i.subSurface.refractionIntensity=f;let e=Wm(a.transmissionColor);e&&(i.subSurface.tintColor=new N(e[0],e[1],e[2]));let t=Gm(a.specularIor);t&&s(`ior`)&&(i.subSurface.indexOfRefraction=t)}else{let e=Gm(a.specularIor);e&&s(`ior`)&&e>1&&(i.indexOfRefraction=e)}let p=Gm(a.coatFactor)??0;if(s(`coat`)&&p>0||a.coatFactor?.texture){i.clearCoat.isEnabled=!0,i.clearCoat.intensity=p;let e=Gm(a.coatRoughness);e!==void 0&&(i.clearCoat.roughness=e);let t=Gm(a.coatIor);t!==void 0&&t>1&&(i.clearCoat.indexOfRefraction=t);let n=Wm(a.coatColor);n&&(n[0]!==1||n[1]!==1||n[2]!==1)&&(i.clearCoat.isTintEnabled=!0,i.clearCoat.tintColor=new N(n[0],n[1],n[2]))}let m=Gm(a.sheenFactor)??0;if(s(`sheen`)&&m>0||a.sheenColor?.texture){i.sheen.isEnabled=!0,i.sheen.intensity=m;let e=Wm(a.sheenColor);e&&(i.sheen.color=new N(e[0],e[1],e[2]));let t=Gm(a.sheenRoughness);t!==void 0&&(i.sheen.roughness=t)}s(`unlit`)&&(i.unlit=!0),s(`doubleSided`)&&(i.backFaceCulling=!1);let h=(t,i=!1)=>
8{if(!t?.texture||!t.textureEnabled)return null;let a=e._createTexture(t.texture,n,r,i);return a&&e._applyTextureSettings(a,t.texture),a},g=h(a.baseColor);g&&(i.albedoTexture=g);let _=h(a.normalMap,!0);_&&(i.bumpTexture=_,this._configureNormalTexture(_,i));let v=h(a.emissionColor);v&&(i.emissiveTexture=v,(!u||u.r===0&&u.g===0&&u.b===0)&&(i.emissiveColor=N.White()));let y=h(a.ambientOcclusion);if(y&&(i.ambientTexture=y,i.useAmbientInGrayScale=!0),c){let e=h(a.specularColor);e&&(i.reflectivityTexture=e);let t=h(a.glossiness)??h(a.roughness);t&&(i.microSurfaceTexture=t)}else{let e=a.metalness?.textureEnabled?a.metalness.texture:void 0,t=a.roughness?.textureEnabled&&a.roughness.texture?a.roughness:a.glossiness?.textureEnabled&&a.glossiness.texture?a.glossiness:void 0,n=t?.texture,r=!!e&&!!n&&e.id===n.id,o=!1;if(e&&(r||!n)){let e=h(a.metalness);e&&(o=!0,i.metallicTexture=e,i.useMetallnessFromMetallicTextureBlue=!0,i.useRoughnessFromMetallicTextureGreen=r,i.useRoughnessFromMetallicTextureAlpha=!1)}else if(n){let n=h(t);n&&(i.metallicTexture=n,i.useMetallnessFromMetallicTextureBlue=!1,i.useRoughnessFromMetallicTextureGreen=!0,i.useRoughnessFromMetallicTextureAlpha=!1,e&&(i.metadata={...i.metadata??{},fbxDroppedMetalnessTexture:e.relativeFileName}))}o&&i.metallic===0&&(i.metallic=1)}if(a.opacity?.texture&&a.opacity.textureEnabled){if(g&&a.opacity.texture.id===a.baseColor?.texture?.id)i.useAlphaFromAlbedoTexture=!0,i.transparencyMode=Tn.MATERIAL_ALPHATESTANDBLEND;else{let e=h(a.opacity);e&&(i.opacityTexture=e,i.transparencyMode=Tn.MATERIAL_ALPHATESTANDBLEND)}}if(i.clearCoat.isEnabled){let e=h(a.coatFactor);e&&(i.clearCoat.texture=e);let t=h(a.coatNormal,!0);t&&(i.clearCoat.bumpTexture=t)}if(i.sheen.isEnabled){let e=h(a.sheenColor);e&&(i.sheen.texture=e)}return i}static _alphaFromClassicTransparency(e){let t=e.properties;if(t.opacity!==void 0)return t.opacity;let n=Gm(e.model.fbx.transparencyFactor);if(n===void 0)return 1;let r=Wm(e.model.fbx.transparencyColor),i=r?(r[0]+r[1]+r[2])/3:1;return Math.min(1,Math.max(0,1-i*n))}static _applyTextureSettings(e,t){t.uvTranslation&&(e.uOffset=t.uvTranslation[0],e.vOffset=t.uvTranslation[1]),t.uvScaling&&(e.uScale=t.uvScaling[0],e.vScale=t.uvScaling[1]),t.uvRotation!==void 0&&(e.wAng=t.uvRotation*(Math.PI/180)),t.uvSetIndex!==void 0&&(e.coordinatesIndex=t.uvSetIndex),t.wrapU!==void 0&&(e.wrapU=t.wrapU===1?I.CLAMP_ADDRESSMODE:I.WRAP_ADDRESSMODE),t.wrapV!==void 0&&(e.wrapV=t.wrapV===1?I.CLAMP_ADDRESSMODE:I.WRAP_ADDRESSMODE),(t.uvSetName||t.layeredTextureId!==void 0)&&(e.metadata={...e.metadata??{},...t.uvSetName?{fbxUVSetName:t.uvSetName}:{},...t.layeredTextureId===void 0?{}:{fbxLayeredTextureId:t.layeredTextureId}})}_createStandardMaterial(t,n,r){let i=new he(t.name,n),a=t.properties,o=(...e)=>t.textures.some(t=>e.includes(t.propertyName));if(t.type===`Lambert`&&(i.specularColor=N.Black()),a.diffuseColor){let e=o(`DiffuseColor`,`Diffuse`)?1:a.diffuseFactor??1;i.diffuseColor=new N(a.diffuseColor[0]*e,a.diffuseColor[1]*e,a.diffuseColor[2]*e)}if(a.ambientColor){let e=o(`AmbientColor`,`Ambient`)?1:a.ambientFactor??1;i.ambientColor=new N(a.ambientColor[0]*e,a.ambientColor[1]*e,a.ambientColor[2]*e)}if(t.type===`Phong`&&a.specularColor){let e=o(`SpecularColor`,`Specular`,`Shininess`,`ShininessExponent`)?1:a.specularFactor??1;i.specularColor=new N(a.specularColor[0]*e,a.specularColor[1]*e,a.specularColor[2]*e)}if(a.emissiveColor){let e=o(`EmissiveColor`,`Emissive`)?1:a.emissiveFactor??1;i.emissiveColor=new N(a.emissiveColor[0]*e,a.emissiveColor[1]*e,a.emissiveColor[2]*e)}i.alpha=e._alphaFromClassicTransparency(t),i.alpha<1&&(i.transparencyMode=Tn.MATERIAL_ALPHABLEND),a.shininess!==void 0&&(i.specularPower=a.shininess);for(let a of t.textures){if(!e._isSupportedMaterialTextureSlot(a.propertyName))continue;let t=e._createTexture(a,n,r,e._isNormalMapTextureSlot(a.propertyName));if(t){switch(a.propertyName){case`DiffuseColor`:i.diffuseTexture=t,i.diffuseColor=new N(1,1,1);break;case`NormalMap`:case`NormalMapTexture`:case`normalCamera`:i.bumpTexture=t,this._configureNormalTexture(t,i);break;
8case`Bump`:case`BumpFactor`:i.bumpTexture=t,this._configureNormalTexture(t,i);break;case`EmissiveColor`:i.emissiveTexture=t;break;case`AmbientColor`:i.ambientTexture=t;break;case`SpecularColor`:i.specularTexture=t;break;case`TransparencyFactor`:case`TransparentColor`:i.opacityTexture=t,i.transparencyMode=Tn.MATERIAL_ALPHATESTANDBLEND;break;case`ReflectionColor`:case`ReflectionFactor`:i.reflectionTexture=t}e._applyTextureSettings(t,a)}}return i}_configureNormalTexture(e,t){e.gammaSpace=!1,t.invertNormalMapX=!1,t.invertNormalMapY=this._options.normalMapCoordinateSystem===`y-down`}_getNormalMapTangentHandednessScale(){return this._options.normalMapCoordinateSystem===`y-down`?-1:1}static _isSupportedMaterialTextureSlot(e){switch(e){case`DiffuseColor`:case`NormalMap`:case`NormalMapTexture`:case`normalCamera`:case`Bump`:case`BumpFactor`:case`EmissiveColor`:case`AmbientColor`:case`SpecularColor`:case`TransparencyFactor`:case`TransparentColor`:case`ReflectionColor`:case`ReflectionFactor`:case`DisplacementColor`:case`Displacement`:case`DisplacementFactor`:case`ShininessExponent`:case`Shininess`:return!0;default:return!1}}static _isNormalMapTextureSlot(e){switch(e){case`NormalMap`:case`NormalMapTexture`:case`normalCamera`:case`Bump`:case`BumpFactor`:return!0;default:return!1}}static _createTexture(t,n,r,i){let a=e._getTextureSourceName(t),o=e._getTextureCreationOptions(a,i,t.embeddedData);if(t.embeddedData){let e=new I(null,n,o),r=a??`embeddedTexture_${t.id.toString()}`;return e.updateURL(`data:fbx-embedded-texture/${encodeURIComponent(r)}`,new Uint8Array(t.embeddedData),void 0,o.forcedExtension),e.name=r,e}let s=e._getExternalTextureUrls(t,r),c=s.shift();return c?e._createExternalTexture(c,s,n,o):null}static _createExternalTexture(t,n,r,i){n.push(...e._buildTextureFallbackUrls(t));let a=0,o=new I(t,r,{...i,onError:()=>{let t=n[a++];t&&o.getScene()&&o.updateURL(t,null,void 0,e._getForcedExtension(t))}});return o}static _buildTextureFallbackUrls(e){let t=Math.max(e.lastIndexOf(`/`),e.lastIndexOf(`\\`)),n=e.lastIndexOf(`.`);if(n<=t)return[];let r=e.slice(0,n),i=e.slice(n+1).toLowerCase();return[`png`,`jpg`,`jpeg`,`webp`,`bmp`,`tga`].filter(e=>e!==i).map(e=>`${r}.${e}`)}static _getTextureCreationOptions(t,n,r){let i=r?t?e._getMimeType(t):`image/png`:void 0;return{buffer:r?new Uint8Array(r):void 0,forcedExtension:t?e._getForcedExtension(t,i):r?`.png`:void 0,gammaSpace:!n,mimeType:i}}static _getExternalTextureUrls(t,n){let r=[t.relativeFileName,t.fileName].filter(e=>!!e),i=[];for(let t of r){let r=t.replace(/\\/g,`/`);e._isSafeRelativeTexturePath(r)&&i.push(n+r);let a=e._getTextureSourceNameFromPath(r);a&&i.push(n+a)}return Array.from(new Set(i))}static _getTextureSourceName(t){let n=t.relativeFileName||t.fileName;if(!n)return null;let r=n.replace(/\\/g,`/`);return e._getTextureSourceNameFromPath(r)}static _getTextureSourceNameFromPath(e){return e.split(`/`).pop()??e}static _isSafeRelativeTexturePath(e){return/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(e)||e.startsWith(`/`)||e.startsWith(`//`)?!1:!e.split(`/`).some(e=>e===`..`)}static _getForcedExtension(e,t){let n=Math.max(e.lastIndexOf(`/`),e.lastIndexOf(`\\`)),r=e.lastIndexOf(`.`);if(r>n)return e.slice(r).toLowerCase();switch(t){case`image/png`:return`.png`;case`image/jpeg`:return`.jpg`;case`image/webp`:return`.webp`;case`image/bmp`:return`.bmp`;case`image/gif`:return`.gif`;case`image/x-tga`:return`.tga`;default:return}}static _getMimeType(t){let n=ar(t);if(n)return n;switch(e._getForcedExtension(t)){case`.tga`:return`image/x-tga`;case`.bmp`:return`image/bmp`;case`.gif`:return`image/gif`;default:return`image/png`}}_applyBlendShapes(e,t,n){for(let r of e){let e=t.find(e=>e.metadata?.fbxGeometryId===r.geometryId);if(!e)continue;let i=new qn(n);i.optimizeInfluencers=!1;let a=e.metadata?.fbxGeometryDeltaMatrix??e.metadata?.fbxPreRotMatrix??null,o=e.metadata?.fbxGeometryNormalMatrix??a;for(let t of r.channels){let r=e.metadata?.fbxControlPointIndices;if(!r)continue;let s=e.getVerticesData(`position`),c=e.getVerticesData(`normal`);if(!s)continue;let l=ev(t.deformPercent,t.fullWeights,t.shapes.length),u=[];for(let e=0;e<t.shapes.length;e++){let d=t.shapes[e];if(!d)continue;let f=$_(d,r,s,c,a,o);if(!f)continue;let p=t.fullWeights&&t.shapes.length>1?`${t.name}_${t.fullWeights[e]}`:t.name,m=new kt(p,l[e]??0,n);m.setPositions(f.positions),f.normals&&m.setNormals(f.normals),u.push(i.numTargets),i.addTarget(m)}u.length!==0&&(e.metadata||={},e.metadata.fbxBlendShapeChannelIds||(e.metadata.fbxBlendShapeChannelIds=new Map),e.metadata.fbxBlendShapeChannelIds.set(t.id,u[0]),e.metadata.fbxBlendShapeChannelTargets||(e.metadata.fbxBlendShapeChannelTargets=new Map),e.metadata.fbxBlendShapeChannelTargets.set(t.id,{targetIndices:u,fullWeights:t.fullWeights}))}i.numTargets>0&&(i.numMaxInfluencers=i.numTargets,e.morphTargetManager=i)}}_createCamera(e,t,n){let r=t.get(e.modelId),i=r?r.computeWorldMatrix(!0):L.Identity(),a=R.TransformCoordinates(R.Zero(),i),o=new fr(e.name,a,n);if(o.fov=e.fieldOfView*(Math.PI/180),o.fovMode=De.FOVMODE_VERTICAL_FIXED,o.minZ=e.nearPlane,o.maxZ=e.farPlane,o.metadata={...o.metadata??{},fbxCamera:{projectionType:e.projectionType,focalLength:e.focalLength,filmWidth:e.filmWidth,filmHeight:e.filmHeight,orthoZoom:e.orthoZoom,roll:e.roll,aspectRatio:e.aspectRatio,fieldOfViewX:e.fieldOfViewX,apertureMode:e.apertureMode,apertureSizeInch:e.apertureSizeInch,userProperties:e.userProperties,unknownProperties:e.unknownProperties,diagnostics:e.diagnostics}},e.projectionType===`orthographic`&&(o.mode=De.ORTHOGRAPHIC_CAMERA,o.orthoTop=e.orthographicSize[1]/2,o.orthoBottom=-e.orthographicSize[1]/2,o.orthoRight=e.orthographicSize[0]/2,o.orthoLeft=-e.orthographicSize[0]/2),r&&this._options.attachCamerasAndLights){let t=r;if(i.determinant()<0){let i=new Ge(`${e.name}__fbx_cameraPivot`,n);i.parent=r,i.scaling.set(1,1,-1),t=i}o.parent=t,o.position.set(0,0,0);
8let a=(e.roll??0)*Math.PI/180;o.rotationQuaternion=z.FromRotationMatrix(L.RotationZ(a).multiply(L.RotationY(Math.PI/2)))}else{let e=R.TransformCoordinates(new R(1,0,0),i);o.setTarget(e)}return o}_createLight(e,t,n){let r=t.get(e.modelId),i=r?r.computeWorldMatrix(!0):L.Identity(),a=R.TransformCoordinates(R.Zero(),i),o=new N(e.color[0],e.color[1],e.color[2]),s=R.TransformCoordinates(new R(0,0,-1),i).subtract(a).normalize(),c,l=!!r&&this._options.attachCamerasAndLights,u=l?R.Zero():a,d=l?new R(0,0,-1):s;switch(e.lightType){case 1:c=new Ot(e.name,d,n),c.diffuse=o,c.intensity=e.intensity;break;case 2:{let t=e.coneAngle*(Math.PI/180);c=new Ct(e.name,u,d,t,2,n),c.diffuse=o,c.intensity=e.intensity,e.innerAngle!==void 0&&(c.innerAngle=Math.min(t,e.innerAngle*Math.PI/180));break}default:c=new O(e.name,u,n),c.diffuse=o,c.intensity=e.intensity}return l&&r&&(c.parent=r,c.computeTransformedInformation()),c.specular=o,e.enableFarAttenuation&&e.farAttenuationEnd!==void 0&&e.farAttenuationEnd>0&&(c.range=e.farAttenuationEnd),c.metadata={...c.metadata??{},fbxLight:{lightType:e.lightType,decayType:e.decayType,decayStart:e.decayStart,innerAngle:e.innerAngle,outerAngle:e.outerAngle,enableNearAttenuation:e.enableNearAttenuation,enableFarAttenuation:e.enableFarAttenuation,castShadows:e.castShadows,farAttenuationStart:e.farAttenuationStart,farAttenuationEnd:e.farAttenuationEnd,areaLightShape:e.areaLightShape,userProperties:e.userProperties,unknownProperties:e.unknownProperties,diagnostics:e.diagnostics}},c}_createSkeleton(t,n,r){let i=new Yt(`Skeleton`,`skeleton_${t}`,r),a=[],o=new Map,s=[],c=[],l=[],u=e._computeBoneInheritScales(n,n.map(e=>e.scale));for(let t=0;t<n.length;t++){let r=n[t],i=e._computeFBXLocalMatrix(r.translation,r.rotation,r.scale,r.preRotation,r.postRotation,r.rotationPivot,r.scalingPivot,r.rotationOffset,r.scalingOffset,r.rotationOrder);s[t]=i,l[t]=e._computeFBXRuntimeLocalMatrix(n,i,t,u)}c.push(...e._computeFBXAbsoluteMatrices(n,l));let d=n.map((e,t)=>e.transformLinkMatrix?L.FromArray(e.transformLinkMatrix):e.modelBindPoseMatrix?L.FromArray(e.modelBindPoseMatrix):c[t]),f=d.map((e,t)=>{let r=n[t].parentIndex;if(r<0)return e;let i=new L;return d[r].invertToRef(i),e.multiply(i)}),p=e._shouldUseBindMatricesAsRest(n,s,f),m=e._computeBoneInheritScales(n,n.map(e=>e.scale));for(let t=0;t<n.length;t++){let r=p?f[t]:l[t],c=n[t].parentIndex>=0?a[n[t].parentIndex]:null;if(!p&&n[t].inheritType!==1&&n[t].parentIndex>=0&&c){let a=e._splitParentScaleCompensatedLocalMatrix(s[t],m[n[t].parentIndex],e._getBoneInheritedScale(n,t,m)),l=new mr(`${n[t].name}__fbx_scaleCompensation`,i,c,a.helperLocalMatrix,a.helperLocalMatrix.clone(),L.Identity(),-1);l.metadata={...l.metadata??{},fbxScaleCompensationForBoneIndex:t,fbxScaleCompensationForBoneName:n[t].name},o.set(t,l),c=l,r=a.boneLocalMatrix}let u=new mr(n[t].name,i,c,r,p?r.clone():null,p?r.clone():null,t);p&&n[t].isCluster&&e._getMaxScaleRatio(s[t],f[t])>=V_&&this._bindRestBones.add(u),a.push(u)}if(this._sourceBonesBySkeleton.set(i,a),this._scaleCompensationHelpersBySkeleton.set(i,o),!p){for(let e=0;e<n.length;e++)a[e].updateMatrix(f[e],!1,!1);for(let e of Array.from(o.values()))e.updateMatrix(L.Identity(),!1,!1);for(let e of i.bones)e.getParent()||e._updateAbsoluteBindMatrices(void 0,!0)}return i}_isRigBone(e){return this._rigBoneModelIds.has(e)}_getSourceBone(e,t){return this._sourceBonesBySkeleton.get(e)?.[t]??e.bones[t]}_getScaleCompensationHelper(e,t){return this._scaleCompensationHelpersBySkeleton.get(e)?.get(t)}static _computeFBXAbsoluteMatrices(e,t){let n=[];for(let r=0;r<e.length;r++){let i=e[r].parentIndex;if(i<0){n[r]=t[r].clone();continue}n[r]=t[r].multiply(n[i])}return n}static _computeBoneInheritScales(t,n){let r=[];for(let i=0;i<t.length;i++){let a=n[i],o=e._getBoneInheritScaleNode(t,i);if(o<0||o>=i)r[i]=[a[0],a[1],a[2]];else{let e=r[o];r[i]=[a[0]*e[0],a[1]*e[1],a[2]*e[2]]}}return r}static _getBoneInheritScaleNode(t,n){let r=t[n].parentIndex;return r<0?-1:t[n].inheritType===0?r:t[n].inheritType===2?e._getBoneInheritScaleNode(t,r):-1}static _getBoneInheritedScale(t,n,r){let i=e._getBoneInheritScaleNode(t,n);return i>=0?r[i]:[1,1,1]}static _computeFBXRuntimeLocalMatrix(t,n,r,i){let a=t[r].parentIndex;if(t[r].inheritType===1||a<0)return n;let o=i??e._computeBoneInheritScales(t,t.map(e=>e.scale));return e._applyParentScaleCompensation(n,o[a],e._getBoneInheritedScale(t,r,o))}static _applyParentScaleCompensation(t,n,r){let i=e._splitParentScaleCompensatedLocalMatrix(t,n,r);return i.boneLocalMatrix.multiply(i.helperLocalMatrix)}static _splitParentScaleCompensatedLocalMatrix(t,n,r){let i=t.getTranslation(),a=t.clone();a.setTranslation(R.Zero()),r&&(r[0]!==1||r[1]!==1||r[2]!==1)&&(a=L.Scaling(r[0],r[1],r[2]).multiply(a));let o=L.Compose(e._getInverseScaleVector(n),z.Identity(),i);return{boneLocalMatrix:a,helperLocalMatrix:o}}static _safeInverseScale(e){return Math.abs(e)>1e-8?1/e:1}static _getInverseScaleVector(t){return new R(e._safeInverseScale(t[0]),e._safeInverseScale(t[1]),e._safeInverseScale(t[2]))}static _shouldUseBindMatricesAsRest(t,n,r){return t.some((t,i)=>t.isCluster?e._getMaxScaleRatio(n[i],r[i])>=V_:!1)}static _getMaxScaleRatio(t,n){let r=new R,i=new z,a=new R,o=new R,s=new z,c=new R;
8return t.decompose(r,i,a),n.decompose(o,s,c),Math.max(e._getScaleRatio(r.x,o.x),e._getScaleRatio(r.y,o.y),e._getScaleRatio(r.z,o.z))}static _getScaleRatio(e,t){let n=Math.abs(e),r=Math.abs(t);return n<1e-6||r<1e-6?n<1e-6&&r<1e-6?1:1/0:Math.max(n/r,r/n)}static _computeFBXGeometricMatrix(e,t,n){return A_(e,t,n)}static _computeFBXGeometricDeltaMatrix(e,t){return j_(e,t)}static _computeFBXGeometricNormalMatrix(e,t){return M_(e,t)}static _computeFBXLocalMatrix(e,t,n,r,i,a,o,s,c,l=0){return N_({translation:e,rotation:t,scale:n,preRotation:r,postRotation:i,rotationPivot:a,scalingPivot:o,rotationOffset:s,scalingOffset:c,rotationOrder:l})}_applyRestTRS(t,n){let r=e._computeLocalTRS(n,n.translation,n.rotation,n.scale);this._adjustTRSForInheritMode(n,r,void 0),t.position=r.position,t.rotationQuaternion=r.rotationQuaternion,t.scaling=r.scaling}static _computeFBXModelLocalMatrix(t){return e._computeFBXLocalMatrix(t.translation,t.rotation,t.scale,t.preRotation,t.postRotation,t.rotationPivot,t.scalingPivot,t.rotationOffset,t.scalingOffset,t.rotationOrder)}static _applyMatrixToTransform(e,t){let n=new R,r=new z,i=new R;t.decompose(n,r,i),e.position=i,e.rotationQuaternion=r,e.scaling=n}_createAnimationGroup(t,n,r,i,a,o,s,c){if(t.curveNodes.length===0&&!t.unsupportedCurveNodes.some(e=>e.targetId!==null&&e.curves.length>0))return null;this._activeLayers=t.layers,this._curveNodesByModelId=new Map;for(let e of t.curveNodes){if(e.type===`DeformPercent`)continue;let t=this._curveNodesByModelId.get(e.targetModelId);t?t.push(e):this._curveNodesByModelId.set(e.targetModelId,[e])}let l=new or(t.name,i),u=new Map,d=(e,t)=>{let n=t.getTransformNode()??t,r=u.get(n);if(!r)r=new Set,u.set(n,r);else if(r.has(e.targetProperty))return;r.add(e.targetProperty),l.addTargetedAnimation(e,n)},f=new Map;for(let e of n){let t=r.get(e.id);if(t)for(let n of e.bones){let e=this._getSourceBone(t,n.index);if(!e)continue;let r=f.get(n.modelId);r?r.push(e):f.set(n.modelId,[e])}}let p=new Map,m=new Map,h=[];for(let e of t.curveNodes){if(e.type===`DeformPercent`){h.push(e);continue}f.has(e.targetModelId)?(p.has(e.targetModelId)||p.set(e.targetModelId,[]),p.get(e.targetModelId).push(e)):(m.has(e.targetModelId)||m.set(e.targetModelId,[]),m.get(e.targetModelId).push(e))}let g=new Set;for(let e of n){let n=new Set(e.bones.filter(e=>e.inheritType!==1&&e.parentIndex>=0).map(e=>e.modelId));if(n.size===0)continue;let i=r.get(e.id);if(i&&!i.bones.some(e=>this._bindRestBones.has(e))){for(let e of Array.from(n))g.add(e);for(let{bone:r,animations:a}of this._buildInheritedRigBoneAnimations(e,i,p,o,n,t.startTime,t.stopTime))for(let e of a)d(e,r)}}for(let[e,n]of Array.from(p)){if(g.has(e))continue;let r=f.get(e),i=o.get(e);if(r&&r.length!==0&&i)for(let e of r){let r=this._buildBoneAnimations(n,e.name,i,t.startTime,t.stopTime,this._bindRestBones.has(e)?e.getBindMatrix():void 0);for(let t of r)d(t,e)}}for(let[e,n]of Array.from(m)){let r=a.get(e);if(!r)continue;let i=o.get(e);if(!i)continue;let s=this._buildNodeAnimations(n,r.name,i,t.startTime,t.stopTime);for(let e of s)l.addTargetedAnimation(e,r)}for(let[n,r]of Array.from(this._inheritScaleHelpers)){let i=o.get(n),s=i?this._parentModelById.get(n):void 0;if(!i||!s)continue;let c=this._frameRate,u=[...this._curveNodesByModelId.get(s.id)??[],...this._collectInheritScaleCurves(s).filter(e=>e.targetModelId!==s.id)];if(u.length>0){let n=av(u,c,t.startTime,t.stopTime),i=e=>this._computeInheritAwareLocalMatrix(s,this._sampleModelLocalMatrix(s,this._curveNodesByModelId.get(s.id)??[],e),e),a=e._refineSampleTimes(n,i),o=[],d=[],f=null;for(let e of a){let t=new R,n=new z,r=new R;i(e).decompose(t,n,r),f&&z.Dot(f,n)<0&&n.scaleInPlace(-1),f=n,o.push({frame:e*c,value:r}),d.push({frame:e*c,value:n})}if(!this._isVector3KeysConstant(o)){let e=new M(`${r.name}_position`,`position`,c,M.ANIMATIONTYPE_VECTOR3,M.ANIMATIONLOOPMODE_CYCLE);e.setKeys(o),l.addTargetedAnimation(e,r)}if(!ov(d)){let e=new M(`${r.name}_rotation`,`rotationQuaternion`,c,M.ANIMATIONTYPE_QUATERNION,M.ANIMATIONLOOPMODE_CYCLE);e.setKeys(d),l.addTargetedAnimation(e,r)}}let d=this._collectInheritScaleCurves(s),f=a.get(n);if(f&&d.length>0&&!m.has(n)&&!p.has(n))for(let e of this._buildNodeAnimations([],f.name,i,t.startTime,t.stopTime,d))l.addTargetedAnimation(e,f)}let _=new Map;for(let e of h){let t=_.get(e.targetModelId);
8t?t.push(e):_.set(e.targetModelId,[e])}for(let[e,n]of Array.from(_)){n.sort((e,t)=>e.layerIndex-t.layerIndex);let r=n.filter(e=>e.curves.length>0).map(e=>({layerIndex:e.layerIndex,curves:e.curves}));if(r.length===0)continue;let i=!1;for(let n of s){if(!n.morphTargetManager||i)continue;let a=n.metadata,o=(a?.fbxBlendShapeChannelTargets)?.get(e);if(o){let e=this._frameRate;for(let i=0;i<o.targetIndices.length;i++){let a=n.morphTargetManager.getTarget(o.targetIndices[i]);if(!a)continue;let s=new M(`${a.name}_influence`,`influence`,e,M.ANIMATIONTYPE_FLOAT,M.ANIMATIONLOOPMODE_CYCLE),c=this._layeredScalarKeys(r,t,e=>ev(e,o.fullWeights,o.targetIndices.length)[i]??0);s.setKeys(c),l.addTargetedAnimation(s,a)}i=!0;continue}let s=a?.fbxBlendShapeChannelIds;if(!s)continue;let c=s.get(e);if(c===void 0)continue;let u=n.morphTargetManager.getTarget(c);if(u){let e=this._frameRate,n=new M(`${u.name}_influence`,`influence`,e,M.ANIMATIONTYPE_FLOAT,M.ANIMATIONLOOPMODE_CYCLE);n.setKeys(this._layeredScalarKeys(r,t,e=>e/100)),l.addTargetedAnimation(n,u),i=!0}}}let v=new Map;for(let e of t.unsupportedCurveNodes){if(e.targetId===null||e.curves.length===0)continue;let t=`${e.targetId}|${e.propertyName??e.type}`,n=v.get(t);n?n.push(e):v.set(t,[e])}for(let e of Array.from(v.values())){e.sort((e,t)=>e.layerIndex-t.layerIndex);let n=this._buildPropertyAnimations(e,t,a,c);if(n.length>0)for(let t of e)this._evaluatedCurveNodeIds.add(t.id);for(let{animation:e,target:t}of n)l.addTargetedAnimation(e,t)}return l.targetedAnimations.length>0?(l.normalize(t.startTime*this._frameRate,t.stopTime*this._frameRate),l):(l.dispose(),null)}_buildInheritedRigBoneAnimations(t,n,r,i,a,o,s){let c=this._frameRate,l=new Set;for(let e=0;e<t.bones.length;e++)if(a.has(t.bones[e].modelId))for(let n=e;n>=0;n=t.bones[n].parentIndex)l.add(t.bones[n].modelId);let u=av(t.bones.filter(e=>l.has(e.modelId)).flatMap(e=>r.get(e.modelId)??[]),c,o,s);if(u.length===0)return[];for(let n of t.bones){let t=i.get(n.modelId),a=r.get(n.modelId)??[];l.has(n.modelId)&&t&&a.length!==0&&(u=e._refineSampleTimes(u,e=>this._sampleModelLocalMatrix(t,a,e)))}let d=t.bones.map(()=>({posKeys:[],rotKeys:[],sclKeys:[],prevQuat:null})),f=t.bones.map(()=>({posKeys:[],rotKeys:[],sclKeys:[],prevQuat:null})),p=t.bones.map((t,r)=>{let a=this._getSourceBone(n,r),o=i.get(t.modelId);if(!a||!o||!this._bindRestBones.has(a))return null;let s=e._computeFBXModelLocalMatrix(o),c=new L;return s.invertToRef(c),c});for(let o of u){let s=t.bones.map((e,t)=>{let a=i.get(e.modelId),s=r.get(e.modelId)??[],c=a?this._sampleModelLocalMatrix(a,s,o):L.Identity(),l=p[t];return l&&(c=(this._getSourceBone(n,t)?.getBindMatrix()??L.Identity()).multiply(l).multiply(c)),c}),l=t.bones.map(e=>{let t=i.get(e.modelId),n=r.get(e.modelId)??[];return t?this._sampleModelScale(t,n,o):e.scale}),u=e._computeBoneInheritScales(t.bones,l),m=o*c;for(let n=0;n<s.length;n++){if(!a.has(t.bones[n].modelId))continue;let r=t.bones[n].parentIndex,i=r>=0?u[r]:t.bones[n].scale,o=e._splitParentScaleCompensatedLocalMatrix(s[n],i,e._getBoneInheritedScale(t.bones,n,u));e._pushMatrixKeys(d[n],m,o.boneLocalMatrix),e._pushMatrixKeys(f[n],m,o.helperLocalMatrix)}}let m=[];for(let e=0;e<t.bones.length;e++){if(!a.has(t.bones[e].modelId))continue;let r=this._getSourceBone(n,e);if(!r)continue;let{posKeys:i,rotKeys:o,sclKeys:s}=d[e],l=[];if(!this._isVector3KeysConstant(i)){let e=new M(`${r.name}_position`,`position`,c,M.ANIMATIONTYPE_VECTOR3,M.ANIMATIONLOOPMODE_CYCLE);e.setKeys(i),l.push(e)}if(!ov(o)){let e=new M(`${r.name}_rotation`,`rotationQuaternion`,c,M.ANIMATIONTYPE_QUATERNION,M.ANIMATIONLOOPMODE_CYCLE);e.setKeys(o),l.push(e)}if(!this._isVector3KeysConstant(s)){let e=new M(`${r.name}_scaling`,`scaling`,c,M.ANIMATIONTYPE_VECTOR3,M.ANIMATIONLOOPMODE_CYCLE);e.setKeys(s),l.push(e)}l.length>0&&m.push({bone:r,animations:l});let u=this._getScaleCompensationHelper(n,e);if(!u)continue;let p=[],{posKeys:h,rotKeys:g,sclKeys:_}=f[e];if(!this._isVector3KeysConstant(h)){let e=new M(`${u.name}_position`,`position`,c,M.ANIMATIONTYPE_VECTOR3,M.ANIMATIONLOOPMODE_CYCLE);e.setKeys(h),p.push(e)}if(!ov(g)){let e=new M(`${u.name}_rotation`,`rotationQuaternion`,c,M.ANIMATIONTYPE_QUATERNION,M.ANIMATIONLOOPMODE_CYCLE);e.setKeys(g),p.push(e)}if(!this._isVector3KeysConstant(_)){let e=new M(`${u.name}_scaling`,`scaling`,c,M.ANIMATIONTYPE_VECTOR3,M.ANIMATIONLOOPMODE_CYCLE);e.setKeys(_),p.push(e)}p.length>0&&m.push({bone:u,animations:p})}return m}static _pushMatrixKeys(e,t,n){let r=new R,i=new z,a=new R;n.decompose(r,i,a),e.prevQuat&&z.Dot(e.prevQuat,i)<0&&i.scaleInPlace(-1),e.prevQuat=i,e.posKeys.push({frame:t,value:a}),e.rotKeys.push({frame:t,value:i}),e.sclKeys.push({frame:t,value:r})}_buildNodeAnimations(t,n,r,i,a,o=[]){let s=this._frameRate,c=t.find(e=>e.type===`R`),l=av([...t,...o],s,i,a);if(l.length===0)return[];let u=n=>{let i=this._sampleModelTRS(r,t,n),a=e._computeLocalTRS(r,i.translation,i.rotation,i.scale);return this._adjustTRSForInheritMode(r,a,n),a},d=e._refineSampleTimes(l,e=>{let t=u(e);return L.Compose(t.scaling,t.rotationQuaternion,t.position)}),f=[],p=[],m=[],h=null;for(let e of d){let n=e*s,r=u(e),i=r.scaling,a=r.rotationQuaternion,o=r.position,c=Jg(t,`T`,e),l=Jg(t,`R`,e),d=Jg(t,`S`,e);h&&z.Dot(h,a)<0&&a.scaleInPlace(-1),h=a,f.push(c?{frame:n,value:o,interpolation:1}:{frame:n,value:o}),p.push(l?{frame:n,value:a,interpolation:1}:{frame:n,value:a}),m.push(d?{frame:n,value:i,interpolation:1}:{frame:n,value:i})}let g=[];if(!this._isVector3KeysConstant(f)){let e=new M(`${n}_position`,`position`,s,M.ANIMATIONTYPE_VECTOR3,M.ANIMATIONLOOPMODE_CYCLE);e.setKeys(f),g.push(e)}if(c){let e=new M(`${n}_rotation`,`rotationQuaternion`,s,M.ANIMATIONTYPE_QUATERNION,M.ANIMATIONLOOPMODE_CYCLE);e.setKeys(p),g.push(e)}if(!this._isVector3KeysConstant(m)){let e=new M(`${n}_scaling`,`scaling`,s,M.ANIMATIONTYPE_VECTOR3,M.ANIMATIONLOOPMODE_CYCLE);e.setKeys(m),g.push(e)}return g}static _refineSampleTimes(e,t,n=2){let r=e=>{let n=new R,r=new z,i=new R;return t(e).decompose(n,r,i),{s:n,r,t:i}},i=[],a=(e,t,o,s,c)=>{if(c>=n)return;let l=(e+t)*.5;
8if(!(l>e&&l<t))return;let u=r(l),d=R.Lerp(o.t,s.t,.5),f=R.Lerp(o.s,s.s,.5),p=z.Slerp(o.r,s.r,.5),m=R.Distance(d,u.t),h=R.Distance(f,u.s),g=Math.min(1,Math.abs(z.Dot(p,u.r))),_=2*Math.acos(g),v=1e-4*(1+Math.max(Math.abs(u.t.x),Math.abs(u.t.y),Math.abs(u.t.z))),y=1e-4*(1+Math.max(Math.abs(u.s.x),Math.abs(u.s.y),Math.abs(u.s.z)));(m>v||h>y||_>5e-4)&&(a(e,l,o,u,c+1),i.push(l),a(l,t,u,s,c+1))},o=e.length>0?r(e[0]):null;for(let t=0;t<e.length;t++)if(i.push(e[t]),t+1<e.length&&o){let n=r(e[t+1]);a(e[t],e[t+1],o,n,0),o=n}return i}_layeredScalarKeys(e,t,n){let r=this._frameRate;if(e.length===0)return[];if(e.length===1)return sv(e[0].curves[0],r,t.startTime,t.stopTime,n);let i=e[0].curves[0].channel;return av(e.map(e=>({type:`other`,targetModelId:0,curves:Array.from(e.curves),layerIndex:e.layerIndex})),r,t.startTime,t.stopTime).map(a=>({frame:a*r,value:n(qg(e,t.layers,[i],[0],a)[0])}))}_buildPropertyAnimations(e,t,n,r){let i=this._frameRate,a=e[0],o=a.propertyName??a.type,s=a.targetId,c=[],l=a.curves.find(e=>e.channel===`d|X`)??a.curves[0],u=a.defaultValues,d=e.length>1,f=e.map(e=>({layerIndex:e.layerIndex,curves:e.curves,defaultValues:e.defaultValues})),p=()=>av(e.map(e=>({type:`other`,targetModelId:s,curves:e.curves,layerIndex:e.layerIndex})),i,t.startTime,t.stopTime),m=e=>{let n=a.curves.find(e=>e.channel===`d|X`),r=a.curves.find(e=>e.channel===`d|Y`),o=a.curves.find(e=>e.channel===`d|Z`);return p().map(a=>({frame:a*i,values:d?qg(f,t.layers,[`d|X`,`d|Y`,`d|Z`],e,a):[jg(n,a)??e[0],jg(r,a)??e[1],jg(o,a)??e[2]]}))},h=(e,n=!1)=>{let r=d?p().map(n=>({frame:n*i,value:e(qg(f,t.layers,[l.channel],[u[l.channel]??0],n)[0])})):sv(l,i,t.startTime,t.stopTime,e);if(n)for(let e of r)e.interpolation=1,delete e.inTangent,delete e.outTangent;return r},g=()=>m([u[`d|X`]??1,u[`d|Y`]??1,u[`d|Z`]??1]).map(({frame:e,values:t})=>({frame:e,value:new N(t[0],t[1],t[2])})),_=(e,t,n,r,a)=>{if(r.length===0)return;let o=new M(`${a}_${t}`,t,i,n,M.ANIMATIONLOOPMODE_CYCLE);o.setKeys(r),c.push({animation:o,target:e})},v=n.get(s);if(v){if(o===`Visibility`&&v instanceof At)return _(v,`visibility`,M.ANIMATIONTYPE_FLOAT,h(e=>Math.min(1,Math.max(0,e)),!0),v.name),c;let e=v.metadata?.fbxUserProperties;if(e&&o in e){if(a.curves.some(e=>e.channel===`d|Y`||e.channel===`d|Z`)){let t=e[o],n=Array.isArray(t)?t:[0,0,0];e[o]=new R(n[0]??0,n[1]??0,n[2]??0);let r=m([n[0]??0,n[1]??0,n[2]??0]).map(({frame:e,values:t})=>({frame:e,value:new R(t[0],t[1],t[2])}));_(v,`metadata.fbxUserProperties.${o}`,M.ANIMATIONTYPE_VECTOR3,r,v.name)}else typeof e[o]==`boolean`&&(e[o]=+!!e[o]),_(v,`metadata.fbxUserProperties.${o}`,M.ANIMATIONTYPE_FLOAT,h(e=>e),v.name)}return c}let y=r.cameraByAttributeId.get(s);if(y){let e=y.metadata?.fbxCamera,t=e?.aspectRatio||1,n=e?.apertureMode??2;switch(o){case`FieldOfView`:_(y,`fov`,M.ANIMATIONTYPE_FLOAT,h(e=>n===1?2*Math.atan(Math.tan(e*Math.PI/360)/t):e*Math.PI/180),y.name);break;case`FieldOfViewY`:_(y,`fov`,M.ANIMATIONTYPE_FLOAT,h(e=>e*Math.PI/180),y.name);break;case`FieldOfViewX`:n!==0&&_(y,`fov`,M.ANIMATIONTYPE_FLOAT,h(e=>2*Math.atan(Math.tan(e*Math.PI/360)/t)),y.name);break;case`FocalLength`:{let t=e?.apertureSizeInch?.[1];t&&n===3&&_(y,`fov`,M.ANIMATIONTYPE_FLOAT,h(e=>2*Math.atan(t/Math.max(e/25.4,1e-6)*.5)),y.name);break}case`NearPlane`:_(y,`minZ`,M.ANIMATIONTYPE_FLOAT,h(e=>e),y.name);break;case`FarPlane`:_(y,`maxZ`,M.ANIMATIONTYPE_FLOAT,h(e=>e),y.name)}return c}let b=r.lightByAttributeId.get(s);if(b){switch(o){case`Intensity`:_(b,`intensity`,M.ANIMATIONTYPE_FLOAT,h(e=>e/100),b.name);break;case`Color`:_(b,`diffuse`,M.ANIMATIONTYPE_COLOR3,g(),b.name);break;case`OuterAngle`:case`ConeAngle`:b instanceof Ct&&_(b,`angle`,M.ANIMATIONTYPE_FLOAT,h(e=>e*Math.PI/180),b.name);break;case`InnerAngle`:b instanceof Ct&&_(b,`innerAngle`,M.ANIMATIONTYPE_FLOAT,h(e=>e*Math.PI/180),b.name)}return c}let x=r.materialCache.get(s);if(x){let e=x instanceof ut,t=o.substring(o.lastIndexOf(`|`)+1);return o===`DiffuseColor`||o===`Diffuse`||t===`baseColor`||t===`base_color`||t===`color`?_(x,e?`albedoColor`:`diffuseColor`,M.ANIMATIONTYPE_COLOR3,g(),x.name):o===`EmissiveColor`||o===`Emissive`||t===`emissionColor`||t===`emission_color`||t===`emissive`||t===`emit_color`?_(x,`emissiveColor`,M.ANIMATIONTYPE_COLOR3,g(),x.name):o===`Opacity`?_(x,`alpha`,M.ANIMATIONTYPE_FLOAT,h(e=>e),x.name):o===`TransparencyFactor`||o===`TransparentFactor`?_(x,`alpha`,M.ANIMATIONTYPE_FLOAT,h(e=>1-e),x.name):e&&(t===`roughness`||t===`specular_roughness`||t===`specularRoughness`)?_(x,`roughness`,M.ANIMATIONTYPE_FLOAT,h(e=>e),x.name):e&&(t===`metalness`||t===`metallic`||t===`base_metalness`)?_(x,`metallic`,M.ANIMATIONTYPE_FLOAT,h(e=>e),x.name):!e&&o===`SpecularColor`&&_(x,`specularColor`,M.ANIMATIONTYPE_COLOR3,g(),x.name),c}return c}_applyConstraints(e,t,n,r){let i=e=>e===void 0?void 0:t.get(e)?.name,a=e.upAxisSign>=0?1:-1,o=new R(e.upAxis===0?a:0,e.upAxis===1?a:0,e.upAxis===2?a:0),s=[];for(let r of e.constraints){let e={name:r.name,type:r.type,node:i(r.nodeId),targets:r.targets.map(e=>({node:i(e.modelId),weight:e.weight})),weight:r.weight,active:r.active,...r.type===`singleChainIK`?{firstJoint:i(r.ikFirstJointId),endJoint:i(r.ikEndJointId),effector:i(r.ikEffectorId)}:{}};s.push(e);let a=r.nodeId===void 0?void 0:t.get(r.nodeId);if(!a)continue;let c=a.metadata?.fbxConstraints??[];if(a.metadata={...a.metadata??{},fbxConstraints:[...c,e]},this._options.constraints!==`apply`||r.type===`singleChainIK`||r.type===`unknown`)continue;let l=[];for(let e of r.targets){let n=t.get(e.modelId);if(!n)continue;let i=Math.PI/180,a=r.type===`parent`?L.Compose(new R(...e.offsetScale),z.FromRotationMatrix(O_(e.offsetRotation[0]*i,e.offsetRotation[1]*i,e.offsetRotation[2]*i)),new R(...e.offsetTranslation)):L.Identity();l.push({node:n,weight:e.weight,offset:a})}if(l.length===0)continue;let u=r.worldUpNodeId===void 0?null:t.get(r.worldUpNodeId)??null;a.addBehavior(new L_(r,{root:n,targets:l,upNode:u,sceneUp:o}))}s.length>0&&(n.metadata={...n.metadata??{},fbxConstraints:s})}_reportDiagnostics(e,t,n){let r=[],i=(e,t,n)=>{let i=typeof t==`string`?t:t?.message??JSON.stringify(t);r.push({source:e,message:i,objectName:n,details:typeof t==`string`?void 0:t})};for(let t of e.diagnostics)t.subType!==`duplicate-parent`&&i(`scene`,t,t.objectName??t.nodeName);for(let t of e.geometries)for(let e of t.diagnostics)i(`geometry`,e,t.name);for(let t of e.curves)for(let e of t.diagnostics)i(`geometry`,e,t.name);for(let t of e.skins){for(let e of t.diagnostics)i(`skin`,e);
8for(let e of t.bones)for(let t of e.diagnostics)i(`skin`,t,e.name)}for(let t of e.rigs)for(let e of t.warnings)i(`rig`,e);for(let t of e.animations)for(let e of t.diagnostics)e.type===`unsupported-curve-node`&&e.curveNodeId!==void 0&&this._evaluatedCurveNodeIds.has(e.curveNodeId)||i(`animation`,e,t.name);for(let t of e.cameras)for(let e of t.diagnostics)i(`camera`,e,t.name);for(let t of e.lights)for(let e of t.diagnostics)i(`light`,e,t.name);let a=e=>{for(let t of e){for(let e of t.diagnostics)i(`model`,e,t.name);a(t.children)}};a(e.rootModels),t.metadata={...t.metadata??{},fbxDiagnostics:r,fbxDisplayLayers:e.displayLayers.map(e=>({name:e.name,show:e.show,freeze:e.freeze,color:e.color})),fbxSelectionSets:e.selectionSets.map(e=>({name:e.name,members:e.members.map(e=>({node:n.get(e.modelId)?.name??String(e.modelId),includeNode:e.includeNode,...e.vertices?{vertices:e.vertices}:{},...e.edges?{edges:e.edges}:{},...e.faces?{faces:e.faces}:{}}))}))};for(let e of r)this._options.onWarning(e)}_collectInheritScaleCurves(e){let t=[],n=e,r=new Set;for(;n&&!r.has(n.id);){r.add(n.id);for(let e of this._curveNodesByModelId.get(n.id)??[])e.type===`S`&&t.push(e);n=this._getInheritScaleNode(n)}return t}_isVector3KeysConstant(e){if(e.length<2)return!0;let t=e[0].value;for(let n=1;n<e.length;n++){let r=e[n].value;if(Math.abs(r.x-t.x)>1e-4||Math.abs(r.y-t.y)>1e-4||Math.abs(r.z-t.z)>1e-4)return!1}return!0}_sampleModelTRS(e,t,n){let r=this._activeLayers;return{translation:Kg(t,r,`T`,e.translation,e.rotationOrder,n),rotation:Kg(t,r,`R`,e.rotation,e.rotationOrder,n),scale:Kg(t,r,`S`,e.scale,e.rotationOrder,n)}}static _computeLocalTRS(t,n,r,i){let a=e=>e[0]!==0||e[1]!==0||e[2]!==0,o=Math.PI/180,s=k_(r[0]*o,r[1]*o,r[2]*o,t.rotationOrder);if(a(t.preRotation)&&(s=s.multiply(O_(t.preRotation[0]*o,t.preRotation[1]*o,t.preRotation[2]*o))),a(t.postRotation)){let e=O_(t.postRotation[0]*o,t.postRotation[1]*o,t.postRotation[2]*o),n=new L;e.invertToRef(n),s=n.multiply(s)}let c=new R(n[0],n[1],n[2]);return(a(t.rotationPivot)||a(t.scalingPivot)||a(t.rotationOffset)||a(t.scalingOffset))&&(c=e._computeFBXLocalMatrix(n,r,i,t.preRotation,t.postRotation,t.rotationPivot,t.scalingPivot,t.rotationOffset,t.scalingOffset,t.rotationOrder).getTranslation()),{position:c,rotationQuaternion:z.FromRotationMatrix(s),scaling:new R(i[0],i[1],i[2])}}_adjustTRSForInheritMode(e,t,n){let r=this._parentModelById.get(e.id);if(e.inheritType===1||!r)return;let i=this._getInheritScale(r,n);t.position.x*=i[0],t.position.y*=i[1],t.position.z*=i[2];let a=this._getInheritScaleNode(e);if(a){let e=this._getInheritScale(a,n);t.scaling.x*=e[0],t.scaling.y*=e[1],t.scaling.z*=e[2]}}_sampleModelLocalMatrix(t,n,r,i){let a=this._sampleModelTRS(t,n,r);return e._computeFBXLocalMatrix(a.translation,a.rotation,i??a.scale,t.preRotation,t.postRotation,t.rotationPivot,t.scalingPivot,t.rotationOffset,t.scalingOffset,t.rotationOrder)}_sampleModelScale(e,t,n){return Kg(t,this._activeLayers,`S`,e.scale,e.rotationOrder,n)}_getInheritScale(e,t){if(!e)return[1,1,1];let n=t===void 0?e.scale:this._sampleModelScale(e,this._curveNodesByModelId.get(e.id)??[],t),r=this._getInheritScaleNode(e);if(!r)return[n[0],n[1],n[2]];let i=this._getInheritScale(r,t);return[n[0]*i[0],n[1]*i[1],n[2]*i[2]]}_getInheritScaleNode(e){let t=this._parentModelById.get(e.id);if(t){if(e.inheritType===0)return t;if(e.inheritType===2)return this._getInheritScaleNode(t)}}_computeInheritAwareLocalMatrix(e,t,n){let r=this._parentModelById.get(e.id);if(e.inheritType===1||!r)return t;let i=new R,a=new z,o=new R;t.decompose(i,a,o);let s=this._getInheritScale(r,n);o.x*=s[0],o.y*=s[1],o.z*=s[2];let c=this._getInheritScaleNode(e);if(c){let e=this._getInheritScale(c,n);i.x*=e[0],i.y*=e[1],i.z*=e[2]}return L.Compose(i,a,o)}_buildBoneAnimations(t,n,r,i,a,o){let s=this._frameRate,c=t.find(e=>e.type===`R`),l=av(t,s,i,a);if(l.length===0)return[];let u=e._refineSampleTimes(l,e=>this._sampleModelLocalMatrix(r,t,e)),d=[],f=[],p=[],m=null,h=null;if(o){let t=e._computeFBXLocalMatrix(r.translation,r.rotation,r.scale,r.preRotation,r.postRotation,r.rotationPivot,r.scalingPivot,r.rotationOffset,r.scalingOffset,r.rotationOrder);h=new L,t.invertToRef(h)}for(let e of u){let n=e*s,i=this._sampleModelLocalMatrix(r,t,e),a=h&&o?o.multiply(h).multiply(i):i,c=new R,l=new z,u=ne
8w R;a.decompose(c,l,u),m&&z.Dot(m,l)<0&&l.scaleInPlace(-1),m=l,d.push({frame:n,value:u}),f.push({frame:n,value:l}),p.push({frame:n,value:c})}let g=[];if(!this._isVector3KeysConstant(d)){let e=new M(`${n}_position`,`position`,s,M.ANIMATIONTYPE_VECTOR3,M.ANIMATIONLOOPMODE_CYCLE);e.setKeys(d),g.push(e)}if(c){let e=new M(`${n}_rotation`,`rotationQuaternion`,s,M.ANIMATIONTYPE_QUATERNION,M.ANIMATIONLOOPMODE_CYCLE);e.setKeys(f),g.push(e)}if(!this._isVector3KeysConstant(p)){let e=new M(`${n}_scaling`,`scaling`,s,M.ANIMATIONTYPE_VECTOR3,M.ANIMATIONLOOPMODE_CYCLE);e.setKeys(p),g.push(e)}return g}_buildNameFilter(e){if(!e)return null;if(typeof e==`string`)return e===``?null:t=>t===e;if(e.length===0)return null;let t=new Set(e);return e=>t.has(e)}};function U_(e){let t=new Float32Array(e.length);for(let n=0;n<e.length;n++)t[n]=e[n];return t}function W_(e,t){if(t!==1)for(let n=3;n<e.length;n+=4)e[n]*=t}function G_(e,t,n,r,i=1,a=null,o=null){let s=e.length/3,c=new Map,l=Array(s).fill(null);for(let i=0;i+2<r.length;i+=3){let s=o?o[i/3]:0,u=r[i],d=r[i+1],f=r[i+2],p=u*3,m=d*3,h=f*3,g=u*2,_=d*2,v=f*2,y=e[m]-e[p],b=e[h]-e[p],x=e[m+1]-e[p+1],S=e[h+1]-e[p+1],C=e[m+2]-e[p+2],w=e[h+2]-e[p+2],T=n[_]-n[g],E=n[v]-n[g],D=n[_+1]-n[g+1],ee=n[v+1]-n[g+1],te=T*ee-E*D;if(Math.abs(te)<1e-8)continue;let O=1/te,ne=(ee*y-D*b)*O,re=(ee*x-D*S)*O,ie=(ee*C-D*w)*O,ae=(T*b-E*y)*O,oe=(T*S-E*x)*O,se=(T*w-E*C)*O;K_(u,d,f,ne,re,ie,ae,oe,se,e,t,n,a,s,c,l),K_(d,f,u,ne,re,ie,ae,oe,se,e,t,n,a,s,c,l),K_(f,u,d,ne,re,ie,ae,oe,se,e,t,n,a,s,c,l)}let u=new Float32Array(s*4);for(let e=0;e<s;e++){let n=e*3,r=e*4,[a,o,s]=X_(t[n],t[n+1],t[n+2]),d=l[e]?c.get(l[e]):void 0,f=d?.tx??0,p=d?.ty??0,m=d?.tz??0,h=a*f+o*p+s*m,g=f-a*h,_=p-o*h,v=m-s*h,y=Math.hypot(g,_,v);y>1e-8?(g/=y,_/=y,v/=y):[g,_,v]=Q_(a,o,s);let b=d?.bx??0,x=d?.by??0,S=d?.bz??0,C=o*v-s*_,w=s*g-a*v,T=a*_-o*g,E=Math.hypot(b,x,S)>1e-8&&C*b+w*x+T*S<0?-1:1;u[r]=g,u[r+1]=_,u[r+2]=v,u[r+3]=E*i}return u}function K_(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h){let g=Y_(l,e,t,n);if(g<=1e-8)return;let _=q_(e,r,i,a,o,s,c,l,u,d,f,p),v=m.get(_);v||(v={tx:0,ty:0,tz:0,bx:0,by:0,bz:0},m.set(_,v)),v.tx+=r*g,v.ty+=i*g,v.tz+=a*g,v.bx+=o*g,v.by+=s*g,v.bz+=c*g,h[e]??(h[e]=_)}function q_(e,t,n,r,i,a,o,s,c,l,u,d){let f=e*3,p=e*3,m=e*2,[h,g,_]=X_(c[p],c[p+1],c[p+2]),v=J_(h,g,_,t,n,r,i,a,o);return[u?`cp:${u[e]}`:`p:${Z_(s[f])},${Z_(s[f+1])},${Z_(s[f+2])}`,Z_(h),Z_(g),Z_(_),Z_(l[m]),Z_(l[m+1]),v,d].join(`|`)}function J_(e,t,n,r,i,a,o,s,c){let l=t*a-n*i,u=n*r-e*a,d=e*i-t*r;return l*o+u*s+d*c<0?-1:1}function Y_(e,t,n,r){let i=t*3,a=n*3,o=r*3,s=e[a]-e[i],c=e[a+1]-e[i+1],l=e[a+2]-e[i+2],u=e[o]-e[i],d=e[o+1]-e[i+1],f=e[o+2]-e[i+2],p=Math.hypot(s,c,l),m=Math.hypot(u,d,f);if(p<=1e-8||m<=1e-8)return 0;let h=(s*u+c*d+l*f)/(p*m);return Math.acos(Math.max(-1,Math.min(1,h)))}function X_(e,t,n){let r=Math.hypot(e,t,n);return r>1e-8?[e/r,t/r,n/r]:[0,0,1]}function Z_(e){let t=Math.round(e*1e6);return Object.is(t,-0)?0:t}function Q_(e,t,n){let r=+(Math.abs(e)<.9),i=r===1?0:1,a=e*r+t*i,o=r-e*a,s=i-t*a,c=-n*a,l=Math.hypot(o,s,c);return l<=1e-8?[1,0,0]:(o/=l,s/=l,c/=l,[o,s,c])}function $_(e,t,n,r,i,a){let o=n.length/3,s=new Float32Array(o*3),c=e.normals!==null&&r!==null?new Float32Array(o*3):null;for(let e=0;e<s.length;e++)s[e]=n[e];if(c&&r)for(let e=0;e<c.length;e++)c[e]=r[e];let l=new Map;for(let t=0;t<e.indices.length;t++)l.set(e.indices[t],t);for(let n=0;n<o;n++){let r=t[n],o=l.get(r);if(o===void 0)continue;let u=e.vertices[o*3],d=e.vertices[o*3+1],f=e.vertices[o*3+2];if(i){let e=R.TransformNormal(new R(u,d,f),i);u=e.x,d=e.y,f=e.z}if(s[n*3]+=u,s[n*3+1]+=d,s[n*3+2]+=f,c&&e.normals){let t=e.normals[o*3],r=e.normals[o*3+1],i=e.normals[o*3+2];if(a){let e=R.TransformNormal(new R(t,r,i),a);e.lengthSquared()>0&&e.normalize(),t=e.x,r=e.y,i=e.z}c[n*3]+=t,c[n*3+1]+=r,c[n*3+2]+=i}}return{positions:s,normals:c}}function ev(e,t,n){if(n<=0)return[];if(!t||t.length!==n||n===1)return[tv(e/(t?.[0]&&t[0]!==0?t[0]:100))];let r=Array(n).fill(0);if(e<=t[0])return r[0]=t[0]===0?+(e<=0):tv(e/t[0]),r;for(let n=1;n<t.length;n++){let i=t[n-1],a=t[n];if(e>a)continue;let o=a-i;if(Math.abs(o)<1e-6)return r[n]=1,r;let s=tv((e-i)/o);return r[n-1]=1-s,r[n]=s,r}return r[n-1]=1,r}function tv(e){return Math.max(0,Math.min(1,e))}var nv=512,rv=32,iv=1e5;function av(e,t,n,r){let i=1/0,a=-1/0,o=new Set,s=[];for(let t of e)for(let e of t.curves){s.push(e);for(let t of e.keys)i=Math.min(i,t.time),a=Math.max(a,t.time),t.time>=n&&t.time<=r&&o.add(t.time)}
8if(!Number.isFinite(i)||!Number.isFinite(a))return[];let c=r>n?n:i,l=r>n?r:a;o.add(c),o.add(l);let u=Array.from(o).filter(e=>e>=c&&e<=l).sort((e,t)=>e-t),d=e=>{for(let t of s){let n=t.keys;if(n.length===0)continue;if(e<n[0].time){if(t.preExtrapolation&&t.preExtrapolation.mode!==`constant`)return!0;continue}if(e>=n[n.length-1].time){if(t.postExtrapolation&&t.postExtrapolation.mode!==`constant`)return!0;continue}let r=0,i=n.length-1;for(;i-r>1;){let t=r+i>>1;n[t].time<=e?r=t:i=t}if(n[r].interpolation===`cubic`)return!0}return!1},f=[],p=Math.floor(l*t)-Math.ceil(c*t)+1,m=Math.max(1,Math.ceil(p/iv));for(let e=0;e<u.length;e++){let n=u[e];if(f.push(n),e+1>=u.length)break;let r=u[e+1],i=Math.floor(n*t)+1,a=Math.ceil(r*t)-1,o=a-i+1;if(o<=0)continue;let s=d(n)?nv:rv,c=Math.max(m,Math.ceil(o/s));for(let e=i;e<=a;e+=c)f.push(e/t)}let h=f.sort((e,t)=>e-t),g=[];for(let e of h)e<c-1e-9||e>l+1e-9||(g.length===0||e-g[g.length-1]>1e-9)&&g.push(e);return g}function ov(e){if(e.length<2)return!0;let t=e[0].value;for(let n=1;n<e.length;n++){let r=e[n].value;if(Math.abs(r.x-t.x)>1e-4||Math.abs(r.y-t.y)>1e-4||Math.abs(r.z-t.z)>1e-4||Math.abs(r.w-t.w)>1e-4)return!1}return!0}function sv(e,t,n,r,i){let a=lv(e,n,r),o=e.keys.filter(e=>e.time>=a.start&&e.time<=a.stop).map(e=>({source:e,frame:e.time*t,value:i(e.value)}));o.some(e=>Math.abs(e.source.time-a.start)<1e-6)||o.unshift({source:{time:a.start,value:jg(e,a.start)??0,interpolation:`linear`,leftDx:0,leftDy:0,rightDx:0,rightDy:0},frame:a.start*t,value:i(jg(e,a.start)??0)}),o.some(e=>Math.abs(e.source.time-a.stop)<1e-6)||o.push({source:{time:a.stop,value:jg(e,a.stop)??0,interpolation:`linear`,leftDx:0,leftDy:0,rightDx:0,rightDy:0},frame:a.stop*t,value:i(jg(e,a.stop)??0)});let s=o.map(e=>({frame:e.frame,value:e.value}));for(let e=0;e<o.length-1;e++){let n=o[e].source,r=s[e+1];if(n.interpolation===`constant`){s[e].interpolation=1;continue}if(n.interpolation!==`cubic`)continue;let a=o[e+1].source,c=Math.max(a.time-n.time,1e-6),l=(a.value-n.value)/c;s[e].outTangent=cv(n.rightSlope??l,i)/t,r.inTangent=cv(n.nextLeftSlope??l,i)/t}return s}function cv(e,t){return t(e)-t(0)}function lv(e,t,n){return n>t?{start:t,stop:n}:{start:e.keys[0]?.time??0,stop:e.keys[e.keys.length-1]?.time??0}}jn(),St(),Ke(),Se(),Bn();var uv=class e{constructor(){this.materials=[]}parseMTL(t,n,r,i,a=e.INVERT_TEXTURE_Y,o,s=!1){let c=s?[]:null;if(n instanceof ArrayBuffer)return c??[];let l=n.split(` 9`),u=/\s+/,d,f=null;for(let n=0;n<l.length;n++){let s=l[n].trim();if(s.length===0||s.charAt(0)===`#`)continue;let p=s.indexOf(` `),m=p>=0?s.substring(0,p):s;m=m.toLowerCase();let h=p>=0?s.substring(p+1).trim():``;if(m===`newmtl`){if(f&&this.materials.push(f),o&&!o.has(h)){f=null;continue}let e=t._blockEntityCollection;t._blockEntityCollection=!!i;try{f=new he(h,t),f._parentContainer=i,i?.materials.push(f)}finally{t._blockEntityCollection=e}}else if(m===`kd`&&f)d=h.split(u,3).map(parseFloat),f.diffuseColor=N.FromArray(d);else if(m===`ka`&&f)d=h.split(u,3).map(parseFloat),f.ambientColor=N.FromArray(d);else if(m===`ks`&&f)d=h.split(u,3).map(parseFloat),f.specularColor=N.FromArray(d);else if(m===`ke`&&f)d=h.split(u,3).map(parseFloat),f.emissiveColor=N.FromArray(d);else if(m===`ns`&&f)f.specularPower=parseFloat(h);else if(m===`d`&&f)f.alpha=parseFloat(h);else if(m===`map_ka`&&f)f.ambientTexture=e._GetTexture(r,h,t,i,a,c);else if(m===`map_kd`&&f)f.diffuseTexture=e._GetTexture(r,h,t,i,a,c);else if(m===`map_ks`&&f)f.specularTexture=e._GetTexture(r,h,t,i,a,c);else if(m!==`map_ns`){if(m===`map_bump`&&f){let n=h.split(u),o=n.indexOf(`-bm`),s=null;o>=0&&(s=n[o+1],n.splice(o,2)),f.bumpTexture=e._GetTexture(r,n.join(` `),t,i,a,c),f.bumpTexture&&s!==null&&(f.bumpTexture.level=parseFloat(s))}else m===`map_d`&&f&&(f.opacityTexture=e._GetTexture(r,h,t,i,a,c))}}return f&&this.materials.push(f),c??[]}static _GetTexture(e,t,n,r,i,a){if(!t)return null;let o=e;if(e===`file:`){let e=t.lastIndexOf(`\\`);e===-1&&(e=t.lastIndexOf(`/`)),o+=e>-1?t.substring(e+1):t}else o+=t;let s=a?new Nt:null;s&&(s.promise.catch(()=>void 0),a.push(s.promise));let c,l=()=>{let e=c?.getInternalTexture();if(!e)return;let t=n.getEngine().getLoadedTexturesCache(),r=t.indexOf(e);r!==-1&&t.splice(r,1)},u=n._blockEntityCollection;n._blockEntityCollection=!!r;try{c=new I(o,n,{invertY:i,onLoad:s?.resolve,onError:(e,t)=>
9{c?l():queueMicrotask(l),s&&s.reject(Error(`${o}: ${t?.message||e||`Failed to load texture`}`))}}),c._parentContainer=r,r?.textures.push(c)}finally{n._blockEntityCollection=u}return s&&c.delayLoadState===k.DELAYLOADSTATE_NOTLOADED&&c.delayLoad(),c}};uv.INVERT_TEXTURE_Y=!0,rn(),Ke(),jn(),rr(),gn(),re(),ct(),yt();var dv=class e{constructor(e,t,n){this._positions=[],this._normals=[],this._uvs=[],this._colors=[],this._extColors=[],this._meshesFromObj=[],this._indicesForBabylon=[],this._wrappedPositionForBabylon=[],this._wrappedUvsForBabylon=[],this._wrappedColorsForBabylon=[],this._wrappedNormalsForBabylon=[],this._tuplePosNorm=[],this._curPositionInIndices=0,this._hasMeshes=!1,this._unwrappedPositionsForBabylon=[],this._unwrappedColorsForBabylon=[],this._unwrappedNormalsForBabylon=[],this._unwrappedUVForBabylon=[],this._triangles=[],this._materialNameFromObj=``,this._objMeshName=``,this._increment=1,this._isFirstMaterial=!0,this._grayColor=new F(.5,.5,.5,1),this._hasLineData=!1,this._materialToUse=e,this._babylonMeshesArray=t,this._loadingOptions=n}_isInArray(e,t){e[t[0]]||(e[t[0]]={normals:[],idx:[]});let n=e[t[0]].normals.indexOf(t[1]);return n===-1?-1:e[t[0]].idx[n]}_isInArrayUV(e,t){e[t[0]]||(e[t[0]]={normals:[],idx:[],uv:[]});let n=e[t[0]].normals.indexOf(t[1]);return n!=1&&t[2]===e[t[0]].uv[n]?e[t[0]].idx[n]:-1}_setData(e){e.indiceUvsFromObj??=-1,e.indiceNormalFromObj??=-1;let t;t=this._loadingOptions.optimizeWithUV?this._isInArrayUV(this._tuplePosNorm,[e.indicePositionFromObj,e.indiceNormalFromObj,e.indiceUvsFromObj]):this._isInArray(this._tuplePosNorm,[e.indicePositionFromObj,e.indiceNormalFromObj]),t===-1?(this._indicesForBabylon.push(this._wrappedPositionForBabylon.length),this._wrappedPositionForBabylon.push(e.positionVectorFromOBJ),e.textureVectorFromOBJ!==void 0&&this._wrappedUvsForBabylon.push(e.textureVectorFromOBJ),e.normalsVectorFromOBJ!==void 0&&this._wrappedNormalsForBabylon.push(e.normalsVectorFromOBJ),e.positionColorsFromOBJ!==void 0&&this._wrappedColorsForBabylon.push(e.positionColorsFromOBJ),this._tuplePosNorm[e.indicePositionFromObj].normals.push(e.indiceNormalFromObj),this._tuplePosNorm[e.indicePositionFromObj].idx.push(this._curPositionInIndices++),this._loadingOptions.optimizeWithUV&&this._tuplePosNorm[e.indicePositionFromObj].uv.push(e.indiceUvsFromObj)):this._indicesForBabylon.push(t)}_unwrapData(){try{for(let e=0;e<this._wrappedPositionForBabylon.length;e++)this._unwrappedPositionsForBabylon.push(this._wrappedPositionForBabylon[e].x*this._handednessSign,this._wrappedPositionForBabylon[e].y,this._wrappedPositionForBabylon[e].z),this._wrappedNormalsForBabylon.length&&this._unwrappedNormalsForBabylon.push(this._wrappedNormalsForBabylon[e].x*this._handednessSign,this._wrappedNormalsForBabylon[e].y,this._wrappedNormalsForBabylon[e].z),this._wrappedUvsForBabylon.length&&this._unwrappedUVForBabylon.push(this._wrappedUvsForBabylon[e].x,this._wrappedUvsForBabylon[e].y),this._wrappedColorsForBabylon.length&&this._unwrappedColorsForBabylon.push(this._wrappedColorsForBabylon[e].r,this._wrappedColorsForBabylon[e].g,this._wrappedColorsForBabylon[e].b,this._wrappedColorsForBabylon[e].a);this._wrappedPositionForBabylon.length=0,this._wrappedNormalsForBabylon.length=0,this._wrappedUvsForBabylon.length=0,this._wrappedColorsForBabylon.length=0,this._tuplePosNorm.length=0,this._curPositionInIndices=0}catch(e){throw Error(`Unable to unwrap data while parsing OBJ data.`,{cause:e})}}_getTriangles(e,t){for(let n=t;n<e.length-1;n++)this._pushTriangle(e,n)}_getColor(e){if(this._loadingOptions.importVertexColors)return this._extColors[e]??this._colors[e]}_setDataForCurrentFaceWithPattern1(e,t){this._getTriangles(e,t);for(let e=0;e<this._triangles.length;e++){let t=parseInt(this._triangles[e])-1;this._setData({indicePositionFromObj:t,positionVectorFromOBJ:this._positions[t],positionColorsFromOBJ:this._getColor(t)})}this._triangles.length=0}_setDataForCurrentFaceWithPattern2(e,t){this._getTriangles(e,t);for(let e=0;e<this._triangles.length;e++){let t=this._triangles[e].split(`/`),n=parseInt(t[0])-1,r=parseInt(t[1])-1;this._setData({indicePositionFromObj:n,indiceUvsFromObj:r,positionVectorFromOBJ:this._positions[n],textureVectorFromOBJ:this._uvs[r],positionColorsFromOBJ:this._getColor(n)})}this._triangles.length=0}_setDataForCurrentFaceWithPattern3(e,t){this._getTriangles(e,t);for(let e=0;e<this._triangles.length;e++){let t=this._triangles[e].split(`/`),n=parseInt(t[0])-1,r=parseInt(t[1])-1,i=parseInt(t[2])-1;this._setData({indicePositionFromObj:n,indiceUvsFromObj:r,indiceNormalFromObj:i,positionVectorFromOBJ:this._positions[n],textureVectorFromOBJ:this._uvs[r],normalsVectorFromOBJ:this._normals[i]})}this._triangles.length=0}_setDataForCurrentFaceWithPattern4(e,t){this._getTriangles(e,t);for(let e=0;e<this._triangles.length;e++){let t=this._triangles[e].split(`//`),n=parseInt(t[0])-1,r=parseInt(t[1])-1;this._setData({indicePositionFromObj:n,indiceNormalFromObj:r,positionVectorFromOBJ:this._positions[n],normalsVectorFromOBJ:this._normals[r],positionColorsFromOBJ:this._getColor(n)})}this._triangles.length=0}_setDataForCurrentFaceWithPattern5(e,t){this._getTriangles(e,t);for(let e=0;e<this._triangles.length;e++){let t=this._triangles[e].split(`/`),n=this._positions.length+parseInt(t[0]),r=this._uvs.length+parseInt(t[1]),i=this._normals.length+parseInt(t[2]);this._setData({indicePositionFromObj:n,indiceUvsFromObj:r,indiceNormalFromObj:i,positionVectorFromOBJ:this._positions[n],textureVectorFromOBJ:this._uvs[r],normalsVectorFromOBJ:this._normals[i],positionColorsFromOBJ:this._getColor(n)})}this._triangles.length=0}_addPreviousObjMesh(){this._meshesFromObj.length>0&&(this._handledMesh=this._meshesFromObj[this._meshesFromObj.length-1],this._unwrapData(),this._loadingOptions.useLegacyBehavior&&this._indicesForBabylon.reverse(),this._handledMesh.indices=this._indicesForBabylon.slice(),this._handledMesh.positions=this._unwrappedPositionsForBabylon.slice(),this._unwrappedNormalsForBabylon.length&&(this._handledMesh.normals=this._unwrappedNormalsForBabylon.slice()),this._unwrappedUVForBabylon.length&&(this._handledMesh.uvs=this._unwrappedUVForBabylon.slice()),this._unwrappedColorsForBabylon.length&&(this._handledMesh.colors=this._unwrappedColorsForBabylon.slice()),this._handledMesh.hasLines=this._hasLineData,this._indicesForBabylon.length=0,this._unwrappedPositionsForBabylon.length=0,this._unwrappedColorsForBabylon.length=0,this._unwrappedNormalsForBabylon.length=0,this._unwrappedUVForBabylon.length=0,this._hasLineData=!1)}_optimizeNormals(e){let t=e.getVerticesData(j.PositionKind),n=e.getVerticesData(j.NormalKind),r={};if(!t||!n)return;for(let e=0;e<t.length/3;e++){let n=t[e*3+0],i=t[e*3+1],a=t[e*3+2],o=n+`_`+i+`_`+a,s=r[o];s||(s=[],r[o]=s),s.push(e)}let i=new R;for(let e in r){let t=r[e];if(t.length<2)continue;let a=t[0];for(let e=1;e<t.length;++e){let r=t[e];n[a*3+0]+=n[r*3+0],n[a*3+1]+=n[r*3+1],n[a*3+2]+=n[r*3+2]}i.copyFromFloats(n[a*3+0],n[a*3+1],n[a*3+2]),i.normalize();for(let e=0;e<t.length;++e){let r=t[e];
9n[r*3+0]=i.x,n[r*3+1]=i.y,n[r*3+2]=i.z}}e.setVerticesData(j.NormalKind,n)}static _IsLineElement(e){return e.startsWith(`l`)}static _IsObjectElement(e){return e.startsWith(`o`)}static _IsGroupElement(e){return e.startsWith(`g`)}static _GetZbrushMRGB(e,t){if(!e.startsWith(`mrgb`))return null;if(e=e.replace(`mrgb`,``).trim(),t)return[];let n=e.match(/[a-z0-9]/g);if(!n||n.length%8!=0)return[];let r=[];for(let e=0;e<n.length/8;e++){let t=n[e*8+2]+n[e*8+3],i=n[e*8+4]+n[e*8+5],a=n[e*8+6]+n[e*8+7];r.push(new F(parseInt(t,16)/255,parseInt(i,16)/255,parseInt(a,16)/255,1))}return r}parse(t,n,r,i,a){n=n.replace(/#MRGB/g,`mrgb`),n=n.replace(/#.*$/gm,``).trim(),this._loadingOptions.useLegacyBehavior?(this._pushTriangle=(e,t)=>this._triangles.push(e[0],e[t],e[t+1]),this._handednessSign=1):r.useRightHandedSystem?(this._pushTriangle=(e,t)=>this._triangles.push(e[0],e[t+1],e[t]),this._handednessSign=1):(this._pushTriangle=(e,t)=>this._triangles.push(e[0],e[t],e[t+1]),this._handednessSign=-1);let o=n.split(` 10`),s=[],c=[];s.push(c);for(let t=0;t<o.length;t++){let n=o[t].trim().replace(/\s\s/g,` `);if(n.length!==0&&n.charAt(0)!==`#`){if((e._IsGroupElement(n)||e._IsObjectElement(n))&&(c=[],s.push(c)),e._IsLineElement(n)){let e=n.split(` `);for(let t=1;t<e.length-1;t++)c.push(`l ${e[t]} ${e[t+1]}`)}else c.push(n)}}let l=s.flat();for(let t=0;t<l.length;t++){let n=l[t].trim().replace(/\s\s/g,` `),r;if(n.length!==0&&n.charAt(0)!==`#`){if(e.VertexPattern.test(n)){if(r=n.match(/[^ ]+/g),this._positions.push(new R(parseFloat(r[1]),parseFloat(r[2]),parseFloat(r[3]))),this._loadingOptions.importVertexColors){if(r.length>=7){let e=parseFloat(r[4]),t=parseFloat(r[5]),n=parseFloat(r[6]);this._colors.push(new F(e>1?e/255:e,t>1?t/255:t,n>1?n/255:n,r.length===7||r[7]===void 0?1:parseFloat(r[7])))}else this._colors.push(this._grayColor)}}else if((r=e.NormalPattern.exec(n))!==null)this._normals.push(new R(parseFloat(r[1]),parseFloat(r[2]),parseFloat(r[3])));else if((r=e.UVPattern.exec(n))!==null)this._uvs.push(new Xn(parseFloat(r[1])*this._loadingOptions.UVScaling.x,parseFloat(r[2])*this._loadingOptions.UVScaling.y));else if((r=e.FacePattern3.exec(n))!==null)this._setDataForCurrentFaceWithPattern3(r[1].trim().split(` `),1);else if((r=e.FacePattern4.exec(n))!==null)this._setDataForCurrentFaceWithPattern4(r[1].trim().split(` `),1);else if((r=e.FacePattern5.exec(n))!==null)this._setDataForCurrentFaceWithPattern5(r[1].trim().split(` `),1);else if((r=e.FacePattern2.exec(n))!==null)this._setDataForCurrentFaceWithPattern2(r[1].trim().split(` `),1);else if((r=e.FacePattern1.exec(n))!==null)this._setDataForCurrentFaceWithPattern1(r[1].trim().split(` `),1);else if((r=e.LinePattern1.exec(n))!==null)this._setDataForCurrentFaceWithPattern1(r[1].trim().split(` `),0),this._hasLineData=!0;else if((r=e.LinePattern2.exec(n))!==null)this._setDataForCurrentFaceWithPattern2(r[1].trim().split(` `),0),this._hasLineData=!0;else if(r=e._GetZbrushMRGB(n,!this._loadingOptions.importVertexColors))for(let e of r)this._extColors.push(e);else if((r=e.LinePattern3.exec(n))!==null)this._setDataForCurrentFaceWithPattern3(r[1].trim().split(` `),0),this._hasLineData=!0;else if(e.GroupDescriptor.test(n)||e.ObjectDescriptor.test(n)){let t={name:n.substring(2).trim(),indices:null,positions:null,normals:null,uvs:null,colors:null,materialName:this._materialNameFromObj,isObject:e.ObjectDescriptor.test(n)};this._addPreviousObjMesh(),this._meshesFromObj.push(t),this._hasMeshes=!0,this._isFirstMaterial=!0,this._increment=1}else if(e.UseMtlDescriptor.test(n)){if(this._materialNameFromObj=n.substring(7).trim(),!this._isFirstMaterial||!this._hasMeshes){this._addPreviousObjMesh();let e={name:(this._objMeshName||`mesh`)+`_mm`+this._increment.toString(),indices:null,positions:null,normals:null,uvs:null,colors:null,materialName:this._materialNameFromObj,isObject:!1};this._increment++,this._meshesFromObj.push(e),this._hasMeshes=!0}this._hasMeshes&&this._isFirstMaterial&&(this._meshesFromObj[this._meshesFromObj.length-1].materialName=this._materialNameFromObj,this._isFirstMaterial=!1)}else e.MtlLibGroupDescriptor.test(n)?a(n.substring(7).trim()):e.SmoothDescriptor.test(n)||A.Log(`Unhandled expression at line : `+n)}}if(this._hasMeshes&&(this._handledMesh=this._meshesFromObj[this._meshesFromObj.length-1],this._loadingOptions.useLegacyBehavior&&this._indicesForBabylon.reverse(),this._unwrapData(),this._handledMesh.indices=this._indicesForBabylon,this._handledMesh.positions=this._unwrappedPositionsForBabylon,this._unwrappedNormalsForBabylon.length&&(this._handledMesh.normals=this._unwrappedNormalsForBabylon),this._unwrappedUVForBabylon.length&&(this._handledMesh.uvs=this._unwrappedUVForBabylon),this._unwrappedColorsForBabylon.length&&(this._handledMesh.colors=this._unwrappedColorsForBabylon),this._handledMesh.hasLines=this._hasLineData),!this._hasMeshes){let e=null;if(this._indicesForBabylon.length)this._loadingOptions.useLegacyBehavior&&this._indicesForBabylon.reverse(),this._unwrapData();else{for(let e of this._positions)this._unwrappedPositionsForBabylon.push(e.x,e.y,e.z);if(this._normals.length)for(let e of this._normals)this._unwrappedNormalsForBabylon.push(e.x,e.y,e.z);if(this._uvs.length)for(let e of this._uvs)this._unwrappedUVForBabylon.push(e.x,e.y);if(this._extColors.length)for(let e of this._extColors)this._unwrappedColorsForBabylon.push(e.r,e.g,e.b,e.a);else if(this._colors.length)for(let e of this._colors)this._unwrappedColorsForBabylon.push(e.r,e.g,e.b,e.a);if(!this._materialNameFromObj){let t=r._blockEntityCollection;r._blockEntityCollection=!!i;try{e=new he(C.RandomId(),r),e._parentContainer=i,i?.materials.push(e)}finally{r._blockEntityCollection=t}e.pointsCloud=!0,this._materialNameFromObj=e.name,this._normals.length||(e.disableLighting=!0,e.emissiveColor=N.White())}}this._meshesFromObj.push({name:C.RandomId(),indices:this._indicesForBabylon,positions:this._unwrappedPositionsForBabylon,colors:this._unwrappedColorsForBabylon,normals:this._unwrappedNormalsForBabylon,uvs:this._unwrappedUVForBabylon,materialName:this._materialNameFromObj,directMaterial:e,isObject:!0,hasLines:this._hasLineData})}for(let e=0;e<this._meshesFromObj.length;e++){if(t&&this._meshesFromObj[e].name){if(t instanceof Array){if(t.indexOf(this._meshesFromObj[e].name)===-1)continue}else if(this._meshesFromObj[e].name!==t)continue}this._handledMesh=this._meshesFromObj[e];let n=r._blockEntityCollection;r._blockEntityCollection=!!i;let a;try{a=new At(this._meshesFromObj[e].name,r),a._parentContainer=i,i?.meshes.push(a)}finally{r._blockEntityCollection=n}if(this._handledMesh._babylonMesh=a,!this._handledMesh.isObject){for(let t=e-1;t>=0;--t)if(this._meshesFromObj[t].isObject&&this._meshesFromObj[t]._babylonMesh){a.parent=this._meshesFromObj[t]._babylonMesh;break}}if(this._materialToUse.push(this._meshesFromObj[e].materialName),this._handledMesh.hasLines&&(a._internalMetadata??(a._internalMetadata={}),a._internalMetadata._isLine=!0),this._handledMesh.positions?.length===0){this._babylonMeshesArray.push(a);continue}let o=new E;if(o.indices=this._handledMesh.indices,o.positions=this._handledMesh.positions,this._loadingOptions.computeNormals||!this._handledMesh.normals?.length){let e=[];E.ComputeNormals(this._handledMesh.positions,this._handledMesh.indices,e),o.normals=e}else o.normals=this._handledMesh.normals;this._handledMesh.uvs?.length&&(o.uvs=this._handledMesh.uvs),this._handledMesh.colors?.length&&(o.colors=this._handledMesh.colors);let s=r._blockEntityCollection;r._blockEntityCollection=!!i;try{o.applyToMesh(a),a.geometry._parentContainer=i,i?.geometries.push(a.geometry)}finally{r._blockEntityCollection=s}this._loadingOptions.invertY&&(a.scaling.y*=-1),this._loadingOptions.optimizeNormals&&this._optimizeNormals(a),this._babylonMeshesArray.push(a),this._handledMesh.directMaterial&&(a.material=this._handledMesh.directMaterial)}}};dv.ObjectDescriptor=/^o/,dv.GroupDescriptor=/^g/,dv.MtlLibGroupDescriptor=/^mtllib /,dv.UseMtlDescriptor=/^usemtl /,dv.SmoothDescriptor=/^s /,dv.VertexPattern=/^v(\s+[\d|.|+|\-|e|E]+){3,7}/,dv.NormalPattern=/^vn(\s+[\d|.|+|\-|e|E]+)( +[\d|.|+|\-|e|E]+)( +[\d|.|+|\-|e|E]+)/,dv.UVPattern=/^vt(\s+[\d|.|+|\-|e|E]+)( +[\d|.|+|\-|e|E]+)/,dv.FacePattern1=/^f\s+(([\d]{1,}[\s]?){3,})+/,dv.FacePattern2=/^f\s+((([\d]{1,}\/[\d]{1,}[\s]?){3,})+)/,dv.FacePattern3=/^f\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){3,})+)/,dv.FacePattern4=/^f\s+((([\d]{1,}\/\/[\d]{1,}[\s]?){3,})+)/,dv.FacePattern5=/^f\s+(((-[\d]{1,}\/-[\d]{1,}\/-[\d]{1,}[\s]?){3,})+)/,dv.LinePattern1=/^l\s+(([\d]{1,}[\s]?){2,})+/,dv.LinePattern2=/^l\s+((([\d]{1,}\/[\d]{1,}[\s]?){2,})+)/,dv.LinePattern3=/^l\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){2,})+)/;var fv=e({OBJFileLoader:()=>pv});zn(),wt(),We(),at();var pv=class e{static get INVERT_TEXTURE_Y(){return uv.INVERT_TEXTURE_Y}static set INVERT_TEXTURE_Y(e){uv.INVERT_TEXTURE_Y=e}constructor(t){this.name=o.name,this.extensions=o.extensions,this._assetContainer=null,this._loadingOptions={...e._DefaultLoadingOptions,...t??{}}}static get _DefaultLoadingOptions(){return{encoding:e.ENCODING,computeNormals:e.COMPUTE_NORMALS,optimizeNormals:e.OPTIMIZE_NORMALS,importVertexColors:e.IMPORT_VERTEX_COLORS,invertY:e.INVERT_Y,invertTextureY:e.INVERT_TEXTURE_Y,waitForTextures:e.WAIT_FOR_TEXTURES,UVScaling:e.UV_SCALING,materialLoadingFailsSilently:e.MATERIAL_LOADING_FAILS_SILENTLY,optimizeWithUV:e.OPTIMIZE_WITH_UV,skipM
10aterials:e.SKIP_MATERIALS,useLegacyBehavior:e.USE_LEGACY_BEHAVIOR}}_loadMTL(e,t,n,r){let i=t+e;P.LoadFile(i,n,void 0,void 0,!0,(e,t)=>{r(i,t)})}_decode(e){if(typeof e==`string`)return e;let t=new Uint8Array(e),n=this._loadingOptions.encoding??`auto`;if(n!==`auto`)return new TextDecoder(n).decode(t);if(t[0]===255&&t[1]===254)return new TextDecoder(`utf-16le`).decode(t);if(t[0]===254&&t[1]===255)return new TextDecoder(`utf-16be`).decode(t);try{return new TextDecoder(`utf-8`,{fatal:!0}).decode(t)}catch{return new TextDecoder(`gb18030`).decode(t)}}createPlugin(t){return new e(t[o.name])}canDirectLoad(){return!1}importMeshAsync(e,t,n,r){return this._parseSolidAsync(e,t,n,r).then(e=>{let t=[];for(let n=0;n<e.length;++n){let r=e[n].geometry;r&&t.push(r)}return{meshes:e,particleSystems:[],skeletons:[],animationGroups:[],transformNodes:[],geometries:t,lights:[],spriteManagers:[]}})}loadAsync(e,t,n){return this.importMeshAsync(null,e,t,n).then(()=>{})}async loadAssetContainerAsync(e,t,n){let r=new bt(e);this._assetContainer=r;try{return await this.importMeshAsync(null,e,t,n),r}catch(e){throw r.dispose(),e}finally{this._assetContainer=null}}_parseSolidAsync(e,t,n,r){let i=``,a=new uv,o=[],s=[];n=this._decode(n),n=n.replace(/#.*$/gm,``).trim(),new dv(o,s,this._loadingOptions).parse(e,n,t,this._assetContainer,e=>{i=e});let c=[];return i!==``&&!this._loadingOptions.skipMaterials&&c.push(new Promise((e,n)=>{this._loadMTL(i,r,async c=>{try{let n=a.parseMTL(t,this._decode(c),r,this._assetContainer,this._loadingOptions.invertTextureY,new Set(o),this._loadingOptions.waitForTextures);for(let e=0;e<a.materials.length;++e){let t=a.materials[e];for(let e=o.indexOf(t.name);e!==-1;e=o.indexOf(t.name,e+1)){let n=s[e];n.material=t,n.getTotalIndices()||(t.pointsCloud=!0)}}if(this._loadingOptions.waitForTextures){let e=(await Promise.allSettled(n)).find(e=>e.status===`rejected`);if(e)throw e.reason}e()}catch(t){P.Warn(`Error processing MTL file: '${i}'`),this._loadingOptions.materialLoadingFailsSilently?e():n(t)}},(t,r)=>{P.Warn(`Error downloading MTL file: '${i}'`),this._loadingOptions.materialLoadingFailsSilently?e():n(r)})})),Promise.all(c).then(()=>{let e=e=>!!(e._internalMetadata?._isLine??!1);return s.forEach(n=>{if(e(n)){let r=n.material;if(!r){let e=t._blockEntityCollection;t._blockEntityCollection=!!this._assetContainer;try{r=new he(n.name+`_line`,t),r._parentContainer=this._assetContainer,this._assetContainer?.materials.push(r)}finally{t._blockEntityCollection=e}}if(r.getBindedMeshes().filter(t=>!e(t)).length>0){let e=r,{ambientTexture:n,diffuseTexture:i,specularTexture:a,bumpTexture:o,opacityTexture:s}=e,c=t._blockEntityCollection,l;try{e.ambientTexture=null,e.diffuseTexture=null,e.specularTexture=null,e.bumpTexture=null,e.opacityTexture=null,t._blockEntityCollection=!!this._assetContainer,l=e.clone(e.name+`_line`),l._parentContainer=this._assetContainer,this._assetContainer?.materials.push(l)}finally{t._blockEntityCollection=c,e.ambientTexture=n,e.diffuseTexture=i,e.specularTexture=a,e.bumpTexture=o,e.opacityTexture=s}l.ambientTexture=n,l.diffuseTexture=i,l.specularTexture=a,l.bumpTexture=o,l.opacityTexture=s,r=l}r.wireframe=!0,n.material=r}}),s.forEach(e=>{e._internalMetadata&&(e._internalMetadata._isLine=void 0)}),s})}};pv.ENCODING=`auto`,pv.OPTIMIZE_WITH_UV=!0,pv.INVERT_Y=!1,pv.WAIT_FOR_TEXTURES=!1,pv.IMPORT_VERTEX_COLORS=!1,pv.COMPUTE_NORMALS=!1,pv.OPTIMIZE_NORMALS=!1,pv.UV_SCALING=new Xn(1,1),pv.SKIP_MATERIALS=!1,pv.MATERIAL_LOADING_FAILS_SILENTLY=!0,pv.USE_LEGACY_BEHAVIOR=!1,un(),y(),tr(),Zt(),Se(),wt();var mv=.28209479177387814;async function hv(e,t,n){return await new Promise((r,i)=>{let a=n.createCanvasImage();if(!a)throw Error(`Failed to create ImageBitmap`);a.onload=()=>{try{let e=n.createCanvas(a.width,a.height);if(!e)throw Error(`Failed to create canvas`);let t=e.getContext(`2d`);if(!t)throw Error(`Failed to get 2D context`);t.drawImage(a,0,0);let i=t.getImageData(0,0,e.width,e.height);r({bits:new Uint8Array(i.data.buffer),width:i.width,height:i.height})}catch(e){i(`Error loading image ${a.src} with exception: ${e}`)}},a.onerror=e=>{i(`Error loading image ${a.src} with exception: ${e}`)},a.crossOrigin=`anonymous`;let o;if(typeof e==`string`){if(!t)throw Error(`filename is required when using a URL`);a.src=e+t}else{let t=new Blob([e],{type:`image/webp`});o=URL.createObjectURL(t),a.src=o}})}
10async function gv(e,t,n){let r=e.count?e.count:e.means.shape[0],i=new ArrayBuffer(32*r),a=new Float32Array(i),o=new Float32Array(i),s=new Uint8ClampedArray(i),c=new Uint8ClampedArray(i),l=e=>Math.sign(e)*(Math.exp(Math.abs(e))-1),u=t[0].bits,d=t[1].bits;if(!Array.isArray(e.means.mins)||!Array.isArray(e.means.maxs))throw Error(`Missing arrays in SOG data.`);for(let t=0;t<r;t++){let n=t*4;for(let r=0;r<3;r++){let i=e.means.mins[r],o=e.means.maxs[r],s=d[n+r],c=u[n+r],f=s<<8|c,p=we.Lerp(i,o,f/65535);a[t*8+r]=l(p)}}let f=t[2].bits;if(e.version===2){if(!e.scales.codebook)throw Error(`Missing codebook in SOG version 2 scales data.`);for(let t=0;t<r;t++){let n=t*4;for(let r=0;r<3;r++){let i=e.scales.codebook[f[n+r]],a=Math.exp(i);o[t*8+3+r]=a}}}else{if(!Array.isArray(e.scales.mins)||!Array.isArray(e.scales.maxs))throw Error(`Missing arrays in SOG scales data.`);for(let t=0;t<r;t++){let n=t*4;for(let r=0;r<3;r++){let i=f[n+r],a=we.Lerp(e.scales.mins[r],e.scales.maxs[r],i/255),s=Math.exp(a);o[t*8+3+r]=s}}}let p=t[4].bits;if(e.version===2){if(!e.sh0.codebook)throw Error(`Missing codebook in SOG version 2 sh0 data.`);for(let t=0;t<r;t++){let n=t*4;for(let r=0;r<3;r++){let i=.5+e.sh0.codebook[p[n+r]]*mv;s[t*32+24+r]=Math.max(0,Math.min(255,Math.round(255*i)))}s[t*32+24+3]=p[n+3]}}else{if(!Array.isArray(e.sh0.mins)||!Array.isArray(e.sh0.maxs))throw Error(`Missing arrays in SOG sh0 data.`);for(let t=0;t<r;t++){let n=t*4;for(let r=0;r<4;r++){let i=e.sh0.mins[r],a=e.sh0.maxs[r],o=p[n+r],c=we.Lerp(i,a,o/255),l;l=r<3?.5+c*mv:1/(1+Math.exp(-c)),s[t*32+24+r]=Math.max(0,Math.min(255,Math.round(255*l)))}}}let m=e=>(e/255-.5)*2/Math.SQRT2,h=t[3].bits;for(let e=0;e<r;e++){let t=h[e*4+0],n=h[e*4+1],r=h[e*4+2],i=h[e*4+3],a=m(t),o=m(n),s=m(r),l=i-252,u=a*a+o*o+s*s,d=Math.sqrt(Math.max(0,1-u)),f;switch(l){case 0:f=[d,a,o,s];break;case 1:f=[a,d,o,s];break;case 2:f=[a,o,d,s];break;case 3:f=[a,o,s,d];break;default:throw Error(`Invalid quaternion mode`)}c[e*32+28+0]=f[0]*127.5+127.5,c[e*32+28+1]=f[1]*127.5+127.5,c[e*32+28+2]=f[2]*127.5+127.5,c[e*32+28+3]=f[3]*127.5+127.5}if(e.shN){let a=e.shN.bands?(e.shN.bands+1)**2-1:e.shN.shape[1]/3,o=e.shN.bands!==void 0&&e.shN.bands!==null?e.shN.bands:Math.round(Math.sqrt(a+1)-1),s=t[5].bits,c=t[6].bits,l=t[5].width,u=a*3,d=Math.ceil(u/16),f=n.getEngine().getCaps().maxTextureSize,p=Math.ceil(r/f),m=Ht(d,p*f*4*4);if(e.version===2){if(!e.shN.codebook)throw Error(`Missing codebook in SOG version 2 shN data.`);for(let t=0;t<r;t++){let n=c[t*4+0]+(c[t*4+1]<<8),r=n%64*a,i=Math.floor(n/64);for(let n=0;n<a;n++)for(let a=0;a<3;a++){let o=n*3+a,c=m[Math.floor(o/16)],u=o%16,d=t*16,f=e.shN.codebook[s[(r+n)*4+a+i*l*4]]*127.5+127.5;c[u+d]=Math.max(0,Math.min(255,f))}}}else for(let t=0;t<r;t++){let n=c[t*4+0]+(c[t*4+1]<<8),r=n%64*a,i=Math.floor(n/64),o=e.shN.mins,u=e.shN.maxs;for(let e=0;e<3;e++)for(let n=0;n<a/3;n++){let a=n*3+e,c=m[Math.floor(a/16)],d=a%16,f=t*16,p=we.Lerp(o,u,s[(r+n)*4+e+i*l*4]/255
10)*127.5+127.5;c[d+f]=Math.max(0,Math.min(255,p))}}return await new Promise(e=>{e({mode:0,data:i,hasVertexColors:!1,sh:m,shDegree:o})})}return await new Promise(e=>{e({mode:0,data:i,hasVertexColors:!1})})}async function _v(e,t,n){let r,i;if(e instanceof Map){i=e;let t=i.get(`meta.json`);if(!t)throw Error(`meta.json not found in files Map`);r=JSON.parse(new TextDecoder().decode(t))}else r=e;let a=[...r.means.files,...r.scales.files,...r.quats.files,...r.sh0.files];r.shN&&a.push(...r.shN.files);let o=await Promise.all(a.map(async e=>i&&i.has(e)?await hv(i.get(e),e,n.getEngine()):await hv(t,e,n.getEngine())));return await gv(r,o,n)}function vv(e,t,n,r){let i=new on(t,n,r,k.TEXTUREFORMAT_RGBA,e,!1,!1,k.TEXTURE_NEAREST_SAMPLINGMODE,k.TEXTURETYPE_UNSIGNED_BYTE);return i.wrapU=k.TEXTURE_CLAMP_ADDRESSMODE,i.wrapV=k.TEXTURE_CLAMP_ADDRESSMODE,i}function yv(e,t){return vv(e,t.bits,t.width,t.height)}async function bv(e,t,n){let r=n.getEngine();if(typeof createImageBitmap==`function`)try{let i=t.toLowerCase().endsWith(`.png`)?`image/png`:`image/webp`,a;if(typeof e==`string`){let n=await P.LoadFileAsync(e+t,!0);a=new Blob([n],{type:i})}else a=new Blob([e],{type:i});let o=await createImageBitmap(a,{premultiplyAlpha:`none`,colorSpaceConversion:`none`});try{let e=new on(null,o.width,o.height,k.TEXTUREFORMAT_RGBA,n,!1,!1,k.TEXTURE_NEAREST_SAMPLINGMODE,k.TEXTURETYPE_UNSIGNED_BYTE);e.wrapU=k.TEXTURE_CLAMP_ADDRESSMODE,e.wrapV=k.TEXTURE_CLAMP_ADDRESSMODE;let t=e.getInternalTexture();return t&&r.updateDynamicTexture(t,o,!1,!1),e}finally{o.close()}}catch{}return yv(n,await hv(e,t,r))}function xv(e,t,n,r){let i=e=>Math.sign(e)*(Math.exp(Math.abs(e))-1);if(!Array.isArray(e.means.mins)||!Array.isArray(e.means.maxs))throw Error(`Missing arrays in SOG data.`);let a=new Float32Array(r*4);for(let o=0;o<r;o++){let r=o*4;for(let s=0;s<3;s++){let c=n[r+s]<<8|t[r+s],l=we.Lerp(e.means.mins[s],e.means.maxs[s],c/65535);a[o*4+s]=i(l)}a[o*4+3]=1}return a}
10async function Sv(e,t,n,r=!0,i,a){let o,s;if(e instanceof Map){s=e;let t=s.get(`meta.json`);if(!t)throw Error(`meta.json not found in files Map`);o=JSON.parse(new TextDecoder().decode(t))}else o=e;let c=async e=>s&&s.has(e)?await hv(s.get(e),e,n.getEngine()):i?await hv(new Uint8Array(await i.loadFileAsync(t+e,a)),e,n.getEngine()):await hv(t,e,n.getEngine()),l=async e=>s&&s.has(e)?await bv(s.get(e),e,n):i?await bv(new Uint8Array(await i.loadFileAsync(t+e,a)),e,n):await bv(t,e,n),u=[...o.scales.files,...o.quats.files,...o.sh0.files,...o.shN?.files??[]],d,f,p,m,h=null,g;if(r){let[e,t]=await Promise.all([Promise.all(o.means.files.map(c)),Promise.all(u.map(l))]);h=[e[0],e[1]],g=t,d=yv(n,e[0]),f=yv(n,e[1]),p=e[0].width,m=e[0].height}else{let[e,t]=await Promise.all([Promise.all(o.means.files.map(l)),Promise.all(u.map(l))]);g=t,d=e[0],f=e[1];let n=d.getSize();p=n.width,m=n.height}let _=o.count??o.means.shape[0],v=p*m;if(v<_)throw Error(`SOG texture contains ${v} texels, but metadata references ${_} splats.`);let y=g[0],b=g[1],x=g[2],S,C,w=0,T=0;o.shN&&g.length>=5&&(S=g[3],C=g[4],w=o.shN.bands?(o.shN.bands+1)**2-1:o.shN.shape[1]/3,T=o.shN.bands??Math.round(Math.sqrt(w+1)-1));let E;if(o.version===2){let e=new Float32Array(768);o.scales.codebook&&e.set(o.scales.codebook.slice(0,256),0),o.sh0.codebook&&e.set(o.sh0.codebook.slice(0,256),256),o.shN?.codebook&&e.set(o.shN.codebook.slice(0,256),512),E=new on(e,768,1,k.TEXTUREFORMAT_R,n,!1,!1,k.TEXTURE_NEAREST_SAMPLINGMODE,k.TEXTURETYPE_FLOAT),E.wrapU=k.TEXTURE_CLAMP_ADDRESSMODE,E.wrapV=k.TEXTURE_CLAMP_ADDRESSMODE}let D=o.means.mins,ee=o.means.maxs,te={version:o.version===2?2:1,splatCount:_,shDegree:T,meansTextureL:d,meansTextureU:f,scalesTexture:y,quatsTexture:b,sh0Texture:x,shCentroidsTexture:S,shLabelsTexture:C,codebookTexture:E,meansMin:[D[0],D[1],D[2]],meansMax:[ee[0],ee[1],ee[2]],scalesMin:Array.isArray(o.scales.mins)?[o.scales.mins[0],o.scales.mins[1],o.scales.mins[2]]:void 0,scalesMax:Array.isArray(o.scales.maxs)?[o.scales.maxs[0],o.scales.maxs[1],o.scales.maxs[2]]:void 0,sh0Min:Array.isArray(o.sh0.mins)?[o.sh0.mins[0],o.sh0.mins[1],o.sh0.mins[2],o.sh0.mins[3]]:void 0,sh0Max:Array.isArray(o.sh0.maxs)?[o.sh0.maxs[0],o.sh0.maxs[1],o.sh0.maxs[2],o.sh0.maxs[3]]:void 0,shnMin:typeof o.shN?.mins==`number`?o.shN.mins:void 0,shnMax:typeof o.shN?.maxs==`number`?o.shN.maxs:void 0,shCoeffCount:w,positions:h?xv(o,h[0].bits,h[1].bits,_):new Float32Array};return{mode:0,data:new ArrayBuffer(0),hasVertexColors:!1,shDegree:T,sogTextures:te}}oe(),gr();var Cv=`precision highp float; 11attribute vec3 position; 12void main() { 13 gl_Position = vec4(position.xy, 0.0, 1.0); 14} 15`,wv=`precision highp float; 16precision highp int; 17 18uniform sampler2D sogMeansLTex; 19uniform sampler2D sogMeansUTex; 20uniform sampler2D sogScalesTex; 21uniform sampler2D sogQuatsTex; 22uniform sampler2D sogSh0Tex; 23uniform sampler2D sogCodebookTex; 24 25uniform vec3 sogMeansMin; 26uniform vec3 sogMeansMax; 27uniform vec3 sogScalesMin; 28uniform vec3 sogScalesMax; 29uniform vec4 sogSh0Min; 30uniform vec4 sogSh0Max; 31uniform int uVersion; 32uniform int uOffset; 33uniform int uCount; 34uniform int uDestWidth; 35uniform int uSrcWidth; 36 37layout(location = 0) out vec4 glFragData[4]; 38 39mat3 transposeM(mat3 m) { 40 return mat3(m[0][0], m[1][0], m[2][0], m[0][1], m[1][1], m[2][1], m[0][2], m[1][2], m[2][2]); 41} 42 43void main() { 44 ivec2 p = ivec2(gl_FragCoord.xy); 45 int global = p.y * uDestWidth + p.x; 46 if (global < uOffset || global >= uOffset + uCount) { 47 discard; 48 } 49 int k = global - uOffset; 50 ivec2 src = ivec2(k - (k / uSrcWidth) * uSrcWidth, k / uSrcWidth); 51 52 vec3 mL = texelFetch(sogMeansLTex, src, 0).xyz; 53 vec3 mU = texelFetch(sogMeansUTex, src, 0).xyz; 54 vec3 sRaw = texelFetch(sogScalesTex, src, 0).xyz; 55 vec4 qRaw = texelFetch(sogQuatsTex, src, 0); 56 vec4 c0 = texelFetch(sogSh0Tex, src, 0); 57 58 // Position: q16 = (u<<8)|l normalized; n = lerp(min,max,q16); pos = sign(n)*(exp(|n|)-1) 59 vec3 q16 = (mU * 256.0 + mL) * (255.0 / 65535.0); 60 vec3 nPos = mix(sogMeansMin, sogMeansMax, q16); 61 vec3 center = sign(nPos) * (exp(abs(nPos)) - vec3(1.0)); 62 63 // Scale (v1: lerp+exp ; v2: codebook lookup) 64 vec3 splatScale; 65 if (uVersion == 2) { 66 vec3 sIdx = floor(sRaw * 255.0 + 0.5); 67 splatScale.x = exp(texelFetch(sogCodebookTex, ivec2(int(sIdx.x), 0), 0).r); 68 splatScale.y = exp(texelFetch(sogCodebookTex, ivec2(int(sIdx.y), 0), 0).r); 69 splatScale.z = exp(texelFetch(sogCodebookTex, ivec2(int(sIdx.z), 0), 0).r); 70 } else { 71 splatScale = exp(mix(sogScalesMin, sogScalesMax, sRaw)); 72 } 73 74 // Quaternion (largest-omitted, mode in alpha as 252 + omitted-index) 75 const float invSqrt2 = 0.70710678118; 76 vec3 qabc = (qRaw.xyz - vec3(0.5)) * 2.0 * invSqrt2; 77 int qMode = int(qRaw.w * 255.0 + 0.5) - 252; 78 float qd = sqrt(max(0.0, 1.0 - dot(qabc, qabc))); 79 vec4 quat; 80 if (qMode == 0) { 81 quat = vec4(qd, qabc.x, qabc.y, qabc.z); 82 } else if (qMode == 1) { 83 quat = vec4(qabc.x, qd, qabc.y, qabc.z); 84 } else if (qMode == 2) { 85 quat = vec4(qabc.x, qabc.y, qd, qabc.z); 86 } else { 87 quat = vec4(qabc.x, qabc.y, qabc.z, qd); 88 } 89
90 float qw = quat.x, qx = quat.y, qy = quat.z, qz = quat.w; 91 mat3 R = mat3( 92 1.0 - 2.0 * (qy * qy + qz * qz), 2.0 * (qx * qy + qw * qz), 2.0 * (qx * qz - qw * qy), 93 2.0 * (qx * qy - qw * qz), 1.0 - 2.0 * (qx * qx + qz * qz), 2.0 * (qy * qz + qw * qx), 94 2.0 * (qx * qz + qw * qy), 2.0 * (qy * qz - qw * qx), 1.0 - 2.0 * (qx * qx + qy * qy) 95 ); 96 mat3 S2 = mat3( 97 4.0 * splatScale.x * splatScale.x, 0.0, 0.0, 98 0.0, 4.0 * splatScale.y * splatScale.y, 0.0, 99 0.0, 0.0, 4.0 * splatScale.z * splatScale.z 100 ); 101 mat3 Sigma = R * S2 * transposeM(R); 102 103 // Color (sh0) 104 const float SH_C0 = 0.28209479177387814; 105 vec3 colRgb; 106 float colA; 107 if (uVersion == 2) { 108 vec3 c3; 109 c3.x = texelFetch(sogCodebookTex, ivec2(256 + int(c0.x * 255.0 + 0.5), 0), 0).r; 110 c3.y = texelFetch(sogCodebookTex, ivec2(256 + int(c0.y * 255.0 + 0.5), 0), 0).r; 111 c3.z = texelFetch(sogCodebookTex, ivec2(256 + int(c0.z * 255.0 + 0.5), 0), 0).r; 112 colRgb = vec3(0.5) + c3 * SH_C0; 113 colA = c0.w; 114 } else { 115 vec4 cLerp = mix(sogSh0Min, sogSh0Max, c0); 116 colRgb = vec3(0.5) + cLerp.xyz * SH_C0; 117 colA = 1.0 / (1.0 + exp(-cLerp.w)); 118 } 119 120 glFragData[0] = vec4(center, 1.0); 121 glFragData[1] = vec4(Sigma[0][0], Sigma[0][1], Sigma[0][2], Sigma[1][1]); 122 glFragData[2] = vec4(Sigma[1][2], Sigma[2][2], 0.0, 0.0); 123 glFragData[3] = vec4(colRgb, colA); 124} 125`,Tv=` 126attribute position : vec3<f32>; 127@vertex 128fn main(input : VertexInputs) -> FragmentInputs { 129 vertexOutputs.position = vec4<f32>(input.position.xy, 0.0, 1.0); 130} 131`,Ev=` 132var sogMeansLTexSampler : sampler; 133var sogMeansLTex : texture_2d<f32>; 134var sogMeansUTexSampler : sampler; 135var sogMeansUTex : texture_2d<f32>; 136var sogScalesTexSampler : sampler; 137var sogScalesTex : texture_2d<f32>; 138var sogQuatsTexSampler : sampler; 139var sogQuatsTex : texture_2d<f32>; 140var sogSh0TexSampler : sampler; 141var sogSh0Tex : texture_2d<f32>; 142var sogCodebookTexSampler : sampler; 143var sogCodebookTex : texture_2d<f32>; 144 145uniform sogMeansMin : vec3<f32>; 146uniform sogMeansMax : vec3<f32>; 147uniform sogScalesMin : vec3<f32>; 148uniform sogScalesMax : vec3<f32>; 149uniform sogSh0Min : vec4<f32>; 150uniform sogSh0Max : vec4<f32>; 151uniform uVersion : i32; 152uniform uOffset : i32; 153uniform uCount : i32; 154uniform uDestWidth : i32; 155uniform uSrcWidth : i32; 156 157@fragment 158fn main(input : FragmentInputs) -> FragmentOutputs { 159 let p : vec2<i32> = vec2<i32>(i32(fragmentInputs.position.x), i32(fragmentInputs.position.y)); 160 let global : i32 = p.y * uniforms.uDestWidth + p.x; 161 if (global < uniforms.uOffset || global >= uniforms.uOffset + uniforms.uCount) { 162 discard; 163 } 164 let k : i32 = global - uniforms.uOffset; 165 let src : vec2<i32> = vec2<i32>(k - (k / uniforms.uSrcWidth) * uniforms.uSrcWidth, k / uniforms.uSrcWidth); 166 167 let mL : vec3<f32> = textureLoad(sogMeansLTex, src, 0).xyz; 168 let mU : vec3<f32> = textureLoad(sogMeansUTex, src, 0).xyz; 169 let sRaw : vec3<f32> = textureLoad(sogScalesTex, src, 0).xyz; 170 let qRaw : vec4<f32> = textureLoad(sogQuatsTex, src, 0); 171 let c0 : vec4<f32> = textureLoad(sogSh0Tex, src, 0); 172 173 let q16 : vec3<f32> = (mU * 256.0 + mL) * (255.0 / 65535.0); 174 let nPos : vec3<f32> = mix(uniforms.sogMeansMin, uniforms.sogMeansMax, q16); 175 let center : vec3<f32> = sign(nPos) * (exp(abs(nPos)) - vec3<f32>(1.0)); 176 177 var splatScale : vec3<f32>; 178 if (uniforms.uVersion == 2) { 179 let sIdx : vec3<f32> = floor(sRaw * 255.0 + 0.5); 180 splatScale.x = exp(textureLoad(sogCodebookTex, vec2<i32>(i32(sIdx.x), 0), 0).r); 181 splatScale.y = exp(textureLoad(sogCodebookTex, vec2<i32>(i32(sIdx.y), 0), 0).r); 182 splatScale.z = exp(textureLoad(sogCodebookTex, vec2<i32>(i32(sIdx.z), 0), 0).r); 183 } else { 184 splatScale = exp(mix(uniforms.sogScalesMin, uniforms.sogScalesMax, sRaw)); 185 } 186 187 let invSqrt2 : f32 = 0.70710678118; 188 let qabc : vec3<f32> = (qRaw.xyz - vec3<f32>(0.5)) * 2.0 * invSqrt2; 189 let qMode : i32 = i32(qRaw.w * 255.0 + 0.5) - 252; 190 let qd : f32 = sqrt(max(0.0, 1.0 - dot(qabc, qabc))); 191 var quat : vec4<f32>; 192 if (qMode == 0) { 193 quat = vec4<f32>(qd, qabc.x, qabc.y, qabc.z); 194 } else if (qMode == 1) { 195 quat = vec4<f32>(qabc.x, qd, qabc.y, qabc.z); 196 } else if (qMode == 2) { 197 quat = vec4<f32>(qabc.x, qabc.y, qd, qabc.z); 198 } else { 199 quat = vec4<f32>(qabc.x, qabc.y, qabc.z, qd); 200 } 201 202 let qw : f32 = quat.x; 203 let qx : f32 = quat.y; 204 let qy : f32 = quat.z;
205 let qz : f32 = quat.w; 206 let R : mat3x3<f32> = mat3x3<f32>( 207 1.0 - 2.0 * (qy * qy + qz * qz), 2.0 * (qx * qy + qw * qz), 2.0 * (qx * qz - qw * qy), 208 2.0 * (qx * qy - qw * qz), 1.0 - 2.0 * (qx * qx + qz * qz), 2.0 * (qy * qz + qw * qx), 209 2.0 * (qx * qz + qw * qy), 2.0 * (qy * qz - qw * qx), 1.0 - 2.0 * (qx * qx + qy * qy) 210 ); 211 let S2 : mat3x3<f32> = mat3x3<f32>( 212 4.0 * splatScale.x * splatScale.x, 0.0, 0.0, 213 0.0, 4.0 * splatScale.y * splatScale.y, 0.0, 214 0.0, 0.0, 4.0 * splatScale.z * splatScale.z 215 ); 216 let Sigma : mat3x3<f32> = R * S2 * transpose(R); 217 218 let SH_C0 : f32 = 0.28209479177387814; 219 var colRgb : vec3<f32>; 220 var colA : f32; 221 if (uniforms.uVersion == 2) { 222 var c3 : vec3<f32>; 223 c3.x = textureLoad(sogCodebookTex, vec2<i32>(256 + i32(c0.x * 255.0 + 0.5), 0), 0).r; 224 c3.y = textureLoad(sogCodebookTex, vec2<i32>(256 + i32(c0.y * 255.0 + 0.5), 0), 0).r; 225 c3.z = textureLoad(sogCodebookTex, vec2<i32>(256 + i32(c0.z * 255.0 + 0.5), 0), 0).r; 226 colRgb = vec3<f32>(0.5) + c3 * SH_C0; 227 colA = c0.w; 228 } else { 229 let cLerp : vec4<f32> = mix(uniforms.sogSh0Min, uniforms.sogSh0Max, c0); 230 colRgb = vec3<f32>(0.5) + cLerp.xyz * SH_C0; 231 colA = 1.0 / (1.0 + exp(-cLerp.w)); 232 } 233 234 fragmentOutputs.fragData0 = vec4<f32>(center, 1.0); 235 fragmentOutputs.fragData1 = vec4<f32>(Sigma[0][0], Sigma[0][1], Sigma[0][2], Sigma[1][1]); 236 fragmentOutputs.fragData2 = vec4<f32>(Sigma[1][2], Sigma[2][2], 0.0, 0.0); 237 fragmentOutputs.fragData3 = vec4<f32>(colRgb, colA); 238} 239`,Dv=`gsSogRotDecodeToWorkBuffer`,Ov=`precision highp float; 240precision highp int; 241 242uniform sampler2D sogScalesTex; 243uniform sampler2D sogQuatsTex; 244uniform sampler2D sogCodebookTex; 245 246uniform vec3 sogScalesMin; 247uniform vec3 sogScalesMax; 248uniform int uVersion; 249uniform int uOffset; 250uniform int uCount; 251uniform int uDestWidth; 252uniform int uSrcWidth; 253 254layout(location = 0) out vec4 glFragData[3]; 255 256void main() { 257 ivec2 p = ivec2(gl_FragCoord.xy); 258 int global = p.y * uDestWidth + p.x; 259 if (global < uOffset || global >= uOffset + uCount) { 260 discard; 261 } 262 int k = global - uOffset; 263 ivec2 src = ivec2(k - (k / uSrcWidth) * uSrcWidth, k / uSrcWidth); 264 265 vec3 sRaw = texelFetch(sogScalesTex, src, 0).xyz; 266 vec4 qRaw = texelFetch(sogQuatsTex, src, 0); 267 268 vec3 splatScale; 269 if (uVersion == 2) { 270 vec3 sIdx = floor(sRaw * 255.0 + 0.5); 271 splatScale.x = exp(texelFetch(sogCodebookTex, ivec2(int(sIdx.x), 0), 0).r); 272 splatScale.y = exp(texelFetch(sogCodebookTex, ivec2(int(sIdx.y), 0), 0).r); 273 splatScale.z = exp(texelFetch(sogCodebookTex, ivec2(int(sIdx.z), 0), 0).r); 274 } else { 275 splatScale = exp(mix(sogScalesMin, sogScalesMax, sRaw)); 276 } 277 278 const float invSqrt2 = 0.70710678118; 279 vec3 qabc = (qRaw.xyz - vec3(0.5)) * 2.0 * invSqrt2; 280 int qMode = int(qRaw.w * 255.0 + 0.5) - 252; 281 float qd = sqrt(max(0.0, 1.0 - dot(qabc, qabc))); 282 vec4 quat; 283 if (qMode == 0) { 284 quat = vec4(qd, qabc.x, qabc.y, qabc.z); 285 } else if (qMode == 1) { 286 quat = vec4(qabc.x, qd, qabc.y, qabc.z); 287 } else if (qMode == 2) { 288 quat = vec4(qabc.x, qabc.y, qd, qabc.z); 289 } else { 290 quat = vec4(qabc.x, qabc.y, qabc.z, qd); 291 } 292 293 float qw = quat.x, qx = quat.y, qy = quat.z, qz = quat.w; 294 mat3 R = mat3( 295 1.0 - 2.0 * (qy * qy + qz * qz), 2.0 * (qx * qy + qw * qz), 2.0 * (qx * qz - qw * qy), 296 2.0 * (qx * qy - qw * qz), 1.0 - 2.0 * (qx * qx + qz * qz), 2.0 * (qy * qz + qw * qx), 297 2.0 * (qx * qz + qw * qy), 2.0 * (qy * qz - qw * qx), 1.0 - 2.0 * (qx * qx + qy * qy) 298 ); 299 300 glFragData[0] = vec4(R[0], R[1].x); 301 glFragData[1] = vec4(R[1].y, R[1].z, R[2].x, R[2].y); 302 glFragData[2] = vec4(R[2].z, 2.0 * splatScale.x, 2.0 * splatScale.y, 2.0 *
302splatScale.z); 303} 304`,kv=` 305var sogScalesTexSampler : sampler; 306var sogScalesTex : texture_2d<f32>; 307var sogQuatsTexSampler : sampler; 308var sogQuatsTex : texture_2d<f32>; 309var sogCodebookTexSampler : sampler; 310var sogCodebookTex : texture_2d<f32>; 311 312uniform sogScalesMin : vec3<f32>; 313uniform sogScalesMax : vec3<f32>; 314uniform uVersion : i32; 315uniform uOffset : i32; 316uniform uCount : i32; 317uniform uDestWidth : i32; 318uniform uSrcWidth : i32; 319 320@fragment 321fn main(input : FragmentInputs) -> FragmentOutputs { 322 let p : vec2<i32> = vec2<i32>(i32(fragmentInputs.position.x), i32(fragmentInputs.position.y)); 323 let global : i32 = p.y * uniforms.uDestWidth + p.x; 324 if (global < uniforms.uOffset || global >= uniforms.uOffset + uniforms.uCount) { 325 discard; 326 } 327 let k : i32 = global - uniforms.uOffset; 328 let src : vec2<i32> = vec2<i32>(k - (k / uniforms.uSrcWidth) * uniforms.uSrcWidth, k / uniforms.uSrcWidth); 329 330 let sRaw : vec3<f32> = textureLoad(sogScalesTex, src, 0).xyz; 331 let qRaw : vec4<f32> = textureLoad(sogQuatsTex, src, 0); 332 333 var splatScale : vec3<f32>; 334 if (uniforms.uVersion == 2) { 335 let sIdx : vec3<f32> = floor(sRaw * 255.0 + 0.5); 336 splatScale.x = exp(textureLoad(sogCodebookTex, vec2<i32>(i32(sIdx.x), 0), 0).r); 337 splatScale.y = exp(textureLoad(sogCodebookTex, vec2<i32>(i32(sIdx.y), 0), 0).r); 338 splatScale.z = exp(textureLoad(sogCodebookTex, vec2<i32>(i32(sIdx.z), 0), 0).r); 339 } else { 340 splatScale = exp(mix(uniforms.sogScalesMin, uniforms.sogScalesMax, sRaw)); 341 } 342 343 let invSqrt2 : f32 = 0.70710678118; 344 let qabc : vec3<f32> = (qRaw.xyz - vec3<f32>(0.5)) * 2.0 * invSqrt2; 345 let qMode : i32 = i32(qRaw.w * 255.0 + 0.5) - 252; 346 let qd : f32 = sqrt(max(0.0, 1.0 - dot(qabc, qabc))); 347 var quat : vec4<f32>; 348 if (qMode == 0) { 349 quat = vec4<f32>(qd, qabc.x, qabc.y, qabc.z); 350 } else if (qMode == 1) { 351 quat = vec4<f32>(qabc.x, qd, qabc.y, qabc.z); 352 } else if (qMode == 2) { 353 quat = vec4<f32>(qabc.x, qabc.y, qd, qabc.z); 354 } else { 355 quat = vec4<f32>(qabc.x, qabc.y, qabc.z, qd); 356 } 357 358 let qw : f32 = quat.x; 359 let qx : f32 = quat.y; 360 let qy : f32 = quat.z;
361 let qz : f32 = quat.w; 362 let R : mat3x3<f32> = mat3x3<f32>( 363 1.0 - 2.0 * (qy * qy + qz * qz), 2.0 * (qx * qy + qw * qz), 2.0 * (qx * qz - qw * qy), 364 2.0 * (qx * qy - qw * qz), 1.0 - 2.0 * (qx * qx + qz * qz), 2.0 * (qy * qz + qw * qx), 365 2.0 * (qx * qz + qw * qy), 2.0 * (qy * qz - qw * qx), 1.0 - 2.0 * (qx * qx + qy * qy) 366 ); 367 368 fragmentOutputs.fragData0 = vec4<f32>(R[0], R[1].x); 369 fragmentOutputs.fragData1 = vec4<f32>(R[1].y, R[1].z, R[2].x, R[2].y); 370 fragmentOutputs.fragData2 = vec4<f32>(R[2].z, 2.0 * splatScale.x, 2.0 * splatScale.y, 2.0 * splatScale.z); 371} 372`,Av=`gsSogShDecodeToWorkBuffer`,jv=`precision highp float; 373precision highp int; 374 375uniform sampler2D sogShLabelsTex; 376uniform sampler2D sogShCentroidsTex; 377uniform sampler2D sogCodebookTex; 378uniform float sogShnMin; 379uniform float sogShnMax; 380uniform int uVersion; 381uniform int uOffset; 382uniform int uCount; 383uniform int uDestWidth; 384uniform int uSrcWidth; 385uniform int uCoeffs; 386uniform int uShTextureIndex; 387 388layout(location = 0) out uvec4 outSh; 389 390void main() { 391 ivec2 p = ivec2(gl_FragCoord.xy); 392 int global = p.y * uDestWidth + p.x; 393 if (global < uOffset || global >= uOffset + uCount) { 394 discard; 395 } 396 int kLocal = global - uOffset; 397 398 // 16-bit label for this source splat (LSB in r, MSB in g), indexed over the labels texture's own width. 399 ivec2 lsz = textureSize(sogShLabelsTex, 0); 400 ivec2 lsrc = ivec2(kLocal - (kLocal / lsz.x) * lsz.x, kLocal / lsz.x); 401 vec4 labelRaw = texelFetch(sogShLabelsTex, lsrc, 0); 402 int n = int(labelRaw.r * 255.0 + 0.5) + int(labelRaw.g * 255.0 + 0.5) * 256; 403 int u = (n - (n / 64) * 64) * uCoeffs; 404 int v = n / 64; 405 406 uint packed0 = 0u; 407 uint packed1 = 0u; 408 uint packed2 = 0u; 409 uint packed3 = 0u; 410 411 for (int b = 0; b < 16; b++) { 412 int s = uShTextureIndex * 16 + b; // flat SH scalar index 413 int kc = s / 3; // higher-order coefficient (0-based) 414 int j = s - kc * 3; // channel (0=r,1=g,2=b) 415 float byteVal = 128.0; // neutral (decompose(128) ~= 0) 416 if (kc < uCoeffs) { 417 vec4 centroidRaw = texelFetch(sogShCentroidsTex, ivec2(u + kc, v), 0); 418 float ch = (j == 0) ? centroidRaw.r : ((j == 1) ? centroidRaw.g : centroidRaw.b); 419 float coeff; 420 if (uVersion == 2) { 421 int cidx = int(ch * 255.0 + 0.5); 422 coeff = texelFetch(sogCodebookTex, ivec2(512 + cidx, 0), 0).r; 423 } else { 424 coeff = mix(sogShnMin, sogShnMax, ch); 425 } 426 byteVal = clamp(coeff * 127.5 + 127.5, 0.0, 255.0); 427 } 428 uint bv = uint(byteVal + 0.5); 429 int comp = b / 4; 430 uint contrib = bv << uint((b - comp * 4) * 8); 431 if (comp == 0) { packed0 |= contrib; } 432 else if (comp == 1) { packed1 |= contrib; } 433 else if (comp == 2) { packed2 |= contrib; } 434 else { packed3 |= contrib; } 435 } 436 outSh = uvec4(packed0, packed1, packed2, packed3); 437} 438`,Mv=` 439var sogShLabelsTexSampler : sampler; 440var sogShLabelsTex : texture_2d<f32>; 441var sogShCentroidsTexSampler : sampler; 442var sogShCentroidsTex : texture_2d<f32>; 443var sogCodebookTexSampler : sampler; 444var sogCodebookTex : texture_2d<f32>; 445 446uniform sogShnMin : f32; 447uniform sogShnMax : f32; 448uniform uVersion : i32; 449uniform uOffset : i32; 450uniform uCount : i32; 451uniform uDestWidth : i32; 452uniform uSrcWidth : i32; 453uniform uCoeffs : i32; 454uniform uShTextureIndex : i32; 455 456@fragment 457fn main(input : FragmentInputs) -> FragmentOutputs { 458 let p : vec2<i32> = vec2<i32>(i32(fragmentInputs.position.x), i32(fragmentInputs.position.y)); 459 let global : i32 = p.y * uniforms.uDestWidth + p.x; 460 if (global < uniforms.uOffset || global >= uniforms.uOffset + uniforms.uCount) { 461 discard; 462 } 463 let kLocal : i32 = global - uniforms.uOffset; 464 465 let lsz : vec2<i32> = vec2<i32>(textureDimensions(sogShLabelsTex, 0)); 466 let lsrc : vec2<i32> = vec2<i32>(kLocal - (kLocal / lsz.x) * lsz.x, kLocal / lsz.x); 467 let labelRaw : vec4<f32> = textureLoad(sogShLabelsTex, lsrc, 0); 468 let n : i32 = i32(labelRaw.r * 255.0 + 0.5) + i32(labelRaw.g * 255.0 + 0.5) * 256; 469 let u : i32 = (n - (n / 64) * 64) * uniforms.uCoeffs; 470 let v : i32 = n / 64; 471 472 var packed : array<u32, 4> = array<u32, 4>(0u, 0u, 0u, 0u); 473 474 for (var b : i32 = 0; b < 16; b = b + 1) { 475 let s : i32 = uniforms.uShTextureIndex * 16 + b; 476 let kc : i32 = s / 3; 477 let j : i32 = s - kc * 3; 478 var byteVal : f32 = 128.0; 479 if (kc < uniforms.uCoeffs) { 480 let centroidRaw : vec4<f32> = textureLoad(sogShCentroidsTex, vec2<i32>(u + kc, v), 0); 481 var ch : f32 = centroidRaw.b; 482 if (j == 0) { ch = centroidRaw.r; } else if (j == 1) { ch = centroidRaw.g; } 483 var coeff : f32; 484 if (uniforms.uVersion == 2) { 485 let cidx : i32 = i32(ch * 255.0 + 0.5); 486 coeff = textureLoad(sogCodebookTex, vec2<i32>(512 + cidx, 0), 0).r; 487 } else { 488 coeff = mix(uniforms.sogShnMin, uniforms.sogShnMax, ch); 489 } 490 byteVal = clamp(coeff * 127.5 + 127.5, 0.0, 255.0); 491 } 492 let bv : u32 = u32(byteVal + 0.5); 493 let comp : i32 = b / 4; 494 packed[comp] = packed[comp] | (bv << u32((b - comp * 4) * 8)); 495 } 496 fragmentOutputs.fragData0 = vec4<u32>(packed[0], packed[1], packed[2], packed[3]); 497} 498`,Nv=`gsWorkBufferRelayout`,Pv=`precision highp float; 499precision highp int; 500 501uniform sampler2D uMapTex; 502uniform sampler2D uSrc0; 503uniform sampler2D uSrc1; 504uniform sampler2D uSrc2; 505uniform sampler2D uSrc3; 506uniform int uDstWidth; 507uniform int uSrcWidth; 508uniform int uUseMap; 509// Region-scoped relayout (hosted compound atlas), both default 0 (standalone square path unchanged): 510// uSrcBaseOffset â added to the map's (region-local) source index so pass 1 reads the correct GLOBAL atlas texel.
511// uDstBaseRow â subtracted from the atlas destination row so pass 2's identity copy reads the region-local temp. 512uniform int uSrcBaseOffset; 513uniform int uDstBaseRow; 514 515layout(location = 0) out vec4 glFragData[4]; 516 517void main() { 518 ivec2 p = ivec2(gl_FragCoord.xy); 519 int srcIdx; 520 if (uUseMap == 1) { 521 float m = texelFetch(uMapTex, p, 0).r; 522 if (m < 0.0) { 523 discard; 524 } 525 srcIdx = uSrcBaseOffset + int(m + 0.5); 526 } else { 527 srcIdx = (p.y - uDstBaseRow) * uDstWidth + p.x; 528 } 529 ivec2 s = ivec2(srcIdx - (srcIdx / uSrcWidth) * uSrcWidth, srcIdx / uSrcWidth); 530 glFragData[0] = texelFetch(uSrc0, s, 0); 531 glFragData[1] = texelFetch(uSrc1, s, 0); 532 glFragData[2] = texelFetch(uSrc2, s, 0); 533 glFragData[3] = texelFetch(uSrc3, s, 0); 534} 535`,Fv=`gsWorkBufferShCopy`,Iv=`precision highp float; 536precision highp int; 537precision highp usampler2D; 538 539uniform sampler2D uMapTex; 540uniform usampler2D uSrcSh; 541uniform int uDstWidth; 542uniform int uSrcWidth; 543uniform int uUseMap; 544uniform int uSrcBaseOffset; 545uniform int uDstBaseRow; 546 547layout(location = 0) out uvec4 outSh; 548 549void main() { 550 ivec2 p = ivec2(gl_FragCoord.xy); 551 int srcIdx; 552 if (uUseMap == 1) { 553 float m = texelFetch(uMapTex, p, 0).r; 554 if (m < 0.0) { 555 discard; 556 } 557 srcIdx = uSrcBaseOffset + int(m + 0.5); 558 } else { 559 srcIdx = (p.y - uDstBaseRow) * uDstWidth + p.x; 560 } 561 ivec2 s = ivec2(srcIdx - (srcIdx / uSrcWidth) * uSrcWidth, srcIdx / uSrcWidth); 562 outSh = texelFetch(uSrcSh, s, 0); 563} 564`,Lv=` 565var uMapTexSampler : sampler; 566var uMapTex : texture_2d<f32>; 567// Integer source sampled via textureLoad only â NO paired sampler (a sampler on a Uint texture fails WebGPU 568// validation: "None of the supported sample types (Uint)"). Mirrors the draw shader's shTexture0 declaration. 569var uSrcSh : texture_2d<u32>; 570 571uniform uDstWidth : i32; 572uniform uSrcWidth : i32; 573uniform uUseMap : i32; 574uniform uSrcBaseOffset : i32; 575uniform uDstBaseRow : i32; 576 577@fragment 578fn main(input : FragmentInputs) -> FragmentOutputs { 579 let p : vec2<i32> = vec2<i32>(i32(fragmentInputs.position.x), i32(fragmentInputs.position.y)); 580 var srcIdx : i32; 581 if (uniforms.uUseMap == 1) { 582 let m : f32 = textureLoad(uMapTex, p, 0).r; 583 if (m < 0.0) { 584 discard; 585 } 586 srcIdx = uniforms.uSrcBaseOffset + i32(m + 0.5); 587 } else { 588 srcIdx = (p.y - uniforms.uDstBaseRow) * uniforms.uDstWidth + p.x; 589 } 590 let s : vec2<i32> = vec2<i32>(srcIdx - (srcIdx / uniforms.uSrcWidth) * uniforms.uSrcWidth, srcIdx / uniforms.uSrcWidth); 591 // Wrap in an explicit vec4<u32> so the WGSL processor emits an integer fragData location (its detection keys 592 // off a literal vec4<u32>/vec4u in the assignment; a bare textureLoad(...) would default to vec4<f32>). 593 fragmentOutputs.fragData0 = vec4<u32>(textureLoad(uSrcSh, s, 0)); 594} 595`,Rv=`gsWorkBufferRotCopy`,zv=`precision highp float; 596precision highp int; 597 598uniform sampler2D uMapTex; 599uniform sampler2D uSrc0; 600uniform sampler2D uSrc1; 601uniform sampler2D uSrc2; 602uniform int uDstWidth; 603uniform int uSrcWidth; 604uniform int uUseMap; 605uniform int uSrcBaseOffset; 606uniform int uDstBaseRow; 607 608layout(location = 0) out vec4 glFragData[3]; 609 610void main() { 611 ivec2 p = ivec2(gl_FragCoord.xy); 612 int srcIdx; 613 if (uUseMap == 1) { 614 float m = texelFetch(uMapTex, p, 0).r; 615 if (m < 0.0) { 616 discard; 617 } 618 srcIdx = uSrcBaseOffset + int(m + 0.5); 619 } else { 620 srcIdx = (p.y - uDstBaseRow) * uDstWidth + p.x; 621 } 622 ivec2 s = ivec2(srcIdx - (srcIdx / uSrcWidth) * uSrcWidth, srcIdx / uSrcWidth); 623 glFragData[0] = texelFetch(uSrc0, s, 0); 624 glFragData[1] = texelFetch(uSrc1, s, 0); 625 glFragData[2] = texelFetch(uSrc2, s, 0); 626} 627`,Bv=` 628var uMapTexSampler : sampler; 629var uMapTex : texture_2d<f32>; 630var uSrc0Sampler : sampler; 631var uSrc0 : texture_2d<f32>; 632var uSrc1Sampler : sampler; 633var uSrc1 : texture_2d<f32>; 634var uSrc2Sampler : sampler; 635var uSrc2 : texture_2d<f32>; 636 637uniform uDstWidth : i32; 638uniform uSrcWidth : i32; 639uniform uUseMap : i32; 640uniform uSrcBaseOffset : i32; 641uniform uDstBaseRow : i32; 642 643@fragment 644fn main(input : FragmentInputs) -> FragmentOutputs { 645 let p : vec2<i32> = vec2<i32>(i32(fragmentInputs.position.x), i32(fragmentInputs.position.y)); 646 var srcIdx : i32; 647 if (uniforms.uUseMap == 1) { 648 let m : f32 = textureLoad(uMapTex, p, 0).r; 649 if (m < 0.0) { 650 discard; 651 } 652 srcIdx = uniforms.uSrcBaseOffset + i32(m + 0.5); 653 } else { 654 srcIdx = (p.y - uniforms.uDstBaseRow) * uniforms.uDstWidth + p.x; 655 } 656 let s : vec2<i32> = vec2<i32>(srcIdx - (srcIdx / uniforms.uSrcWidth) * uniforms.uSrcWidth, srcIdx / uniforms.uSrcWidth); 657 fragmentOutputs.fragData0 = textureLoad(uSrc0, s, 0); 658 fragmentOutputs.fragData1 = textureLoad(uSrc1, s, 0); 659 fragmentOutputs.fragData2 = textureLoad(uSrc2, s, 0); 660} 661`,Vv=` 662var uMapTexSampler : sampler; 663var uMapTex : texture_2d<f32>; 664var uSrc0Sampler : sampler; 665var uSrc0 : texture_2d<f32>; 666var uSrc1Sampler : sampler; 667var uSrc1 : texture_2d<f32>; 668var uSrc2Sampler : sampler; 669var uSrc2 : texture_2d<f32>; 670var uSrc3Sampler : sampler; 671var uSrc3 : texture_2d<f32>; 672 673uniform uDstWidth : i32; 674uniform uSrcWidth : i32; 675uniform uUseMap : i32; 676// Region-scoped relayout (hosted compound atlas), both default 0 (standalone square path unchanged). 677uniform uSrcBaseOffset : i32; 678uniform uDstBaseRow : i32; 679 680@fragment 681fn main(input : FragmentInputs) -> FragmentOutputs { 682 let p : vec2<i32> = vec2<i32>(i32(fragmentInputs.position.x), i32(fragmentInputs.position.y)); 683 var srcIdx : i32; 684 if (uniforms.uUseMap == 1) { 685 let m : f32 = textureLoad(uMapTex, p, 0).r; 686 if (m < 0.0) { 687 discard; 688 } 689 srcIdx = uniforms.uSrcBaseOffset + i32(m + 0.5); 690 } else { 691 srcIdx = (p.y - uniforms.uDstBaseRow) * uniforms.uDstWidth + p.x; 692 } 693 let s : vec2<i32> = vec2<i32>(srcIdx - (srcIdx / uniforms.uSrcWidth) * uniforms.uSrcWidth, srcIdx / uniforms.uSrcWidth); 694 fragmentOutputs.fragData0 = textureLoad(uSrc0, s, 0); 695 fragmentOutputs.fragData1 = textureLoad(uSrc1, s, 0); 696 fragmentOutputs.fragData2 = textureLoad(uSrc2, s, 0); 697 fragmentOutputs.fragData3 = textureLoad(uSrc3, s, 0); 698} 699`;yt(),Se(),re(),ct(),jn(),rr(),en();var Hv=class{get supportsAsyncCentersReadback(){let e=this._scene.getEngine();if(e.isWebGPU)return!0;let t=e;return!!t._gl&&typeof t._readPixelsAsync==`function`&&(t.webGLVersion??0)>=2}get textureSize(){return this._textureSize}get textures(){return this._mrt.textures}get shTextures(){return this._shMrts.map(e=>e.textures[0])}get rotationTextures(){return this._rotMrt?this._rotMrt.textures:[]}constructor(e,t,n,r,i){if(this._copyMaterial=null,this._relayoutMapData=null,this._relayoutMapTexture=null,this._backupMrt=null,this._disposed=!1,this._readFbo=null,this._shMrts=[],this._ownsShMrts=!1,this._shMaterial=null,this._shCopyMaterial=null,this._backupShMrts=null,this._rotMrt=null,this._ownsRotMrt=!1,this._rotMaterial=null,this._rotCopyMaterial=null,this._backupRotMrt=null,this._scene=e,this._shaderLanguage=+!!e.getEngine().isWebGPU,this._capacity=Math.max(1,t),n?(this._mrt=n.mrt,this._textureSize=n.width,this._baseOffset=n.baseOffset,this._ownsMrt=!1):(this._textureSize=Math.max(1,Math.ceil(Math.sqrt(Math.max(1,t)))),this._baseOffset=0,this._ownsMrt=!0,this._mrt=this._createMrt(`gsWorkBuffer`,!0)),r&&r.textureCount>0){if(r.externalMrts)this._shMrts=r.externalMrts.slice(0,r.textureCount),this._ownsShMrts=!1;else{for(let e=0;e<r.textureCount;e++)this._shMrts.push(this._createShMrt(`gsWorkBufferSh${e}`,!0));this._ownsShMrts=!0}this._shMaterial=this._createShMaterial()}i&&(i.externalMrt?(this._rotMrt=i.externalMrt,this._ownsRotMrt=!1):(this._rotMrt=this._createRotMrt(`gsWorkBufferRot`,!0),this._ownsRotMrt=!0),this._rotMaterial=this._createRotMaterial()),this._material=this._createMaterial(),this._quad=this._createQuad(),this._quad.material=this._material,this._ownsMrt||this.isRelayoutReady()}rebindAtlas(e){this._ownsMrt||(this._mrt=e)}rebindShAtlas(e){!this._ownsShMrts&&e&&this._shMrts.length&&(this._shMrts=e.slice(0,this._shMrts.length))}rebindRotAtlas(e){!this._ownsRotMrt&&e&&this._rotMrt&&(this._rotMrt=e)}setBaseOffset(e){this._ownsMrt||(this._baseOffset=e)}get canBackup(){return this._disposed||this._ownsMrt?!1:this.isRelayoutReady()}backupRegion(){if(this._disposed||this._ownsMrt)return;if(!this.isRelayoutReady()){A.Warn(`GaussianSplattingWorkBuffer: backup skipped because the copy shaders are not ready; streamed region data may be lost on the atlas rebuild.`);return}let e=this._textureSize,t=Math.max(1,Math.floor(this._capacity/e)),n=Math.floor(this._baseOffset/e);if(this._backupMrt||=this._createMrt(`gsAtlasBackup`,!1,e,t),this._renderRelayoutPass(this._backupMrt,this._mrt.textures,this._mrt.textures[0],0,e,e,0,-n),this._shMrts.length&&this._shCopyMaterial){this._backupShMrts||=this._shMrts.map((n,r)=>this._createShMrt(`gsShAtlasBackup${r}`,!1,e,t));for(let t=0;t<this._shMrts.length;t++)this._renderShCopyPass(this._backupShMrts[t],this._shMrts[t].textures[0],this._mrt.textures[0],0,e,e,0,-n)}this._rotMrt&&this._rotCopyMaterial&&(this._backupRotMrt||=this._createRotMrt(`gsRotAtlasBackup`,!1,e,t),this._renderRotCopyPass(this._backupRotMrt,this._rotMrt.textures,this._mrt.textures[0],0,e,e,0,-n)),this._quad.material=this._material}restoreRegion(){if(this._disposed||this._ownsMrt||!this._backupMrt||!this._copyMaterial)return;let e=this._textureSize,t=Math.max(1,Math.floor(this._capacity/e)),n=Math.floor(this._baseOffset/e),r=this._scene.getEngine();r.enableScissor(0,n,e,t);try{if(this._renderRelayoutPass(this._mrt,this._backupMrt.textures,this._backupMrt.textures[0],0,e,e,0,n),this._backupShMrts&&this._shMrts.length&&this._shCopyMaterial)for(let t=0;t<this._shMrts.length&&t<this._backupShMrts.length;t++)this._renderShCopyPass(this._shMrts[t],this._backupShMrts[t].textures[0],this._mrt.textures[0],0,e,e,0,n);this._backupRotMrt&&this._rotMrt&&this._rotCopyMaterial&&this._renderRotCopyPass(this._rotMrt,this._backupRotMrt.textures,this._mrt.textures[0],0,e,e,0,n)}finally{r.disableScissor(),this._quad.material=this._material}if(this._backupMrt.dispose(),this._backupMrt=null,this._backupShMrts){for(let e of this._backupShMrts)e.dispose();this._backupShMrts=null}this._backupRotMrt?.dispose(),this._backupRotMrt=null}_createMrt(e,t,n=this._textureSize,r=this._textureSize){let i=this._scene.getEngine()._caps.textureHalfFloatRen
699der?k.TEXTURETYPE_HALF_FLOAT:k.TEXTURETYPE_FLOAT,a=new Oe(e,{width:n,height:r},4,this._scene,{types:[k.TEXTURETYPE_FLOAT,i,i,k.TEXTURETYPE_UNSIGNED_BYTE],samplingModes:[k.TEXTURE_NEAREST_SAMPLINGMODE,k.TEXTURE_NEAREST_SAMPLINGMODE,k.TEXTURE_NEAREST_SAMPLINGMODE,k.TEXTURE_NEAREST_SAMPLINGMODE],formats:[k.TEXTUREFORMAT_RGBA,k.TEXTUREFORMAT_RGBA,k.TEXTUREFORMAT_RGBA,k.TEXTUREFORMAT_RGBA],generateDepthBuffer:!1,generateDepthTexture:!1,generateMipMaps:!1},[`${e}Centers`,`${e}CovA`,`${e}CovB`,`${e}Colors`]);return a.clearColor=new F(0,0,0,0),a.renderList=[],t&&a.onClearObservable.add(()=>{}),a}_createShMrt(e,t,n=this._textureSize,r=this._textureSize){let i=new Oe(e,{width:n,height:r},1,this._scene,{types:[k.TEXTURETYPE_UNSIGNED_INTEGER],formats:[k.TEXTUREFORMAT_RGBA_INTEGER],samplingModes:[k.TEXTURE_NEAREST_SAMPLINGMODE],generateDepthBuffer:!1,generateDepthTexture:!1,generateMipMaps:!1},[e]);return i.clearColor=new F(0,0,0,0),i.renderList=[],t&&i.onClearObservable.add(()=>{}),i}_createRotMrt(e,t,n=this._textureSize,r=this._textureSize){let i=this._scene.getEngine()._caps.textureHalfFloatRender?k.TEXTURETYPE_HALF_FLOAT:k.TEXTURETYPE_FLOAT,a=new Oe(e,{width:n,height:r},3,this._scene,{types:[i,i,i],formats:[k.TEXTUREFORMAT_RGBA,k.TEXTUREFORMAT_RGBA,k.TEXTUREFORMAT_RGBA],samplingModes:[k.TEXTURE_NEAREST_SAMPLINGMODE,k.TEXTURE_NEAREST_SAMPLINGMODE,k.TEXTURE_NEAREST_SAMPLINGMODE],generateDepthBuffer:!1,generateDepthTexture:!1,generateMipMaps:!1},[`${e}A`,`${e}B`,`${e}Scale`]);return a.clearColor=new F(0,0,0,0),a.renderList=[],t&&a.onClearObservable.add(()=>{}),a}async decodeAsync(e,t){if(this._disposed)return;this._applyPack(e);let n=this._shMaterial!==null&&this._shMrts.length>0;n&&this._applyShPack(e);let r=this._rotMaterial!==null&&this._rotMrt!==null;r&&this._applyRotPack(e),await new Promise(i=>{let a=()=>{if(this._disposed){i();return}if(!this._material.isReady(this._quad)||n&&!this._shMaterial.isReady(this._quad)||r&&!this._rotMaterial.isReady(this._quad)){this._scene.onBeforeRenderObservable.addOnce(a);return}let o=this._textureSize,s=this._baseOffset+t;this._material.setInt(`uOffset`,s),n&&this._shMaterial.setInt(`uOffset`,s),r&&this._rotMaterial.setInt(`uOffset`,s);let c=Math.floor(s/o),l=Math.max(1,Math.ceil((s+e.splatCount)/o)-c),u=this._scene.getEngine();u.enableScissor(0,c,o,l);try{if(this._quad.material=this._material,this._mrt.renderList=[this._quad],this._mrt.render(),n){for(let e=0;e<this._shMrts.length;e++)this._shMaterial.setInt(`uShTextureIndex`,e),this._quad.material=this._shMaterial,this._shMrts[e].renderList=[this._quad],this._shMrts[e].render();this._quad.material=this._material}r&&(this._quad.material=this._rotMaterial,this._rotMrt.renderList=[this._quad],this._rotMrt.render(),this._quad.material=this._material)}finally{u.disableScissor()}i()};this._scene.onBeforeRenderObservable.addOnce(a)})}isRelayoutReady(){if(this._disposed)return!1;this._copyMaterial||=this._createCopyMaterial(),this._shMrts.length&&!this._shCopyMaterial&&(this._shCopyMaterial=this._createShCopyMaterial()),this._rotMrt&&!this._rotCopyMaterial&&(this._rotCopyMaterial=this._createRotCopyMaterial()),this._bindCopyMaterialsToAtlas();let e=this._shMrts.length===0||this._shCopyMaterial!==null&&this._shCopyMaterial.isReady(this._quad),t=!this._rotMrt||this._rotCopyMaterial!==null&&this._rotCopyMaterial.isReady(this._quad);return this._copyMaterial.isReady(this._quad)&&e&&t}_bindCopyMaterialsToAtlas(){let e=this._mrt.textures;if(this._copyMaterial&&(this._copyMaterial.setTexture(`uMapTex`,e[0]),this._copyMaterial.setTexture(`uSrc0`,e[0]),this._copyMaterial.setTexture(`uSrc1`,e[1]),this._copyMaterial.setTexture(`uSrc2`,e[2]),this._copyMaterial.setTexture(`uSrc3`,e[3])),this._shCopyMaterial&&this._shMrts.length&&(this._shCopyMaterial.setTexture(`uMapTex`,e[0]),this._shCopyMaterial.setTexture(`uSrcSh`,this._shMrts[0].textures[0])),this._rotCopyMaterial&&this._rotMrt){let t=this._rotMrt.textures;this._rotCopyMaterial.setTexture(`uMapTex`,e[0]),this._rotCopyMaterial.setTexture(`uSrc0`,t[0]),this._rotCopyMaterial.setTexture(`uSrc1`,t[1]),this._rotCopyMaterial.setTexture(`uSrc2`,t[2])}}relayoutSync(e){if(this._disposed||!this._copyMaterial)return;let t=this._textureSize,n=t,r=this._ownsMrt?t:Math.max(1,Math.floor(this._capacity/t));this._relayoutMapData||=new Float32Array(n*r);let i=this._relayoutMapData;i.fill(-1),i.set(e.subarray(0,Math.min(e.length,i.length))),this._relayoutMapTexture?this._relayoutMapTexture.update(i):this._relayoutMapTexture=new on(i,n,r,k.TEXTUREFORMAT_R,this._scene,!1,!1,k.TEXTURE_NEAREST_SAMPL
699INGMODE,k.TEXTURETYPE_FLOAT);let a=this._relayoutMapTexture;if(this._ownsMrt){let e=this._createMrt(`gsRelayoutTemp`,!1);try{this._renderRelayoutPass(e,this._mrt.textures,a,1),this._renderRelayoutPass(this._mrt,e.textures,a,0)}finally{e.dispose()}if(this._shMrts.length&&this._shCopyMaterial)for(let e=0;e<this._shMrts.length;e++){let t=this._createShMrt(`gsShRelayoutTemp`,!1);try{this._renderShCopyPass(t,this._shMrts[e].textures[0],a,1),this._renderShCopyPass(this._shMrts[e],t.textures[0],a,0)}finally{t.dispose()}}if(this._rotMrt&&this._rotCopyMaterial){let e=this._createRotMrt(`gsRotRelayoutTemp`,!1);try{this._renderRotCopyPass(e,this._rotMrt.textures,a,1),this._renderRotCopyPass(this._rotMrt,e.textures,a,0)}finally{e.dispose()}}this._quad.material=this._material;return}let o=Math.floor(this._baseOffset/t),s=r,c=this._scene.getEngine(),l=this._createMrt(`gsRelayoutTemp`,!1,t,s),u=this._shMrts.length&&this._shCopyMaterial?this._shMrts.map((e,n)=>this._createShMrt(`gsShRelayoutTemp${n}`,!1,t,s)):[],d=this._rotMrt&&this._rotCopyMaterial?this._createRotMrt(`gsRotRelayoutTemp`,!1,t,s):null;try{this._renderRelayoutPass(l,this._mrt.textures,a,1,t,t,this._baseOffset,0);for(let e=0;e<u.length;e++)this._renderShCopyPass(u[e],this._shMrts[e].textures[0],a,1,t,t,this._baseOffset,0);d&&this._renderRotCopyPass(d,this._rotMrt.textures,a,1,t,t,this._baseOffset,0),c.enableScissor(0,o,t,s);try{this._renderRelayoutPass(this._mrt,l.textures,a,0,t,t,0,o);for(let e=0;e<u.length;e++)this._renderShCopyPass(this._shMrts[e],u[e].textures[0],a,0,t,t,0,o);d&&this._renderRotCopyPass(this._rotMrt,d.textures,a,0,t,t,0,o)}finally{c.disableScissor()}}finally{l.dispose();for(let e of u)e.dispose();d?.dispose(),this._quad.material=this._material}}_renderRelayoutPass(e,t,n,r,i=this._textureSize,a=this._textureSize,o=0,s=0){let c=this._copyMaterial;c.setTexture(`uMapTex`,n),c.setTexture(`uSrc0`,t[0]),c.setTexture(`uSrc1`,t[1]),c.setTexture(`uSrc2`,t[2]),c.setTexture(`uSrc3`,t[3]),c.setInt(`uDstWidth`,i),c.setInt(`uSrcWidth`,a),c.setInt(`uUseMap`,r),c.setInt(`uSrcBaseOffset`,o),c.setInt(`uDstBaseRow`,s),this._quad.material=c,e.renderList=[this._quad],e.render()}_createCopyMaterial(){let e=this._shaderLanguage===1,t=new ie(Nv,this._scene,{vertexSource:e?Tv:Cv,fragmentSource:e?Vv:Pv},{attributes:[`position`],uniforms:[`uDstWidth`,`uSrcWidth`,`uUseMap`,`uSrcBaseOffset`,`uDstBaseRow`],samplers:[`uMapTex`,`uSrc0`,`uSrc1`,`uSrc2`,`uSrc3`],shaderLanguage:this._shaderLanguage});return t.backFaceCulling=!1,t.disableDepthWrite=!0,t}_renderShCopyPass(e,t,n,r,i=this._textureSize,a=this._textureSize,o=0,s=0){let c=this._shCopyMaterial;c.setTexture(`uMapTex`,n),c.setTexture(`uSrcSh`,t),c.setInt(`uDstWidth`,i),c.setInt(`uSrcWidth`,a),c.setInt(`uUseMap`,r),c.setInt(`uSrcBaseOffset`,o),c.setInt(`uDstBaseRow`,s),this._quad.material=c,e.renderList=[this._quad],e.render()}_createShCopyMaterial(){let e=this._shaderLanguage===1,t=new ie(Fv,this._scene,{vertexSource:e?Tv:Cv,fragmentSource:e?Lv:Iv},{attributes:[`position`],uniforms:[`uDstWidth`,`uSrcWidth`,`uUseMap`,`uSrcBaseOffset`,`uDstBaseRow`],samplers:[`uMapTex`,`uSrcSh`],shaderLanguage:this._shaderLanguage});return t.backFaceCulling=!1,t.disableDepthWrite=!0,t}_renderRotCopyPass(e,t,n,r,i=this._textureSize,a=this._textureSize,o=0,s=0){let c=this._rotCopyMaterial;c.setTexture(`uMapTex`,n),c.setTexture(`uSrc0`,t[0]),c.setTexture(`uSrc1`,t[1]),c.setTexture(`uSrc2`,t[2]),c.setInt(`uDstWidth`,i),c.setInt(`uSrcWidth`,a),c.setInt(`uUseMap`,r),c.setInt(`uSrcBaseOffset`,o),c.setInt(`uDstBaseRow`,s),this._quad.material=c,e.renderList=[this._quad],e.render()}_createRotCopyMaterial(){let e=this._shaderLanguage===1,t=new ie(Rv,this._scene,{vertexSource:e?Tv:Cv,fragmentSource:e?Bv:zv},{attributes:[`position`],uniforms:[`uDstWidth`,`uSrcWidth`,`uUseMap`,`uSrcBaseOffset`,`uDstBaseRow`],samplers:[`uMapTex`,`uSrc0`,`uSrc1`,`uSrc2`],shaderLanguage:this._shaderLanguage});return t.backFaceCulling=!1,t.disableDepthWrite=!0,t}async readCentersRangeAsync(e,t){if(this._disposed||t<=0||!this.supportsAsyncCentersReadback)return null;let n=this._textureSize,r=this._baseOffset+e,i=Math.floor(r/n),a=Math.ceil((r+t)/n)-i,o=(r-i*n)*4,s=o+t*4,c=this._mrt.textures[0],l=this._scene.getEngine();if(l.isWebGPU){let e=await c.readPixels(0,0,null,!0,!0,0,i,n,a);if(this._disposed||!e)return null;let t=e instanceof Float32Array?e:new Float32Array(e.buffer,e.byteOffset,e.byteLength/4);return t.length>=s?t.subarray(o,s):null}let u=l,d=u._gl,f=c.getInternalTexture()?._hardwareTexture?.underlyingResource;if(!f)return null;let p=new Float32Array(n*a*4);this._readFbo||=d.createFramebuffer();let m=u._currentFramebuffer;d.bindFramebuffer(d.FRAMEBUFFER,this._readFbo),d.framebufferTexture2D(d.FRAMEBUFFER,d.COLOR_ATTACHMENT0,d.TEXTURE_2D,f,0),d.readBuffer(d.COLOR_ATTACHMENT0);let h=u._readPixelsAsync(0,i,n,a,d.RGBA,d.FLOAT,p);return d.bindFramebuffer(d.FRAMEBUFFER,m),m||d.readBuffer(d.BACK),!h||(await h,this._disposed||p.length<s)?null:p.subarray(o,s)}dispose(){if(this._disposed=!0,this._readFbo&&=(this._scene.getEngine()._gl?.deleteFramebuffer(this._readFbo),null),this._quad.dispose(),this._material.dispose(!0,!1),this._shMaterial?.dispose(!0,!1),this._rotMaterial?.dispose(!0,!1),this._copyMaterial?.dispose(!0,!1),this._shCopyMaterial?.dispose(!0,!1),this._rotCopyMaterial?.dispose(!0,!1),this._relayoutMapTexture?.dispose(),this._backupMrt?.dispose(),this._backupMrt=null,this._backupShMrts){for(let e of this._backupShMrts)e.dispose();this._backupShMrts=null}if(this._backupRotMrt?.dispose(),this._backupRotMrt=null,this._ownsMrt&&this._mrt.dispose(),this._ownsShMrts)for(let e of this._shMrts
699)e.dispose();this._shMrts=[],this._ownsRotMrt&&this._rotMrt?.dispose(),this._rotMrt=null}_createQuad(){let e=new At(`gsWorkBufferQuad`,this._scene),t=new E;return t.positions=[-1,-1,0,3,-1,0,-1,3,0],t.indices=[0,1,2],t.applyToMesh(e),this._scene.removeMesh(e),e}_createMaterial(){let e=this._shaderLanguage===1,t=new ie(`gsSogDecode`,this._scene,{vertexSource:e?Tv:Cv,fragmentSource:e?Ev:wv},{attributes:[`position`],uniforms:[`sogMeansMin`,`sogMeansMax`,`sogScalesMin`,`sogScalesMax`,`sogSh0Min`,`sogSh0Max`,`uVersion`,`uOffset`,`uCount`,`uDestWidth`,`uSrcWidth`],samplers:[`sogMeansLTex`,`sogMeansUTex`,`sogScalesTex`,`sogQuatsTex`,`sogSh0Tex`,`sogCodebookTex`],shaderLanguage:this._shaderLanguage});return t.backFaceCulling=!1,t.disableDepthWrite=!0,t}_applyPack(e){let t=this._material,n=e.meansTextureL.getSize().width;t.setTexture(`sogMeansLTex`,e.meansTextureL),t.setTexture(`sogMeansUTex`,e.meansTextureU),t.setTexture(`sogScalesTex`,e.scalesTexture),t.setTexture(`sogQuatsTex`,e.quatsTexture),t.setTexture(`sogSh0Tex`,e.sh0Texture),t.setTexture(`sogCodebookTex`,e.codebookTexture??e.sh0Texture),t.setVector3(`sogMeansMin`,new R(e.meansMin[0],e.meansMin[1],e.meansMin[2])),t.setVector3(`sogMeansMax`,new R(e.meansMax[0],e.meansMax[1],e.meansMax[2]));let r=e.scalesMin??[0,0,0],i=e.scalesMax??[0,0,0];t.setVector3(`sogScalesMin`,new R(r[0],r[1],r[2])),t.setVector3(`sogScalesMax`,new R(i[0],i[1],i[2]));let a=e.sh0Min??[0,0,0,0],o=e.sh0Max??[0,0,0,0];t.setVector4(`sogSh0Min`,new jt(a[0],a[1],a[2],a[3])),t.setVector4(`sogSh0Max`,new jt(o[0],o[1],o[2],o[3])),t.setInt(`uVersion`,e.version),t.setInt(`uCount`,e.splatCount),t.setInt(`uDestWidth`,this._textureSize),t.setInt(`uSrcWidth`,n)}_createShMaterial(){let e=this._shaderLanguage===1,t=new ie(Av,this._scene,{vertexSource:e?Tv:Cv,fragmentSource:e?Mv:jv},{attributes:[`position`],uniforms:[`sogShnMin`,`sogShnMax`,`uVersion`,`uOffset`,`uCount`,`uDestWidth`,`uSrcWidth`,`uCoeffs`,`uShTextureIndex`],samplers:[`sogShLabelsTex`,`sogShCentroidsTex`,`sogCodebookTex`],shaderLanguage:this._shaderLanguage});return t.backFaceCulling=!1,t.disableDepthWrite=!0,t}_applyShPack(e){let t=this._shMaterial,n=!!e.shLabelsTexture&&!!e.shCentroidsTexture,r=e.shLabelsTexture??e.sh0Texture,i=e.shCentroidsTexture??e.sh0Texture;t.setTexture(`sogShLabelsTex`,r),t.setTexture(`sogShCentroidsTex`,i),t.setTexture(`sogCodebookTex`,e.codebookTexture??r),t.setFloat(`sogShnMin`,e.shnMin??0),t.setFloat(`sogShnMax`,e.shnMax??0),t.setInt(`uVersion`,e.version),t.setInt(`uCount`,e.splatCount),t.setInt(`uDestWidth`,this._textureSize),t.setInt(`uSrcWidth`,r.getSize().width),t.setInt(`uCoeffs`,n?e.shCoeffCount:0)}_createRotMaterial(){let e=this._shaderLanguage===1,t=new ie(Dv,this._scene,{vertexSource:e?Tv:Cv,fragmentSource:e?kv:Ov},{attributes:[`position`],uniforms:[`sogScalesMin`,`sogScalesMax`,`uVersion`,`uOffset`,`uCount`,`uDestWidth`,`uSrcWidth`],samplers:[`sogScalesTex`,`sogQuatsTex`,`sogCodebookTex`],shaderLanguage:this._shaderLanguage});return t.backFaceCulling=!1,t.disableDepthWrite=!0,t}_applyRotPack(e){let t=this._rotMaterial,n=e.scalesTexture.getSize().width;t.setTexture(`sogScalesTex`,e.scalesTexture),t.setTexture(`sogQuatsTex`,e.quatsTexture),t.setTexture(`sogCodebookTex`,e.codebookTexture??e.scalesTexture);let r=e.scalesMin??[0,0,0],i=e.scalesMax??[0,0,0];t.setVector3(`sogScalesMin`,new R(r[0],r[1],r[2])),t.setVector3(`sogScalesMax`,new R(i[0],i[1],i[2])),t.setInt(`uVersion`,e.version),t.setInt(`uCount`,e.splatCount),t.setInt(`uDestWidth`,this._textureSize),t.setInt(`uSrcWidth`,n)}};Ze();var Uv=class{constructor(e){this._activeCount=0,this._queue=[],this._pending=new Map,this._groups=new Map,this._disposed=!1,this.maxConcurrent=Math.max(1,e?.maxConcurrent??2),this.maxRetries=Math.max(0,e?.maxRetries??2)}get isIdle(){return this._pending.size===0}async loadFileAsync(e,t){if(this._disposed)throw Error(`GaussianSplattingDownloadManager has been disposed.`);let n=this._pending.get(e);if(n)return await n.promise;let r={url:e,groupId:t,settled:!1,cancelled:!1,started:!1,slotReleased:!1};if(r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),this._pending.set(e,r),t!==void 0){let n=this._groups.get(t);n||(n=new Set,this._groups.set(t,n)),n.add(e)}return this._queue.push(r),this._pump(),await r.promise}
699cancel(e){let t=this._pending.get(e);t&&this._abort(t,Error(`GaussianSplattingDownloadManager: download cancelled (${e}).`))}cancelGroup(e){let t=this._groups.get(e);if(t){for(let e of Array.from(t))this.cancel(e);this._groups.delete(e)}}dispose(){if(!this._disposed){this._disposed=!0,this._queue.length=0;for(let e of Array.from(this._pending.values()))this._abort(e,Error(`GaussianSplattingDownloadManager has been disposed.`))}}_abort(e,t){if(e.settled)return;e.cancelled=!0;let n=this._queue.indexOf(e);n!==-1&&this._queue.splice(n,1),e.request?.abort(),e.cancelAttempt?.(t),this._settle(e,()=>e.reject(t)),e.started&&this._releaseSlot(e)}_settle(e,t){if(!e.settled){if(e.settled=!0,this._pending.delete(e.url),e.groupId!==void 0){let t=this._groups.get(e.groupId);t&&(t.delete(e.url),t.size===0&&this._groups.delete(e.groupId))}t()}}_releaseSlot(e){e.slotReleased||(e.slotReleased=!0,this._activeCount--,this._pump())}_pump(){for(;!this._disposed&&this._activeCount<this.maxConcurrent&&this._queue.length>0;){let e=this._queue.shift();e.settled||(e.started=!0,this._activeCount++,this._runTaskAsync(e).finally(()=>{this._releaseSlot(e)}))}}async _runTaskAsync(e){let t;for(let n=0;n<=this.maxRetries;n++){if(this._disposed||e.cancelled)return;try{let t=await this._downloadAttemptAsync(e);this._settle(e,()=>e.resolve(t));return}catch(n){if(e.cancelAttempt=void 0,this._disposed||e.cancelled)return;t=n}}this._settle(e,()=>e.reject(t))}async _downloadAttemptAsync(e){return await new Promise((t,n)=>{e.cancelAttempt=n,e.request=P.LoadFile(e.url,e=>t(e),void 0,void 0,!0,(t,r)=>n(r instanceof Error?r:Error(`GaussianSplattingDownloadManager: failed to load ${e.url}.`)))})}},Wv=class{constructor(){this._offset=0,this._size=0,this._free=!0,this._prev=null,this._next=null,this._prevFree=null,this._nextFree=null,this._bucket=-1}get offset(){return this._offset}get size(){return this._size}},Gv=class{constructor(e=0,t=1.1){if(this._headAll=null,this._tailAll=null,this._freeBucketHeads=[],this._pool=[],this._capacity=0,this._usedSize=0,this._freeSize=0,this._freeRegionCount=0,this._growMultiplier=t,e>0){this._capacity=e,this._freeSize=e;let t=this._obtain(0,e,!0);this._headAll=t,this._tailAll=t,this._addToBucket(t)}}get capacity(){return this._capacity}get usedSize(){return this._usedSize}get freeSize(){return this._freeSize}get fragmentation(){return this._freeSize>0?1-1/this._freeRegionCount:0}allocate(e){if(e<=0)return null;let t=this._findFreeBlock(e);if(!t)return null;if(this._usedSize+=e,this._freeSize-=e,t._size===e)return t._free=!1,this._removeFromBucket(t),t;let n=this._obtain(t._offset,e,!1);return t._offset+=e,t._size-=e,this._rebucket(t),this._insertAfterInMainList(n,t._prev),n}free(e){if(!e||e._free)return;e._free=!0,this._usedSize-=e._size,this._freeSize+=e._size;let t=e._prev,n=e._next,r=t&&t._free,i=n&&n._free;r&&i?(t._size+=e._size+n._size,this._removeFromMainList(e),this._removeFromMainList(n),this._removeFromBucket(n),this._release(e),this._release(n),this._rebucket(t)):r?(t._size+=e._size,this._removeFromMainList(e),this._release(e),this._rebucket(t)):i?(e._size+=n._size,this._removeFromMainList(n),this._removeFromBucket(n),this._release(n),this._addToBucket(e)):this._addToBucket(e)}grow(e){if(e<=this._capacity)return;let t=e-this._capacity;if(this._capacity=e,this._freeSize+=t,this._tailAll&&this._tailAll._free)this._tailAll._size+=t,this._rebucket(this._tailAll);else{let e=this._obtain(this._capacity-t,t,!0);this._insertAfterInMainList(e,this._tailAll),this._addToBucket(e)}}defrag(e=0,t=new Set){return t.clear(),this._freeRegionCount===0||(e===0?this._defragFull(t):this._defragIncremental(e,t)),t}updateAllocation(e,t){for(let t=0;t<e.length;t++)this.free(e[t]);for(let e=0;e<t.length;e++){let n=t[e],r=this.allocate(n);if(r)t[e]=r;else{let r=n;for(let n=e+1;n<t.length;n++)r+=t[n];let i=this._usedSize+r,a=Math.ceil(i*this._growMultiplier);a>this._capacity&&this.grow(a),this.defrag(0);for(let n=e;n<t.length;n++)t[n]=this.allocate(t[n]);return!0}}return!1}_bucketFor(e){return 31-Math.clz32(e)}_addToBucket(e){let t=this._bucketFor(e._size);for(e._bucket=t;t>=this._freeBucketHeads.length;)this._freeBucketHeads.push(null);e._prevFree=null,e._nextFree=this._freeBucketHeads[t],this._freeBucketHeads[t]&&(this._freeBucketHeads[t]._prevFree=e),this._freeBucketHeads[t]=e,this._freeRegionCount++}_removeFromBucket(e){let t=e._bucket;e._prevFree?e._prevFree._nextFree=e._nextFree:this._freeBucketHeads[t]=e._nextFree,e._nextFree&&(e._nextFree._prevFree=e._prevFree),e._prevFree=null,e._nextFree=null,e._bucket=-1,this._freeRegionCount--}_rebucket(e){this._bucketFor(e._size)!==e._bucket&&(this._removeFromBucket(e),this._addToBucket(e))}_obtain(e,t,n){let r=this._pool.length>0?this._pool.pop():new Wv;return r._offset=e,r._size=t,r._free=n,r._prev=null,r._next=null,r._prevFree=null,r._nextFree=null,r._bucket=-1,r}_release(e){e._prev=null,e._next=null,e._prevFree=null,e._nextFree=null,e._bucket=-1,this._pool.push(e)}_insertAfterInMainList(e,t){t===null?(e._prev=null,e._next=this._headAll,this._headAll&&(this._headAll._prev=e),this._headAll=e,this._tailAll||=e):(e._prev=t,e._next=t._next,t._next&&(t._next._prev=e),t._next=e,this._tailAll===t&&(this._tailAll=e))}_removeFromMainList(e){e._prev?e._prev._next=e._next:this._headAll=e._next,e._next?e._next._prev=e._prev:this._tailAll=e._prev,e._prev=null,e._next=null}_findFreeBlock(e){let t=this._bucketFor(e),n=this._freeBucketHeads.length;if(t<n){let n=null,r=this._freeBucketHeads[t];for(;r&&!(r._size>=e&&(!n||r._size<n._size)&&(n=r,r._size===e));)r=r._nextFree;if(n)return n}for(let e=t+1;e<n;e++)if(this._freeBucketHeads[e])return this._freeBucketHeads[e];return null}_defragFull(e){for(let e=0;e<this._freeBucketHeads.length;e++){let t=this._freeBucketHeads[e];for(;t;){let e=t._nextFree;this._removeFromMainList(t),t._prevFree=null,t._nextFree=null,t._bucket=-1,this._pool.push(t),t=e}this._freeBucketHeads[e]=null}this._freeRegionCount=0;let t=0,n=this._headAll;for(;n;)n._offset!==t&&(n._offset=t,e.add(n)),t+=n._size,n=n._next;let r=this._capacity-t;if(r>0){let e=this._obtain(t,r,!0);this._insertAfterInMainList(e,this._tailAll),this._addToBucket(e)}}_defragIncremental(e,t){let n=Math.ceil(e/2),r=e-n;for(let e=0;e<n;e++){let e=this._tailAll;
699for(;e&&e._free;)e=e._prev;if(!e)break;let n=this._findFreeBlock(e._size);if(!n||n._offset>=e._offset)break;this._moveBlock(e,n),t.add(e)}let i=this._headAll;for(let e=0;e<r&&i;){let n=i._next;if(i._free&&n&&!n._free){let r=n,a=i;r._offset=a._offset,a._offset=r._offset+r._size;let o=a._prev,s=r._next;if(r._prev=o,r._next=a,a._prev=r,a._next=s,o?o._next=r:this._headAll=r,s?s._prev=a:this._tailAll=a,a._next&&a._next._free){let e=a._next;a._size+=e._size,this._removeFromMainList(e),this._removeFromBucket(e),this._release(e),this._rebucket(a)}t.add(r),e++,i=a._next}else i=n}}_moveBlock(e,t){let n=e._size,r=t._offset,i=e._prev;this._removeFromMainList(e);let a=this._obtain(e._offset,n,!0);if(this._insertAfterInMainList(a,i),this._addToBucket(a),a._next&&a._next._free){let e=a._next;a._size+=e._size,this._removeFromMainList(e),this._removeFromBucket(e),this._release(e),this._rebucket(a)}if(a._prev&&a._prev._free){let e=a._prev;e._size+=a._size,this._removeFromMainList(a),this._removeFromBucket(a),this._release(a),this._rebucket(e)}if(e._offset=r,t._size===n){let n=t._prev;this._removeFromMainList(t),this._removeFromBucket(t),this._release(t),this._insertAfterInMainList(e,n)}else t._offset+=n,t._size-=n,this._rebucket(t),this._insertAfterInMainList(e,t._prev)}},Kv=class{constructor(e,t,n){this._blocks=new Map,this._cooldown=new Map,this._pinned=new Set,this._allocator=new Gv(e),this._cooldownFrames=Math.max(0,t),this._onEvict=n}get capacity(){return this._allocator.capacity}get residentCount(){return this._blocks.size}get freeSize(){return this._allocator.freeSize}has(e){return this._blocks.has(e)}offset(e){return this._blocks.get(e)?.offset}allocate(e,t){let n=this._blocks.get(e);if(n)return n.offset;let r=this._allocator.allocate(t);return!r&&(this._evictAllCooled(),r=this._allocator.allocate(t),!r)?null:(this._blocks.set(e,r),r.offset)}pin(e,t){let n=this.allocate(e,t);return n!==null&&this._pinned.add(e),n}free(e){if(this._pinned.has(e))return;let t=this._blocks.get(e);t&&(this._allocator.free(t),this._blocks.delete(e),this._cooldown.delete(e))}compact(){let e=new Map;for(let[t,n]of Array.from(this._blocks))e.set(t,n.offset);this._allocator.defrag(0);let t=[];for(let[n,r]of Array.from(this._blocks)){let i=e.get(n);i!==r.offset&&t.push({file:n,oldOffset:i,newOffset:r.offset,count:r.size})}return t}getResidentBlocks(){let e=[];for(let[t,n]of Array.from(this._blocks))e.push({file:t,offset:n.offset,count:n.size});return e}scheduleEviction(e){!this._pinned.has(e)&&this._blocks.has(e)&&this._cooldown.set(e,this._cooldownFrames)}cancelEviction(e){this._cooldown.delete(e)}tick(){if(this._cooldown.size===0)return[];let e=[];for(let[t,n]of Array.from(this._cooldown))n<=1?e.push(t):this._cooldown.set(t,n-1);for(let t of e)this._evict(t);return e}dispose(){this._blocks.clear(),this._cooldown.clear(),this._pinned.clear()}_evictAllCooled(){let e=Array.from(this._cooldown.keys());for(let t of e)this._evict(t)}_evict(e){let t=this._blocks.get(e);t&&(this._allocator.free(t),this._blocks.delete(e)),this._cooldown.delete(e),this._onEvict(e)}};yt(),Ze(),rr(),jn(),be(),rn();var qv=Math.tan(22.5*Math.PI/180),Jv=-2,Yv=-1,Xv=84,Zv=4,Qv=5,$v=32,ey=512,ty=256,ny=new L,ry=new R,iy=new R,ay=new R,oy=new R(0,0,1),sy=[[0,1],[1,2],[2,3],[3,0],[4,5],[5,6],[6,7],[7,4],[0,4],[1,5],[2,6],[3,7]],cy=sy.length*2,ly=[new F(1,.2,.2,1),new F(1,.6,.1,1),new F(1,1,.2,1),new F(.3,1,.3,1),new F(.2,1,1,1),new F(.4,.5,1,1),new F(.9,.4,1,1),new F(1,1,1,1)],uy=class e extends Bt{static IsLODMetadata(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.lodLevels==`number`&&Array.isArray(t.filenames)&&typeof t.tree==`object`&&t.tree!==null}constructor(t,n,r,i,a={}){let o=e._NormalizeResidentLimit(a.maxResidentSplats??0,`maxResidentSplats`,!0),s=e._NormalizeResidentLimit(a.memoryBudgetMb??0,`memoryBudgetMb`,!1);super(t,null,i,!1),this._leafNodes=[],this._lod0SplatCount=Object.freeze({status:`pending`}),this._lodBaseDistance=5,this._lodMultiplier=3,this._lodBehindPenalty=1,this._lodRangeMin=0,this._maxDecodesPerFrame=1,this._lodCooldownFrames=10,this._lodUpdateInterval=4,this._lodUpdateDistance=.5,this._maxDetail
699Lod=0,this._lodPixelThreshold=1,this._hostBudgetAllocation=null,this._frustumCulling=!0,this._frustumPlanes=[new Et(0,0,0,0),new Et(0,0,0,0),new Et(0,0,0,0),new Et(0,0,0,0),new Et(0,0,0,0),new Et(0,0,0,0)],this._cullCameraViewProj=new L,this._cullViewProj=new L,this._frustumScratch=[],this._workBuffer=null,this._streamShDegree=0,this._shTextureCount=0,this._needsRotationScale=!1,this._useGpuPositionReadback=!1,this._readbackCandidate=!1,this._readbackProbed=!1,this._residency=null,this._fileCounts=new Map,this._fileMeta=new Map,this._baseFileIds=new Set,this._decodedFiles=new Set,this._loadingFiles=new Set,this._decodeQueue=[],this._fileRefs=new Map,this._cancelledDecodes=new Set,this._evictionEnabled=!1,this._residentBudget=0,this._minimumResidentSplats=0,this._maxResidentSplats=0,this._memoryBudgetMb=0,this._evictionCooldownFrames=100,this._decodeGate=Promise.resolve(),this._relayoutOldOffsets=new Map,this._relayoutSrcIndex=null,this._environmentRange=null,this._environmentFiles=null,this._lodObserver=null,this._baseLayerReady=!1,this._metadataReady=!1,this._framesSinceLodUpdate=0,this._lastLodCamPositions=[],this._lastLodSignature=``,this._forceLodUpdate=!1,this._boundsMin=new R(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._boundsMax=new R(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE),this._debugDisplay=!1,this._debugLodSource=`optimal`,this._debugMesh=null,this._debugObserver=null,this._debugColorData=null,this._debugSignature=0,this._disposed=!1,this._hostCompound=null,this._host=null,this._positionBase=0,this._unsubBeforeRebuild=null,this._unsubAfterRebuild=null,this._hostUnsubRemove=null,this._hostUnsubDispose=null,this._partReleasedByHost=!1,this._positionSnapshot=null,this._partReadyPromise=null,this._partReadyResolve=null,this._partReadyReject=null,this._partReadySettled=!1,this._metadata=n,this._rootUrl=r,this._streamOptions=a,this._hostCompound=a.hostCompound??null,this._decodeSh=a.decodeSh??!0,this._needsRotationScale=a.needsRotationScale??!1;let c=Math.max(0,n.lodLevels-1);if(this._lodRangeMax=c,a.lodBaseDistance!==void 0&&(this._lodBaseDistance=Math.max(.1,a.lodBaseDistance)),a.lodMultiplier!==void 0&&(this._lodMultiplier=Math.max(1.2,a.lodMultiplier)),a.lodBehindPenalty!==void 0&&(this._lodBehindPenalty=Math.max(1,a.lodBehindPenalty)),a.lodRangeMin!==void 0&&(this._lodRangeMin=Math.max(0,Math.min(a.lodRangeMin,c))),a.lodRangeMax!==void 0&&(this._lodRangeMax=Math.max(this._lodRangeMin,Math.min(a.lodRangeMax,c))),a.maxDecodesPerFrame!==void 0&&(this._maxDecodesPerFrame=Math.max(1,a.maxDecodesPerFrame)),a.lodCooldownFrames!==void 0&&(this._lodCooldownFrames=Math.max(0,a.lodCooldownFrames)),a.lodUpdateInterval!==void 0&&(this._lodUpdateInterval=Math.max(1,a.lodUpdateInterval)),a.lodUpdateDistance!==void 0&&(this._lodUpdateDistance=Math.max(0,a.lodUpdateDistance)),a.maxDetailLod!==void 0&&(this._maxDetailLod=Math.max(0,Math.floor(a.maxDetailLod))),this._splatBudget=this._resolveSplatBudget(a.splatBudget),a.frustumCulling!==void 0&&(this._frustumCulling=a.frustumCulling),a.debugLodSource&&(this._debugLodSource=a.debugLodSource),a.evictionCooldownFrames!==void 0&&(this._evictionCooldownFrames=Math.max(0,Math.floor(a.evictionCooldownFrames))),this._maxResidentSplats=o,this._memoryBudgetMb=s,this._downloadManager=new Uv({maxConcurrent:a.maxConcurrentDownloads,maxRetries:a.maxDownloadRetries}),!this._hostCompound)this.scaling.y*=-1,this.rotation.x=-Math.PI/2;else{this.setEnabled(!1),this.isPickable=!1,this.doNotSerialize=!0,this._partReadyPromise=new Promise((e,t)=>{this._partReadyResolve=e,this._partReadyReject=t}),this._partReadyPromise.catch(()=>{});let e=this._hostCompound.onDisposeObservable.add(()=>{this._disposed||(this._partReleasedByHost=!0,this.dispose())});this._hostUnsubDispose=()=>this._hostCompound.onDisposeObservable.remove(e)}this._collectLodEntries(n.tree),a.debugDisplay&&(this.debugDisplay=!0),this._streamAllAsync().then(()=>{let e=this._partReadySettled;this._rejectPartReady(`GaussianSplattingStream: stream produced no splats.`),!e&&this._hostCompound&&!this._disposed&&this._disposeAndReclaim()},e=>{this._lod0SplatCount=Object.freeze({status:`unavailable`}),A.Error(`GaussianSplattingStream: streaming failed: `+(e?.message??e)),this._rejectPartReady(`GaussianSplattingStream: streaming failed: `+(e?.message??e)),this._disposed||this._disposeAndReclaim()})}getClassName(){return`GaussianSplattingStream`}isReady(e=!1){return this._hostCompound?!0:super.isReady(e)}get streamingPartProxy(){return this._host?.proxy??null}async whenPartReadyAsync(){await(this._partReadyPromise??Promise.resolve())}_resolvePartReady(){this._partReadySettled||(this._partReadySettled=!0,this._partReadyResolve?.())}_rejectPartReady(e){this._partReadySettled||(this._partReadySettled=!0,this._partReadyReject?.(Error(e)))}
699async whenSettledAsync(e=3){if(this._disposed)return;this._forceLodUpdate=!0;let t=Math.max(1,e),n=this._scene,r=0,i=()=>this._isLoadingIdle()&&this._sinkIsDepthSortSettled?++r>=t:(r=0,!1);if(n.getEngine().activeRenderLoops.length>0){await new Promise(e=>{let t=null;t=n.onAfterRenderObservable.add(()=>{(this._disposed||i())&&(t&&=(n.onAfterRenderObservable.remove(t),null),e())})});return}let a=n.getEngine(),o=globalThis.requestAnimationFrame;for(;!this._disposed;){if(a.beginFrame(),n.render(),a.endFrame(),i())return;await new Promise(e=>{typeof o==`function`?o(()=>e()):setTimeout(e,16)})}}_isLoadingIdle(){return this._baseLayerReady&&this._metadataReady&&this._decodeQueue.length===0&&this._loadingFiles.size===0&&this._downloadManager.isIdle}get maxDetailLod(){return this._maxDetailLod}set maxDetailLod(e){let t=Math.max(0,Math.floor(e));this._maxDetailLod!==t&&(this._maxDetailLod=t,this._forceLodUpdate=!0)}get splatBudget(){return this._splatBudget}set splatBudget(e){let t=e>0?Math.floor(e):0;t!==this._splatBudget&&(this._splatBudget=t,this._forceLodUpdate=!0)}get effectiveSplatBudget(){return this._effectiveSplatBudget()}get residentSplatBudget(){return this._residentBudget}get minimumResidentSplats(){return this._minimumResidentSplats}get lod0SplatCount(){return this._lod0SplatCount}_resolveSplatBudget(e){return e===void 0?0:e===`auto`?this._computeDefaultSplatBudget():e>0?Math.floor(e):0}_computeDefaultSplatBudget(){return this._scene.getEngine().hostInformation?.isMobile?typeof navigator<`u`&&navigator.userAgent&&/iPad|iPhone|iPod/.test(navigator.userAgent)?15e5:1e6:25e5}_effectiveSplatBudget(){if(this._hostBudgetAllocation!==null){let e=Math.max(1,this._hostBudgetAllocation);return this._residentBudget>0?Math.min(e,this._residentBudget):e}return this._splatBudget<=0?0:this._residentBudget>0?Math.min(this._splatBudget,this._residentBudget):this._splatBudget}_splatBudgetEnabled(){return this._effectiveSplatBudget()>0}getBudgetDemand(){if(!this._baseLayerReady)return 0;let e=this._environmentSplatCount();for(let t of this._leafNodes){let n=t.optimalLod??t.baseLod;e+=this._countAtLevel(t,this._cappedLevelForNode(t,n))}return e}setBudgetAllocation(e){if(e===null){this._hostBudgetAllocation!==null&&(this._hostBudgetAllocation=null,this._forceLodUpdate=!0);return}let t=this._hostBudgetAllocation;this._hostBudgetAllocation=e,(t===null||e!==t)&&(this._forceLodUpdate=!0)}get maxLodLevel(){return Math.max(0,this._metadata.lodLevels-1)}get frustumCulling(){return this._frustumCulling}set frustumCulling(e){this._frustumCulling!==e&&(this._frustumCulling=e,this._forceLodUpdate=!0)}get debugDisplay(){return this._debugDisplay}set debugDisplay(e){this._debugDisplay!==e&&(this._debugDisplay=e,e?this._refreshDebugDisplay():this._clearDebugDisplay())}get debugLodSource(){return this._debugLodSource}set debugLodSource(e){this._debugLodSource!==e&&(this._debugLodSource=e,this._debugDisplay&&this._refreshDebugDisplay())}dispose(e){this._disposed||(this._disposed=!0,this._rejectPartReady(`GaussianSplattingStream: disposed before the part was ready.`),this._unsubBeforeRebuild?.(),this._unsubAfterRebuild?.(),this._unsubBeforeRebuild=null,this._unsubAfterRebuild=null,this._hostUnsubRemove?.(),this._hostUnsubDispose?.(),this._hostUnsubRemove=null,this._hostUnsubDispose=null,this._hostCompound&&!this._hostCompound.isDisposed()&&this._hostCompound.unregisterLodBudgetParticipant(this),this._host&&this._hostCompound&&!this._partReleasedByHost&&!this._hostCompound.isDisposed()&&this._hostCompound.removePart(this._host.partIndex),this._host=null,this._lodObserver&&=(this._scene.onBeforeRenderObservable.remove(this._lodObserver),null),this._clearDebugDisplay(),this._downloadManager.dispose(),this._residency?.dispose(),this._residency=null,this._workBuffer?.dispose(),this._workBuffer=null,super.dispose(e))}_disposeAndReclaim(){let e=this._hostCompound,t=!!this._host&&!this._partReleasedByHost;this.dispose(),t&&e&&!e.isDisposed()&&e.compactAtlas()}_getEffectiveWorldMatrix(e){return this._host?this._host.proxy.computeWorldMatrix(e):this.computeWorldMatrix(e)}_getActiveLodCameras(){return(this._scene.activeCameras?.length?this._scene.activeCameras:this._scene.activeCamera?[this._scene.activeCamera]:[]).filter(e=>!!e)}
699evaluateOptimalLods(e=null){let t=e?[e]:this._getActiveLodCameras();if(t.length===0||this._leafNodes.length===0)return;let n=Math.max(0,this._metadata.lodLevels-1),r=this._lodBaseDistance,i=this._lodMultiplier,a=this._lodBehindPenalty,o=this._lodRangeMin,s=this._lodRangeMax,c=this._splatBudgetEnabled(),l=this._scene.getEngine().getRenderHeight()||1,u=this._scene.getEngine();this._getEffectiveWorldMatrix(!1).invertToRef(ny);let d=t.map(e=>{let t=u.getAspectRatio(e)||1,n=Math.tan(e.fov*.5);e.fovMode===De.FOVMODE_HORIZONTAL_FIXED&&(n/=t);let r=n*t,i=Math.min(n,r)/qv,o=l*(e.viewport?e.viewport.height:1),s=R.TransformCoordinatesToRef(e.globalPosition,ny,ry),c={px:s.x,py:s.y,pz:s.z,fwx:0,fwy:0,fwz:0,fovScale:i,tanHalfV:n,pixelHeight:o};if(a>1){e.getDirectionToRef(oy,ay);let t=R.TransformNormalToRef(ay,ny,iy);t.normalize(),c.fwx=t.x,c.fwy=t.y,c.fwz=t.z}return c});for(let e of this._leafNodes){let t=e.bound.min,l=e.bound.max,u=(t[0]+l[0])*.5,f=(t[1]+l[1])*.5,p=(t[2]+l[2])*.5,m=l[0]-t[0],h=l[1]-t[1],g=l[2]-t[2],_=.5*Math.sqrt(m*m+h*h+g*g),v=1/0,y=0;for(let e of d){let o=e.px<t[0]?t[0]:e.px>l[0]?l[0]:e.px,s=e.py<t[1]?t[1]:e.py>l[1]?l[1]:e.py,d=e.pz<t[2]?t[2]:e.pz>l[2]?l[2]:e.pz,m=o-e.px,h=s-e.py,g=d-e.pz,b=Math.sqrt(m*m+h*h+g*g),x=b;if(a>1&&b>.01){let t=(e.fwx*m+e.fwy*h+e.fwz*g)/b;t<0&&(x=b*(1+-t*(a-1)))}let S=x*e.fovScale,C;if(n===0||S<r)C=0;else for(C=n;C>1&&S<r*i**(C-1);)C--;if(C<v&&(v=C),c){let t=u-e.px,n=f-e.py,r=p-e.pz,i=Math.sqrt(t*t+n*n+r*r),a=_*e.pixelHeight/(Math.max(i,1e-4)*e.tanHalfV);a>y&&(y=a)}}v<o?v=o:v>s&&(v=s),this._frustumCulling&&e.inFrustum===!1&&(v=s),e.optimalLod=v,c&&(e.pixelSize=y)}}_displayedLodLevel(e){return this._debugLodSource===`optimal`?e.optimalLod??e.activeLod??0:e.activeLod??0}_refreshDebugDisplay(){this._debugLodSource===`optimal`&&this.evaluateOptimalLods(),this._buildDebugMesh();let e=this._debugDisplay;e&&!this._debugObserver?this._debugObserver=this._scene.onBeforeRenderObservable.add(()=>this._onDebugFrame()):!e&&this._debugObserver&&(this._scene.onBeforeRenderObservable.remove(this._debugObserver),this._debugObserver=null)}_onDebugFrame(){this._debugLodSource===`optimal`&&this.evaluateOptimalLods(),this._computeDebugSignature()!==this._debugSignature&&this._updateDebugColors()}_buildDebugMesh(){this._debugMesh&&=(this._debugMesh.dispose(),null),this._debugColorData=null;let e=[],t=[];for(let n of this._leafNodes){let r=ly[this._displayedLodLevel(n)%ly.length],i=n.bound.min,a=n.bound.max,o=[new R(i[0],i[1],i[2]),new R(a[0],i[1],i[2]),new R(a[0],a[1],i[2]),new R(i[0],a[1],i[2]),new R(i[0],i[1],a[2]),new R(a[0],i[1],a[2]),new R(a[0],a[1],a[2]),new R(i[0],a[1],a[2])];for(let n of sy)e.push([o[n[0]],o[n[1]]]),t.push([r,r])}if(this._debugSignature=this._computeDebugSignature(),e.length===0)return;let n=Er(this.name+`_lodDebug`,{lines:e,colors:t,updatable:!0,useVertexAlpha:!1},this._scene);n.parent=this,n.isPickable=!1,n.doNotSerialize=!0,n.reservedDataStore={hidden:!0},this._debugMesh=n,this._debugColorData=new Float32Array(this._leafNodes.length*cy*4)}_updateDebugColors(){if(!this._debugMesh||!this._debugColorData)return;let e=this._debugColorData,t=0;for(let n of this._leafNodes){let r=ly[this._displayedLodLevel(n)%ly.length];for(let n=0;n<cy;n++)e[t++]=r.r,e[t++]=r.g,e[t++]=r.b,e[t++]=r.a}this._debugMesh.updateVerticesData(j.ColorKind,e),this._debugSignature=this._computeDebugSignature()}_computeDebugSignature(){let e=0;for(let t of this._leafNodes)e=e*31+this._displayedLodLevel(t)|0;return e}_clearDebugDisplay(){this._debugObserver&&=(this._scene.onBeforeRenderObservable.remove(this._debugObserver),null),this._debugMesh&&=(this._debugMesh.dispose(),null),this._debugColorData=null,this._debugSignature=0}_collectLodEntries(e){if(e.children){for(let t of e.children)this._collectLodEntries(t);return}if(!e.lods)return;let t=e.bound?.min,n=e.bound?.max;if(!t||!n||t.length<3||n.length<3||!t.every(e=>Number.isFinite(e))||!n.every(e=>Number.isFinite(e)))return;let r=n[0]-t[0],i=n[1]-t[1],a=n[2]-t[2],o=Math.sqrt(r*r+i*i+a*a);if(!Number.isFinite(o)||o<=0)return;
699let s=Math.floor(Number(this._metadata.lodLevels)),c=Number.isFinite(s)&&s>0?s-1:0,l=[];for(let t of Object.keys(e.lods)){let n=Number(t),r=e.lods[t],i=r?Math.floor(Number(r.count)):NaN;Number.isInteger(n)&&String(n)===t&&n>=0&&n<=c&&r&&Number.isFinite(i)&&i>0&&(r.count=i,l.push(n))}if(l.length===0)return;l.sort((e,t)=>e-t);let u=[],d=1/0;for(let t of l){let n=e.lods[String(t)].count;n<=d&&(u.push(t),d=n)}e.availableLevels=u,e.baseLod=u[u.length-1],e.activeLod=void 0,e.lodCooldown=0,e.inFrustum=!0,e.cullBounds=new Gn(R.FromArray(t),R.FromArray(n)),this._leafNodes.push(e)}async _streamAllAsync(){let t=this._collectAllFileIds(),n=this._collectBaseFileIds();this._baseFileIds.clear();for(let e of n)this._baseFileIds.add(e);if(this._leafNodes.length>0&&n.length===0)throw Error(`GaussianSplattingStream: no valid coarse source files were referenced.`);let r=t.length>$v&&n.length<t.length;r&&this._decodeSh&&(this._streamShDegree=Zv,this._shTextureCount=Qv);let i=r?n:t,a=await this._gatherCountsAsync(i);if(this._disposed)return;for(let e of n){let t=this._fileCounts.get(e);if(!this._fileMeta.has(e)||t===void 0||t<=0)throw Error(`GaussianSplattingStream: required coarse metadata for file ${e} is unavailable or invalid.`)}this._resolveMinimumResidentSplats(n,a),r||(this._resolveLod0SplatCount(),this._metadataReady=!0);let o=null;if(!r){o=1+a;for(let n of t){let t=this._fileCounts.get(n);t!==void 0&&t>0&&(o=e._SafeAddCounts(o,t,`stream capacity`))}}if(this._minimumResidentSplats<=1)throw Error(`GaussianSplattingStream: stream produced no splats.`);let s=0;for(let e of n)s=Math.max(s,this._fileCounts.get(e));let c=this._resolveResidentBudget(o,s);if(this._evictionEnabled=r||o!==null&&c<o,this._residency=new Kv(c,this._evictionCooldownFrames,e=>this._onFileEvicted(e)),this._residency.pin(Jv,1),a>0){let e=this._residency.allocate(Yv,a);e===null?(A.Warn(`GaussianSplattingStream: environment does not fit the memory budget; skipping it.`),this._environmentFiles=null):this._environmentRange={offset:e,count:a}}if(this._hostCompound){let e=L.Compose(new R(1,-1,1),z.RotationYawPitchRoll(0,-Math.PI/2,0),R.ZeroReadOnly),t=this._hostCompound.reserveStreamingPart(c,e,this.name+`_part`,this._shTextureCount,this._streamShDegree,this._needsRotationScale);this._host=t,this._positionBase=t.base,this._hostCompound.registerLodBudgetParticipant(this);let n=this._hostCompound,r=n.onPartRemovedObservable.add(e=>{!this._disposed&&this._host&&e===this._host.partIndex&&(this._partReleasedByHost=!0,this.dispose())});this._hostUnsubRemove=()=>n.onPartRemovedObservable.remove(r);let i=this._shTextureCount>0&&t.shMrtAtlas?{textureCount:this._shTextureCount,externalMrts:t.shMrtAtlas}:void 0,a=this._needsRotationScale&&t.rotMrtAtlas?{externalMrt:t.rotMrtAtlas}:void 0;this._workBuffer=new Hv(this._scene,t.capacity,{mrt:t.mrtAtlas,width:t.atlasWidth,baseOffset:t.base},i,a),this._readbackCandidate=this._workBuffer.supportsAsyncCentersReadback,this._splatPositions=t.splatPositions,this._vertexCount=c;let o=this._workBuffer;this._unsubBeforeRebuild=t.onBeforeAtlasRebuild(()=>{o.backupRegion(),this._positionSnapshot=this._splatPositions?this._splatPositions.slice(this._positionBase*4,(this._positionBase+this._vertexCount)*4):null}),this._unsubAfterRebuild=t.onAfterAtlasRebuild(()=>{t.mrtAtlas&&o.rebindAtlas(t.mrtAtlas),o.rebindShAtlas(t.shMrtAtlas),o.rebindRotAtlas(t.rotMrtAtlas),this._positionBase=t.base,o.setBaseOffset(t.base),o.restoreRegion(),this._splatPositions=t.splatPositions,this._positionSnapshot&&this._splatPositions&&(this._splatPositions.set(this._positionSnapshot,this._positionBase*4),this._positionSnapshot=null)}),t.setActiveRanges([])}else{let e=this._shTextureCount>0?{textureCount:this._shTextureCount}:void 0,t=this._needsRotationScale?{}:void 0;this._workBuffer=new Hv(this._scene,c,void 0,e,t),this._readbackCandidate=this._workBuffer.supportsAsyncCentersReadback;let n=new Float32Array(c*4),r=this._workBuffer.textures,i=e?this._workBuffer.shTextures:void 0,a=t?this._workBuffer.rotationTextures:void 0;this._setExternalWorkBuffer(r[0],r[1],r[2],r[3],n,c,i,this._streamSh
699Degree,a),this.setSplatIndexRanges([]),this.setEnabled(!0)}if(!(this._host&&this._workBuffer&&(await this._waitForCanBackupAsync(this._workBuffer),this._disposed))){this._environmentRange&&this._environmentFiles&&await this._decodeEnvironmentAsync(),this._environmentFiles=null;for(let e of n){if(this._disposed)return;if(!await this._decodeFileAsync(e))throw Error(`GaussianSplattingStream: required coarse file ${e} failed to decode.`)}if(!this._disposed){for(let e of this._leafNodes)if(e.activeLod!==e.baseLod||e.activeFile===void 0)throw Error(`GaussianSplattingStream: the complete coarse layer could not be activated.`);if(this._baseLayerReady=!0,this._resolvePartReady(),r){let e=t.filter(e=>!this._baseFileIds.has(e));if(await this._gatherCountsAsync(e,!1),this._resolveLod0SplatCount(),this._metadataReady=!0,this._disposed)return}this._lodObserver||=this._scene.onBeforeRenderObservable.add(()=>this._onLodFrame())}}}async _waitForCanBackupAsync(e){for(let t=0;t<600&&!this._disposed;t++){if(e.canBackup)return;await new Promise(e=>this._scene.onBeforeRenderObservable.addOnce(()=>e()))}!this._disposed&&!e.canBackup&&A.Warn(`GaussianSplattingStream: backup/restore copy shaders did not compile in time; a grow/compaction before they are ready may drop streamed data.`)}_resolveResidentBudget(t=null,n=0){let r=this._maxResidentSplats>0||this._memoryBudgetMb>0,i=this._maxResidentSplats>0?this._maxResidentSplats:1/0,a=this._bytesPerResidentSplat();if(this._memoryBudgetMb>0){let e=Math.floor(this._memoryBudgetMb*1024*1024/a);i=Math.min(i,e)}if(!r&&t!==null)i=t;else if(r)i<this._minimumResidentSplats&&A.Warn(`GaussianSplattingStream: the requested initial residency (${i} splats) is below the complete coarse minimum (${this._minimumResidentSplats}); using the minimum.`);else{let t=this._scene.getEngine().hostInformation?.isMobile?ty:ey,r=Math.floor(t*1024*1024/a),o=Math.max(0,Math.floor(n)),s=e._SafeAddCounts(this._minimumResidentSplats,o,`automatic resident capacity`);i=Math.max(r,s)}if(i=Math.max(this._minimumResidentSplats,Math.floor(i)),t!==null&&(i=Math.min(i,t)),t!==null||this._minimumResidentSplats>0){let e=Math.floor(this._scene.getEngine().getCaps().maxTextureSize),t=e*e;if(!Number.isSafeInteger(t)||this._minimumResidentSplats>t||(i>t&&(i=t),i<this._minimumResidentSplats))throw Error(`GaussianSplattingStream: minimum resident splat count ${this._minimumResidentSplats} exceeds the device texture capacity ${t}.`)}if(!Number.isSafeInteger(i)||i<this._minimumResidentSplats||i<1)throw Error(`GaussianSplattingStream: resolved resident capacity is invali
699d.`);return this._residentBudget=i,i}_bytesPerResidentSplat(){let e=this._scene.getEngine().getCaps().textureHalfFloatRender?24:48;return Xv+this._shTextureCount*16+(this._needsRotationScale?e:0)}_collectAllFileIds(){let e=new Set;for(let t of this._leafNodes)for(let n of t.availableLevels){let r=t.lods[String(n)];r&&e.add(r.file)}return Array.from(e).sort((e,t)=>e-t)}_collectBaseFileIds(){let e=new Set;for(let t of this._leafNodes){let n=t.lods?.[String(t.baseLod)];n&&e.add(n.file)}return Array.from(e).sort((e,t)=>e-t)}_resolveMinimumResidentSplats(t,n){let r=e._SafeAddCounts(1,Math.max(0,Math.floor(n)),`minimum resident splats`);for(let n of t){let t=this._fileCounts.get(n);if(t===void 0||!Number.isSafeInteger(t)||t<=0)throw Error(`GaussianSplattingStream: required coarse metadata for file ${n} is unavailable or invalid.`);r=e._SafeAddCounts(r,t,`minimum resident splats`)}this._minimumResidentSplats=r}_resolveLod0SplatCount(){let e=0,t=!1;for(let n of this._leafNodes){if(n.availableLevels?.[0]!==0)continue;let r=n.lods?.[`0`];if(!r){this._lod0SplatCount=Object.freeze({status:`unavailable`});return}if(t=!0,!this._fileCounts.has(r.file)||!this._fileMeta.has(r.file)){this._lod0SplatCount=Object.freeze({status:`unavailable`});return}if(e+=r.count,!Number.isSafeInteger(e)){this._lod0SplatCount=Object.freeze({status:`unavailable`});return}}this._lod0SplatCount=Object.freeze(t?{status:`available`,count:e}:{status:`unavailable`})}async _gatherCountsAsync(t,n=!0){let r=0,i=0,a=0,o=t=>{let n=e._GetShInfo(t);n.degree>i&&(i=n.degree),n.coeffs>a&&(a=n.coeffs)};if(n&&this._metadata.environment)try{let t=this._rootUrl+this._metadata.environment,n=await this._downloadManager.loadFileAsync(t),i=await this._unzipAsync(new Uint8Array(n)),a=i.get(`meta.json`);if(a){let t=JSON.parse(new TextDecoder().decode(a));r=e._GetSplatCount(t),o(t),this._environmentFiles=i}}catch(e){A.Warn(`GaussianSplattingStream: failed to load environment: `+(e?.message??e))}await Promise.all(t.map(async t=>{let n=this._metadata.filenames[t];if(!n){A.Warn(`GaussianSplattingStream: missing filename for file index ${t}.`);return}try{let r=this._rootUrl+n,i=r.substring(0,r.lastIndexOf(`/`)+1),a=await this._downloadManager.loadFileAsync(r),o=JSON.parse(new TextDecoder().decode(new Uint8Array(a)));this._fileCounts.set(t,e._GetSplatCount(o)),this._fileMeta.set(t,{sogData:o,subRootUrl:i})}catch(e){A.Warn(`GaussianSplattingStream: failed to load metadata for ${n}: ${e?.message??e}`)}}));for(let{sogData:e}of this._fileMeta.values())o(e);return this._decodeSh&&i>0&&a>0&&(this._streamShDegree=Math.max(this._streamShDegree,i),this._shTextureCount=Math.max(this._shTextureCount,Math.ceil(a*3/16))),r}_enqueueDecode(e){this._decodedFiles.has(e)||this._loadingFiles.has(e)||!this._fileMeta.has(e)||this._decodeQueue.indexOf(e)===-1&&this._decodeQueue.push(e)}_pumpDecodeQueue(){let e=0;for(;this._decodeQueue.length>0&&e<this._maxDecodesPerFrame;){let t=this._decodeQueue.shift();this._decodedFiles.has(t)||this._loadingFiles.has(t)||(e++,this._decodeFileAsync(t).catch(e=>{A.Warn(`GaussianSplattingStream: decode failed: `+(e?.message??e))}))}}_applyPositions(e,t,n){this._splatPositions.set(e,(this._positionBase+t)*4),this._updateBounds(e,n),this._sinkPostPositionsRange(t,n)}_sinkSetActiveRanges(e){this._host?this._host.setActiveRanges(e):this.setSplatIndexRanges(e)}_sinkPostPositionsRange(e,t){this._host?this._host.postPositionsRange(e,t):this._postWorkerPositionsRange(e,t)}_sinkNotifyDataChanged(){this._host?this._host.notifyDataChanged():this._notifyWorkerNewData()}get _sinkIsDepthSortSettled(){return this._host?this._host.isDepthSortSettled:this._isDepthSortSettled}async _probeReadbackAsync(e,t,n){if(this._readbackProbed=!0,!this._workBuffer)return;let r=Math.min(t,1024),i=!1;try{let t=await this._workBuffer.readCentersRangeAsync(e,r);if(this._disposed)return;if(t&&t.length>=r*4){i=!0;for(let e=0;e<r&&i;e++)for(let r=0;r<3;r++){let a=t[e*4+r],o=n[e*4+r];if(Math.abs(a-o)>.01*(1+Math.abs(o))){i=!1;break}}}}catch{i=!1}this._useGpuPositionReadback=i,A.Log(i?`GaussianSplattingStream: GPU position readback validated; streamed LOD positions are read back from the GPU.`:`GaussianSplattingStream: GPU position readback unavailable; decoding LOD positions on the CPU.`)}async _applyDecodedPositionsAsync(e,t,n){if(this._useGpuPositionReadback&&this._workBuffer){let e=await this._workBuffer.readCentersRangeAsync(t,n);if(this._disposed)return!1;if(e&&this._splatPositions)return this._applyPositions(e,t,n),!0}let r=e.positions.length>=n*4?e.positions.subarray(0,n*4):null;return!r||!this._splatPositions?!1:(this._applyPositions(r,t,n),!this._readbackProbed&&this._readbackCandidate&&await this._probeReadbackAsync(t,n,r),
699!0)}async _decodeEnvironmentAsync(){if(!this._environmentRange||!this._environmentFiles||!this._workBuffer)return;let t=this._environmentRange,n=!1;try{let r=(await Sv(this._environmentFiles,``,this._scene,!this._useGpuPositionReadback,this._downloadManager)).sogTextures;if(!r){A.Warn(`GaussianSplattingStream: environment decoding produced no texture data.`);return}try{if(this._disposed||!this._workBuffer||(await this._workBuffer.decodeAsync(r,t.offset),this._disposed))return;let e=await this._applyDecodedPositionsAsync(r,t.offset,t.count);if(this._disposed)return;if(!e){A.Warn(`GaussianSplattingStream: decoded positions could not be applied for the environment.`);return}if(this._residency?.pin(Yv,t.count)!==t.offset)throw Error(`GaussianSplattingStream: decoded environment could not be pinned.`);n=!0,this._refreshActiveRanges()}finally{e._DisposePack(r)}}catch(e){A.Warn(`GaussianSplattingStream: failed to decode environment: `+(e?.message??e))}finally{n||(this._residency?.free(Yv),this._environmentRange=null)}}async _decodeFileAsync(t){if(this._decodedFiles.has(t))return!0;if(this._loadingFiles.has(t)||!this._residency)return!1;let n=this._fileMeta.get(t),r=this._fileCounts.get(t);if(!n||r===void 0)return!1;this._loadingFiles.add(t),this._cancelledDecodes.delete(t);let i=!1;try{let a=(await Sv(n.sogData,n.subRootUrl,this._scene,!this._useGpuPositionReadback,this._downloadManager,t)).sogTextures;if(!a)return!1;let o=await this._acquireDecodeGateAsync();try{if(this._disposed||!this._workBuffer||this._cancelledDecodes.has(t))return!1;let e=this._residency;if(!e)return!1;let n=e.allocate(t,r);if(n===null&&(n=await this._relayoutAndAllocateAsync(t,r)),n===null)return this._cancelledDecodes.has(t)||A.Warn(`GaussianSplattingStream: resident memory budget full; skipping LOD file ${t}.`),!1;if(i=!0,this._disposed||!this._workBuffer||this._cancelledDecodes.has(t)||(await this._workBuffer.decodeAsync(a,n),this._disposed||this._cancelledDecodes.has(t)))return!1;let o=await this._applyDecodedPositionsAsync(a,n,r);if(this._disposed)return!1;if(!o)return A.Warn(`GaussianSplattingStream: decoded positions could not be applied for LOD file ${t}.`),!1;if(this._baseFileIds.has(t)&&e.pin(t,r)!==n)throw Error(`GaussianSplattingStream: required coarse file ${t} could not be pinned.`);return this._decodedFiles.add(t),this._applyDesiredLods()&&this._refreshActiveRanges(),!0}finally{e._DisposePack(a),o()}}catch(e){if(!this._cancelledDecodes.has(t))throw e;return!1}finally{i&&!this._decodedFiles.has(t)&&this._residency?.free(t),this._loadingFiles.delete(t),this._cancelledDecodes.delete(t)}}async _acquireDecodeGateAsync(){let e=this._decodeGate,t;return this._decodeGate=new Promise(e=>{t=e}),await e,t}async _relayoutAndAllocateAsync(e,t){return!this._residency||!this._workBuffer||this._residency.freeSize<t?null:await new Promise(n=>{let r=()=>{if(this._disposed||!this._residency||!this._workBuffer||this._cancelledDecodes.has(e)){n(null);return}if(!this._workBuffer.isRelayoutReady()){this._scene.onBeforeRenderObservable.addOnce(r);return}this._performRelayout(),n(this._residency.allocate(e,t))};this._scene.onBeforeRenderObservable.addOnce(r)})}_performRelayout(){if(!this._residency||!this._workBuffer||!this._splatPositions)return;let e=this._relayoutOldOffsets;e.clear();for(let t of this._residency.getResidentBlocks())e.set(t.file,t.offset);if(this._residency.compact().length===0)return;let t=this._residency.capacity;(!this._relayoutSrcIndex||this._relayoutSrcIndex.length!==t)&&(this._relayoutSrcIndex=new Float32Array(t));let n=this._relayoutSrcIndex;n.fill(-1);let r=this._residency.getResidentBlocks();for(let t of r){let r=e.get(t.file);for(let e=0;e<t.count;e++)n[t.offset+e]=r+e}this._workBuffer.relayoutSync(n);let i=this._splatPositions,a=this._positionBase;r.sort((e,t)=>e.offset-t.offset);for(let t of r){let n=e.get(t.file);n!==t.offset&&i.copyWithin((a+t.offset)*4,(a+n)*4,(a+n+t.count)*4)}if(this._environmentRange){let e=this._residency.offset(Yv);e!==void 0&&(this._environmentRange.offset=e)}this._sinkNotifyDataChanged(),this._refreshActiveRanges()}_onFileEvicted(e){this._decodedFiles.delete(e)}_cappedLevelForNode(e,t){let n=e.availableLevels,r=this._maxDetail
699Lod,i=-1,a=1/0;for(let e of n){if(e<r)continue;let n=Math.abs(e-t);n<a&&(i=e,a=n)}return i<0?e.baseLod:i}_computeTargetLevels(){let e=this._effectiveSplatBudget();if(e<=0){for(let e of this._leafNodes){let t=e.optimalLod??e.baseLod;e.targetLevel=this._cappedLevelForNode(e,t)}return}let t=Math.max(0,e-this._environmentSplatCount());this._convergePixelThreshold(t);let n=this._lodPixelThreshold;for(let e of this._leafNodes)e.targetLevel=this._budgetedLevel(e,n)}_environmentSplatCount(){let e=this._environmentRange?Math.floor(Number(this._environmentRange.count)):0;return Number.isFinite(e)&&e>0?e:0}_budgetedLevel(e,t){let n=e.optimalLod??e.baseLod,r=e.pixelSize??0,i=0;return r>0&&t>r&&(i=Math.max(0,Math.round(Math.log(t/r)/Math.log(this._lodMultiplier)))),this._cappedLevelForNode(e,n+i)}_countAtLevel(e,t){let n=e.lods[String(t)];return n?n.count:0}_totalSplatsAtThreshold(e){let t=0;for(let n of this._leafNodes)t+=this._countAtLevel(n,this._budgetedLevel(n,e));return t}_convergePixelThreshold(e){if(this._totalSplatsAtThreshold(1)<=e){this._lodPixelThreshold=1;return}let t=1;for(let e of this._leafNodes)e.pixelSize&&e.pixelSize>t&&(t=e.pixelSize);
699let n=Math.min(32,Math.max(1,this._metadata.lodLevels)),r=t*this._lodMultiplier**+(n+1);if(this._totalSplatsAtThreshold(r)>e){this._lodPixelThreshold=r;return}let i=1,a=r;for(let t=0;t<40&&a-i>.001*a;t++){let t=.5*(i+a);this._totalSplatsAtThreshold(t)<=e?a=t:i=t}this._lodPixelThreshold=a}_residentLevelAtLeast(e,t){for(let n of e.availableLevels)if(n>=t&&this._decodedFiles.has(e.lods[String(n)].file))return n;return null}_applyDesiredLods(){let e=!1;for(let t of this._leafNodes){let n=t.targetLevel??t.baseLod;if(this._splatBudgetEnabled()&&t.activeLod!==void 0&&t.activeLod<n){let r=this._residentLevelAtLeast(t,n);r!==null&&r!==t.activeLod&&(this._switchActiveFile(t,t.lods[String(r)].file),t.activeLod=r,t.lodCooldown=this._lodCooldownFrames,e=!0)}if(t.lodCooldown&&t.lodCooldown>0)continue;let r;if(n!==t.activeLod){let i=t.lods[String(n)];i&&(this._decodedFiles.has(i.file)?(this._switchActiveFile(t,i.file),t.activeLod=n,t.lodCooldown=this._lodCooldownFrames,e=!0):r=i.file)}t.pendingFile!==r&&(t.pendingFile!==void 0&&this._releaseFileRef(t.pendingFile),r!==void 0&&this._acquirePendingFile(r),t.pendingFile=r)}return e}_switchActiveFile(e,t){e.activeFile!==t&&(e.activeFile!==void 0&&this._releaseFileRef(e.activeFile),this._acquireFileRef(t),e.activeFile=t)}_acquireFileRef(e){let t=(this._fileRefs.get(e)??0)+1;this._fileRefs.set(e,t),t===1&&this._residency?.cancelEviction(e)}_acquirePendingFile(e){this._acquireFileRef(e),this._enqueueDecode(e)}_releaseFileRef(e){let t=(this._fileRefs.get(e)??0)-1;if(t>0){this._fileRefs.set(e,t);return}if(this._fileRefs.delete(e),this._decodedFiles.has(e)){this._evictionEnabled&&this._residency?.scheduleEviction(e);return}let n=this._decodeQueue.indexOf(e);n!==-1&&this._decodeQueue.splice(n,1),this._loadingFiles.has(e)&&(this._cancelledDecodes.add(e),this._downloadManager.cancelGroup(e))}_onLodFrame(){if(this._disposed||!this._baseLayerReady)return;let e=!1;for(let t of this._leafNodes)t.lodCooldown&&t.lodCooldown>0&&(t.lodCooldown--,t.lodCooldown===0&&t.targetLevel!==void 0&&t.targetLevel!==t.activeLod&&(e=!0));this._evictionEnabled&&this._residency?.tick(),this._pumpDecodeQueue();let t=this._updateNodeFrustum(),n=this._forceLodUpdate||t||e;if(!n&&++this._framesSinceLodUpdate>=this._lodUpdateInterval){let e=this._getActiveLodCameras(),t=this._lodUpdateDistance;if(e.length!==this._lastLodCamPositions.length||this._computeLodSignature(e)!==this._lastLodSignature)n=!0;else for(let r=0;r<e.length;r++)if(R.DistanceSquared(e[r].globalPosition,this._lastLodCamPositions[r])>=t*t){n=!0;break}}if(n){this._forceLodUpdate=!1,this._framesSinceLodUpdate=0;let e=this._getActiveLodCameras();this._lastLodCamPositions.length=0;for(let t of e)this._lastLodCamPositions.push(t.globalPosition.clone());this._lastLodSignature=this._computeLodSignature(e),this.evaluateOptimalLods(),this._computeTargetLevels(),this._applyDesiredLods()&&this._refreshActiveRanges()}}_computeLodSignature(e){let t=this._scene.getEngine(),n=`${t.getRenderWidth()}x${t.getRenderHeight()}#${this._getEffectiveWorldMatrix(!1).updateFlag}`;for(let t of e){let e=t.viewport;n+=`|${t.uniqueId}:${t.fov}:${t.fovMode}:${e.x},${e.y},${e.width},${e.height}`}return n}_updateNodeFrustum(){let e=this._getActiveLodCameras(),t=!1;
699if(!this._frustumCulling||e.length===0){for(let e of this._leafNodes)e.inFrustum===!1&&(e.inFrustum=!0,t=!0);return t}let n=this._leafNodes,r=this._frustumScratch,i=this._getEffectiveWorldMatrix(!1);for(let e=0;e<n.length;e++)r[e]=!1;for(let t of e){t.getViewMatrix().multiplyToRef(t.getProjectionMatrix(),this._cullCameraViewProj),i.multiplyToRef(this._cullCameraViewProj,this._cullViewProj),cn.GetPlanesToRef(this._cullViewProj,this._frustumPlanes);let e=!0;for(let t of this._frustumPlanes)if(!Number.isFinite(t.normal.x)||!Number.isFinite(t.normal.y)||!Number.isFinite(t.normal.z)||!Number.isFinite(t.d)||t.normal.lengthSquared()===0){e=!1;break}if(!e){for(let e=0;e<n.length;e++)r[e]=!0;continue}for(let e=0;e<n.length;e++)!r[e]&&n[e].cullBounds.isInFrustum(this._frustumPlanes)&&(r[e]=!0)}for(let e=0;e<n.length;e++)r[e]!==n[e].inFrustum&&(n[e].inFrustum=r[e],t=!0);return t}static _NormalizeResidentLimit(e,t,n){if(!Number.isFinite(e))throw RangeError(`GaussianSplattingStream: ${t} must be finite.`);if(e<=0)return 0;let r=n?Math.max(1,Math.floor(e)):e;if(r>2**53-1)throw RangeError(`GaussianSplattingStream: ${t} is outside the supported range.`);return r}static _SafeAddCounts(e,t,n){let r=e+t;if(!Number.isSafeInteger(e)||e<0||!Number.isSafeInteger(t)||t<0||!Number.isSafeInteger(r))throw Error(`GaussianSplattingStream: ${n} exceeds the supported integer range.`);return r}static _GetSplatCount(e){let t=e.count??(Array.isArray(e.means.shape)?e.means.shape[0]:0),n=Math.floor(Number(t));return Number.isFinite(n)&&n>0?n:0}static _GetShInfo(e){if(!e.shN)return{degree:0,coeffs:0};let t=0,n=e.shN.bands;if(typeof n==`number`&&Number.isFinite(n)&&n>0)t=Math.floor(n);else if(Array.isArray(e.shN.shape)&&Number.isFinite(e.shN.shape[1])&&e.shN.shape[1]>0){let n=Math.floor(e.shN.shape[1]/3);t=n>0?Math.round(Math.sqrt(n+1)-1):0}return t>0?(t>Zv&&(A.Warn(`GaussianSplattingStream: SH degree ${t} exceeds the maximum supported (${Zv}); clamping.`),t=Zv),{degree:t,coeffs:(t+1)**2-1}):{degree:0,coeffs:0}}static _DisposePack(e){e.meansTextureL.dispose(),e.meansTextureU.dispose(),e.scalesTexture.dispose(),e.quatsTexture.dispose(),e.sh0Texture.dispose(),e.shCentroidsTexture?.dispose(),e.shLabelsTexture?.dispose(),e.codebookTexture?.dispose()}_updateBounds(e,t){let n=this._boundsMin,r=this._boundsMax;for(let i=0;i<t;i++){let t=e[i*4+0],a=e[i*4+1],o=e[i*4+2];n.minimizeInPlaceFromFloats(t,a,o),r.maximizeInPlaceFromFloats(t,a,o)}this._host?this._host.expandBounds(n,r):this.setBoundingInfo(new Gn(n,r))}_refreshActiveRanges(){let t=[];this._environmentRange&&t.push({offset:this._environmentRange.offset,count:this._environmentRange.count});for(let e of this._leafNodes){if(e.activeLod===void 0)continue;let n=e.lods[String(e.activeLod)];if(!n)continue;let r=this._residency?.offset(n.file);r!==void 0&&t.push({offset:r+n.offset,count:n.count})}this._sinkSetActiveRanges(e._CoalesceRanges(t))}static _CoalesceRanges(e){if(e.length<=1)return e;let t=e.slice().sort((e,t)=>e.offset-t.offset),n=[{offset:t[0].offset,count:t[0].count}];for(let e=1;e<t.length;e++){let r=n[n.length-1],i=t[e],a=r.offset+r.count;i.offset<=a?r.count=Math.max(a,i.offset+i.count)-r.offset:n.push({offset:i.offset,count:i.count})}return n}async _unzipAsync(e){let t=this._streamOptions.fflate;t||=(window.fflate===void 0&&await P.LoadScriptAsync(this._streamOptions.deflateURL??`https://unpkg.com/fflate/umd/index.js`),window.fflate);let n=t.unzipSync(e),r=new Map;for(let[e,t]of Object.entries(n))r.set(e,t);return r}};Qt(),Qe(),sn(),dr();var dy=32768,fy=.28209479177387814,py=null,my=null;function hy(e,t,n){let r=new Uint8Array(e),i=new Uint32Array(e.slice(0,12)),a=i[2],o=r[12],s=r[13],c=r[14],l=r[15],u=i[1];if(l||i[0]!=1347635022||u<2||u>4)return new Promise(e=>{e({mode:3,data:new ArrayBuffer(0),hasVertexColors:!1})});let d=new ArrayBuffer(32*a),f=1/(1<<s),p=new Int32Array(1),m=new Uint8Array(p.buffer),h=function(e,t){return m[0]=e[t+0],m[1]=e[t+1],m[2]=e[t+2],m[3]=e[t+2]&128?255:0,p[0]*f},g=16,_=new Float32Array(d),v=new Float32Array(d),y=new Uint8ClampedArray(d),b=new Uint8ClampedArray(d);for(let e=0;e<a;e++)_[e*8+0]=h(r,g+0),_[e*8+1]=h(r,g+3),_[e*8+2]=h(r,g+6),g+=9;for(let e=0;e<a;e++){for(let t=0;t<3;t++){let n=(r[g+a+e*3+t]-127.5)/38.25;y[e*32+24+t]=we.Clamp((.5+fy*n)*255,0,255)}y[e*32+24+3]=r[g+e]}g+=a*4;
699for(let e=0;e<a;e++)v[e*8+3+0]=Math.exp(r[g+0]/16-10),v[e*8+3+1]=Math.exp(r[g+1]/16-10),v[e*8+3+2]=Math.exp(r[g+2]/16-10),g+=3;if(u>=3){let e=Math.SQRT1_2;for(let t=0;t<a;t++){let n=[r[g+0],r[g+1],r[g+2],r[g+3]],i=n[0]+(n[1]<<8)+(n[2]<<16)+(n[3]<<24),a=[],o=i>>>30,s=i,c=0;for(let t=3;t>=0;--t)if(t!==o){let n=s&511,r=s>>>9&1;s>>>=10,a[t]=n/511*e,r===1&&(a[t]=-a[t]),c+=a[t]*a[t]}let l=1-c;a[o]=Math.sqrt(Math.max(l,0));let u=[3,0,1,2];for(let e=0;e<4;e++)b[t*32+28+e]=Math.round(127.5+a[u[e]]*127.5);g+=4}}else for(let e=0;e<a;e++){let t=r[g+0],n=r[g+1],i=r[g+2],a=t/127.5-1,o=n/127.5-1,s=i/127.5-1;b[e*32+28+1]=t,b[e*32+28+2]=n,b[e*32+28+3]=i;let c=1-(a*a+o*o+s*s);b[e*32+28+0]=127.5+Math.sqrt(c<0?0:c)*127.5,g+=3}if(o){let e=((o+1)*(o+1)-1)*3,n=Math.ceil(e/16),i=g,s=t.getEngine().getCaps().maxTextureSize,l=Math.ceil(a/s),u=Ht(n,l*s*4*4);for(let t=0;t<a;t++)for(let n=0;n<e;n++){let e=r[i++],a=u[Math.floor(n/16)],o=n%16,s=t*16;a[o+s]=e}return new Promise(e=>{e({mode:0,data:d,hasVertexColors:!1,sh:u,shDegree:o,trainedWithAntialiasing:!!c})})}return new Promise(e=>{e({mode:0,data:d,hasVertexColors:!1,trainedWithAntialiasing:!!c})})}async function gy(e){if(py&&my===e)return await py;let t=An(`import createSpzModule from '${e}'; 700 const module = await createSpzModule(); 701 const returnedValue = module;`);return my=e,py=t,await t}function*_y(e,t,n=!1){let r=e.numPoints,i=new ArrayBuffer(32*r),a=new Float32Array(i),o=new Uint8Array(i),s=e.positions,c=e.scales,l=e.colors,u=e.alphas,d=e.rotations,f=null,p=e.shDegree,m=null,h=0,g=null,_=null,v=null;if(p>0&&e.sh.length>0){h=((p+1)*(p+1)-1)*3;let n=Math.ceil(h/16),i=t.getEngine().getCaps().maxTextureSize,a=Math.ceil(r/i);f=Ht(n,a*i*4*4),g=new Int32Array(n),_=new Int32Array(n);for(let e=0;e<n;e++)g[e]=e*16,_[e]=Math.min((e+1)*16,h);v=f,m=e.sh}for(let e=0;e<r;e++){let t=e*8,r=e*32,i=e*3,f=e*4;a[t+0]=s[i+0],a[t+1]=s[i+1],a[t+2]=s[i+2],a[t+3]=Math.exp(c[i+0]),a[t+4]=Math.exp(c[i+1]),a[t+5]=Math.exp(c[i+2]);let p=(.5+fy*l[i+0])*255,y=(.5+fy*l[i+1])*255,b=(.5+fy*l[i+2])*255;o[r+24]=p<=0?0:p>=255?255:p+.5|0,o[r+25]=y<=0?0:y>=255?255:y+.5|0,o[r+26]=b<=0?0:b>=255?255:b+.5|0,o[r+27]=1/(1+Math.exp(-u[e]))*255+.5|0;let x=d[f+3]*127.5+127.5,S=d[f+0]*127.5+127.5,C=d[f+1]*127.5+127.5,w=d[f+2]*127.5+127.5;if(o[r+28]=x<=0?0:x>=255?255:x+.5|0,o[r+29]=S<=0?0:S>=255?255:S+.5|0,o[r+30]=C<=0?0:C>=255?255:C+.5|0,o[r+31]=w<=0?0:w>=255?255:w+.5|0,m&&v&&g&&_){let t=e*h,n=e*16;for(let e=0;e<v.length;e++){let r=v[e],i=g[e],a=_[e];for(let e=i;e<a;e++){let a=m[t+e]*128+128;r[n+e-i]=a<=0?0:a>=255?255:a+.5|0}}}e%dy===0&&n&&(yield)}let y,b;if(e.extensions)for(let t of e.extensions){let e=t;if(e.safeOrbitRadiusMin!==void 0){y=e.safeOrbitRadiusMin,b=[e.safeOrbitElevationMin,e.safeOrbitElevationMax];break}}return{mode:0,data:i,hasVertexColors:!1,sh:f===null?void 0:f,shDegree:p>0?p:void 0,trainedWithAntialiasing:!!e.antialiased,safeOrbitCameraRadiusMin:y,safeOrbitCameraElevationMinMax:b}}async function vy(e,t){return await xt(_y(e,t,!0),vt())}var yy=e({RegisterSPLATFileLoader:()=>Sy,SPLATFileLoader:()=>by});ee(),En(),We(),Rn(),yt(),zn(),_(),ct(),wt();var by=class e{constructor(t={}){this.name=l.name,this._assetContainer=null,this.extensions=l.extensions,this._loadingOptions={...e._DefaultLoadingOptions,...t}}createPlugin(t){return new e(t[l.name])}async importMeshAsync(e,t,n,r,i,a){let o=this._tryCreateLODStream(t,n,r);return o?{meshes:[o],particleSystems:[],skeletons:[],animationGroups:[],transformNodes:[],geometries:[],lights:[],spriteManagers:[]}:await this._parseAsync(e,t,n,r).then(e=>({meshes:e,particleSystems:[],skeletons:[],animationGroups:[],transformNodes:[],geometries:[],lights:[],spriteManagers:[]}))}_tryCreateLODStream(e,t,n){if(typeof t!=`string`)return null;let r;try{r=JSON.parse(t)}catch{return null}if(!uy.IsLODMetadata(r))return null;let i=e._blockEntityCollection;e._blockEntityCollection=!!this._assetContainer;try{let t=new uy(`GaussianSplattingStream`,r,n,e,{deflateURL:this._loadingOptions.deflateURL,fflate:this._loadingOptions.fflate});return t._parentContainer=this._assetContainer,t}finally{e._blockEntityCollection=i}}static _BuildPointCloud(e,t){if(!t.byteLength)return!1;let n=new Uint8Array(t),r=new Float32Array(t),i=n.length/32;return e.addPoints(i,function(e,t){let i=r[8*t+0],a=r[8*t+1],o=r[8*t+2];e.position=new R(i,a,o);let s=n[32*t+24+0]/255,c=n[32*t+24+1]/255,l=n[32*t+24+2]/255;e.color=new F(s,c,l,1)}),!0}static _BuildMesh(e,t){let n=new At(`PLYMesh`,e),r=new Uint8Array(t.data),i=new Float32Array(t.data),a=r.length/32,o=[],s=new E;for(let e=0;e<a;e++){let t=i[8*e+0],n=i[8*e+1],r=i[8*e+2];o.push(t,n,r)}if(t.hasVertexColors){let e=new Float32Array(a*4);for(let t=0;t<a;t++){let n=r[32*t+24+0]/255,i=r[32*t+24+1]/255,a=r[32*t+24+2]/255;e[t*4+0]=n,e[t*4+1]=i,e[t*4+2]=a,e[t*4+3]=1}s.colors=e}return s.positions=o,s.indices=t.faces,s.applyToMesh(n),n}async _unzipWithFFlateAsync(e){let t=this._loadingOptions.fflate;t||=(window.fflate===void 0&&await P.LoadScriptAsync(this._loadingOptions.deflateURL??`https://unpkg.com/fflate/umd/index.js`),window.fflate);let{unzipSync:n}=t,r=n(e),i=new Map;for(let[e,t]of Object.entries(r))i.set(e,t);return i}_parseAsync(t,n,r,i){let a=[],o=t=>{n._blockEntityCollection=!!this._assetContainer;let r=this._loadingOptions.gaussianSplattingMesh??new Bt(`GaussianSplatting`,null,n,this._loadingOptions.keepInRam,this._loadingOptions.needsRotationScaleTextures);r._parentContainer=this._assetContainer,a.push(r),t.sogTextures?r.setSogTextureData(t.sogTextures):r.updateData(t.data,t.sh,{flipY:!1},void 0,t.shDegree),r.scaling.y*=-1,r.computeWorldMatrix(!0),r.safeOrbitCameraLim
701its=e._ExtractSafeOrbitLimits(t),n._blockEntityCollection=!1},s=n.getEngine(),c=this._loadingOptions.useSogTextures;c&&!s.isWebGPU&&s.version<2&&(A.Warn(`SPLATFileLoader: useSogTextures requires WebGL2 or WebGPU. Falling back to CPU path.`),c=!1);let l=c?Sv:_v;if(typeof r==`string`){let e=JSON.parse(r);if(e&&e.means&&e.scales&&e.quats&&e.sh0)return new Promise((t,r)=>{l(e,i,n).then(e=>{o(e),t(a)}).catch(e=>{r(Error(`Failed to parse SOG data.`,{cause:e}))})})}let u=r instanceof ArrayBuffer?new Uint8Array(r):r;if(u[0]===80&&u[1]===75)return new Promise((e,t)=>{this._unzipWithFFlateAsync(u).then(r=>{l(r,i,n).then(t=>{o(t),e(a)}).catch(e=>{t(Error(`Failed to parse SOG zip data.`,{cause:e}))})})});let d=t=>{e._ConvertPLYToSplat(r).then(async r=>{switch(n._blockEntityCollection=!!this._assetContainer,r.mode){case 0:{let t=this._loadingOptions.gaussianSplattingMesh??new Bt(`GaussianSplatting`,null,n,this._loadingOptions.keepInRam,this._loadingOptions.needsRotationScaleTextures);switch(t._parentContainer=this._assetContainer,a.push(t),t.updateData(r.data,r.sh,{flipY:!1},void 0,r.shDegree),t.scaling.y*=-1,r.chirality===`RightHanded`&&(t.scaling.y*=-1),r.upAxis){case`X`:t.rotation=new R(0,0,Math.PI/2);break;case`Y`:t.rotation=new R(0,0,Math.PI);break;case`Z`:t.rotation=new R(-Math.PI/2,Math.PI,0)}t.computeWorldMatrix(!0),t.safeOrbitCameraLimits=e._ExtractSafeOrbitLimits(r)}break;case 1:{let t=new Ut(`PointCloud`,1,n);e._BuildPointCloud(t,r.data)?await t.buildMeshAsync().then(e=>{a.push(e)}):t.dispose()}break;case 2:if(r.faces)a.push(e._BuildMesh(n,r));else throw Error(`PLY mesh doesn't contain face informations.`);break;default:throw Error(`Unsupported Splat mode`)}n._blockEntityCollection=!1,this.applyAutoCameraLimits(e._ExtractSafeOrbitLimits(r),n),t(a)})},f=u[0]===31&&u[1]===139,p=u[0]===78&&u[1]===71&&u[2]===83&&u[3]===80;if(!f&&!p)return new Promise(e=>{d(e)});let m=(t,r)=>{n._blockEntityCollection=!!this._assetContainer;let i=this._loadingOptions.gaussianSplattingMesh??new Bt(`GaussianSplatting`,null,n,this._loadingOptions.keepInRam,this._loadingOptions.needsRotationScaleTextures);if(t.trainedWithAntialiasing){let e=i.material;e.kernelSize=.1,e.compensation=!0}i._parentContainer=this._assetContainer,a.push(i),i.updateData(t.data,t.sh,{flipY:!1},void 0,t.shDegree),this._loadingOptions.flipY||(i.scaling.y*=-1,i.computeWorldMatrix(!0)),n._blockEntityCollection=!1;let o=e._ExtractSafeOrbitLimits(t);i.safeOrbitCameraLimits=o,this.applyAutoCameraLimits(o,n),r(a)};if(this._loadingOptions.spzLibraryUrl)return gy(this._loadingOptions.spzLibraryUrl).then(e=>vy(e.loadSpzFromBuffer(new Uint8Array(r),{to:e.CoordinateSystem.RUB}),n).then(e=>new Promise(t=>{m(e,t)})));if(p)return Promise.reject(Error(`SPZ V4+ files (NGSP format) are not supported by the native fallback loader. Please provide a valid 'spzLibraryUrl' in the loading options to use the WASM-based SPZ library, or ensure WebAssembly is available in your environment.`));let h=new ReadableStream({start(e){e.enqueue(new Uint8Array(r)),e.close()}}),g=new DecompressionStream(`gzip`),_=h.pipeThrough(g);return new Promise(e=>{new Response(_).arrayBuffer().then(t=>{hy(t,n,this._loadingOptions).then(t=>{m(t,e)})}).catch(()=>{d(e)})})}static _ExtractSafeOrbitLimits(e){return e.safeOrbitCameraRadiusMin===void 0&&e.safeOrbitCameraElevationMinMax===void 0?null:{radiusMin:e.safeOrbitCameraRadiusMin,elevationMinMax:e.safeOrbitCameraElevationMinMax}}applyAutoCameraLimits(e,t){if(!this._loadingOptions.disableAutoCameraLimits&&e&&t.activeCamera?.getClassName()===`ArcRotateCamera`){let n=t.activeCamera;e.elevationMinMax&&(n.lowerBetaLimit=Math.PI*.5-e.elevationMinMax[1],n.upperBetaLimit=Math.PI*.5-e.elevationMinMax[0]),e.radiusMin&&(n.lowerRadiusLimit=e.radiusMin)}}loadAssetContainerAsync(e,t,n){let r=new bt(e);return this._assetContainer=r,this.importMeshAsync(null,e,t,n).then(e=>{for(let t of e.meshes)r.meshes.push(t);return this._assetContainer=null,r}).catch(e=>{throw this._assetContainer=null,e})}loadAsync(e,t,n){return this.importMeshAsync(null,e,t,n).then(()=>{})}static _ConvertPLYToSplat(e){let t=new Uint8Array(e),n=new TextDecoder().decode(t.slice(0,10240)),r=n.indexOf(`end_header 702`);if(r<0||!n)return new Promise(t=>{t({mode:0,data:e,rawSplat:!0})});let i=parseInt(/element vertex (\d+)\n/.exec(n)[1]),a=/element face (\d+)\n/.exec(n),o=0;a&&(o=parseInt(a[1]));let s=/element chunk (\d+)\n/.exec(n),c=0;s&&(c=parseInt(s[1]));let l=0,u=0,d={double:8,int:4,uint:4,float:4,short:2,ushort:2,uint16:2,uchar:1,list:0},f={Vertex:0,Chunk:1,SH:2,Float_Tuple:3,Float:4,Uchar:5},p=f.Chunk,m=[],h=[],g=n.slice(0,r).split(` 703`),_={};for(let t of g)if(t.startsWith(`property `)){let[,n,r]=t.split(` `);if(p==f.Chunk)h.push({name:r,type:n,offset:u}),u+=d[n];else if(p==f.Vertex)m.push({name:r,type:n,offset:l}
703),l+=d[n];else if(p==f.SH)m.push({name:r,type:n,offset:l});else if(p==f.Float_Tuple){let t=new DataView(e,u,d.float*2);_.safeOrbitCameraElevationMinMax=[t.getFloat32(0,!0),t.getFloat32(4,!0)]}else if(p==f.Float)_.safeOrbitCameraRadiusMin=new DataView(e,u,d.float).getFloat32(0,!0);else if(p==f.Uchar){let t=new DataView(e,u,d.uchar);r==`up_axis`?_.upAxis=t.getUint8(0)==0?`X`:t.getUint8(0)==1?`Y`:`Z`:r==`chirality`&&(_.chirality=t.getUint8(0)==0?`LeftHanded`:`RightHanded`)}d[n]||A.Warn(`Unsupported property type: ${n}.`)}else if(t.startsWith(`element `)){let[,e]=t.split(` `);e==`chunk`?p=f.Chunk:e==`vertex`?p=f.Vertex:e==`sh`?p=f.SH:e==`safe_orbit_camera_elevation_min_max_radians`?p=f.Float_Tuple:e==`safe_orbit_camera_radius_min`?p=f.Float:(e==`up_axis`||e==`chirality`)&&(p=f.Uchar)}let v=l,y=u;return Bt.ConvertPLYWithSHToSplatAsync(e).then(async t=>{let n=new DataView(e,r+11),a=y*c+v*i,s=[];if(o)for(let e=0;e<o;e++){let e=n.getUint8(a);if(e==3){a+=1;for(let t=0;t<e;t++){let e=n.getUint32(a+(2-t)*4,!0);s.push(e)}a+=12}}if(c)return await new Promise(e=>{e({mode:0,data:t.buffer,sh:t.sh,shDegree:t.shDegree,faces:s,hasVertexColors:!1,compressed:!0,rawSplat:!1})});let l=0,u=0,d=[`x`,`y`,`z`,`scale_0`,`scale_1`,`scale_2`,`opacity`,`rot_0`,`rot_1`,`rot_2`,`rot_3`],f=[`red`,`green`,`blue`,`f_dc_0`,`f_dc_1`,`f_dc_2`];for(let e=0;e<m.length;e++){let t=m[e];d.includes(t.name)&&l++,f.includes(t.name)&&u++}
703let p=l==d.length&&u>=3,h=o?2:+!p;return await new Promise(e=>{e({..._,mode:h,data:t.buffer,sh:t.sh,shDegree:t.shDegree,faces:s,hasVertexColors:!!u,compressed:!1,rawSplat:!1})})})}};by._DefaultLoadingOptions={keepInRam:!1,flipY:!1,needsRotationScaleTextures:!1,spzLibraryUrl:typeof WebAssembly==`object`?`https://unpkg.com/@adobe/[email protected]/dist/spz.js`:void 0};var xy=!1;function Sy(){xy||(xy=!0,$e(new by))}var Cy=e({RegisterSTLFileLoader:()=>Ey,STLFileLoader:()=>wy});wt(),le(),Rn(),ee(),We();var wy=class e{constructor(){this.solidPattern=/solid (\S*)([\S\s]*?)endsolid[ ]*(\S*)/g,this.facetsPattern=/facet([\s\S]*?)endfacet/g,this.normalPattern=/normal[\s]+([-+]?[0-9]+\.?[0-9]*([eE][-+]?[0-9]+)?)+[\s]+([-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?)+[\s]+([-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?)+/g,this.vertexPattern=/vertex[\s]+([-+]?[0-9]+\.?[0-9]*([eE][-+]?[0-9]+)?)+[\s]+([-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?)+[\s]+([-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?)+/g,this.name=s.name,this.extensions=s.extensions}importMesh(e,t,n,r,i){let a;if(typeof n!=`string`){if(this._isBinary(n)){let e=new At(`stlmesh`,t);return this._parseBinary(e,n),i&&i.push(e),!0}n=new TextDecoder().decode(new Uint8Array(n))}for(;a=this.solidPattern.exec(n);){let n=a[1],r=a[3];if(r&&n!=r)return P.Error(`Error in STL, solid name != endsolid name`),!1;if(e&&n){if(e instanceof Array){if(!e.indexOf(n))continue}else if(n!==e)continue}n||=`stlmesh`;let o=new At(n,t);this._parseASCII(o,a[2]),i&&i.push(o)}return!0}load(e,t,n){return this.importMesh(null,e,t,n,null)}loadAssetContainer(e,t,n){let r=new bt(e);return e._blockEntityCollection=!0,this.importMesh(null,e,t,n,r.meshes),e._blockEntityCollection=!1,r}_isBinary(e){let t=new DataView(e);if(t.byteLength<=80)return!1;if(84+t.getUint32(80,!0)*50===t.byteLength)return!0;let n=[115,111,108,105,100];for(let e=0;e<5;e++)if(t.getUint8(e)!==n[e])return!0;return!1}_parseBinary(t,n){let r=new DataView(n),i=r.getUint32(80,!0),a=0,o=new Float32Array(i*3*3),s=new Float32Array(i*3*3),c=new Uint32Array(i*3),l=0;for(let t=0;t<i;t++){let n=84+t*50,i=r.getFloat32(n,!0),u=r.getFloat32(n+4,!0),d=r.getFloat32(n+8,!0);for(let t=1;t<=3;t++){let c=n+t*12;o[a]=r.getFloat32(c,!0),s[a]=i,e.DO_NOT_ALTER_FILE_COORDINATES?(o[a+1]=r.getFloat32(c+4,!0),o[a+2]=r.getFloat32(c+8,!0),s[a+1]=u,s[a+2]=d):(o[a+2]=r.getFloat32(c+4,!0),o[a+1]=r.getFloat32(c+8,!0),s[a+2]=u,s[a+1]=d),a+=3}e.DO_NOT_ALTER_FILE_COORDINATES?(c[l]=l,c[l+1]=l+2,c[l+2]=l+1,l+=3):(c[l]=l++,c[l]=l++,c[l]=l++)}t.setVerticesData(j.PositionKind,o),t.setVerticesData(j.NormalKind,s),t.setIndices(c),t.computeWorldMatrix(!0)}_parseASCII(t,n){let r=[],i=[],a=[],o=0,s;for(;s=this.facetsPattern.exec(n);){let t=s[1],n=this.normalPattern.exec(t);if(this.normalPattern.lastIndex=0,!n)continue;let c=[Number(n[1]),Number(n[5]),Number(n[3])],l;for(;l=this.vertexPattern.exec(t);)e.DO_NOT_ALTER_FILE_COORDINATES?(r.push(Number(l[1]),Number(l[3]),Number(l[5])),i.push(c[0],c[2],c[1])):(r.push(Number(l[1]),Number(l[5]),Number(l[3])),i.push(c[0],c[1],c[2]));e.DO_NOT_ALTER_FILE_COORDINATES?(a.push(o,o+2,o+1),o+=3):a.push(o++,o++,o++),this.vertexPattern.lastIndex=0}this.facetsPattern.lastIndex=0,t.setVerticesData(j.PositionKind,r),t.setVerticesData(j.NormalKind,i),t.setIndices(a),t.computeWorldMatrix(!0)}};wy.DO_NOT_ALTER_FILE_COORDINATES=!1;var Ty=!1;function Ey(){Ty||(Ty=!0,$e(new wy))}de(),Le(),bn();var Dy,Oy,ky,Ay,jy;(function(e){e[e.Scene=1]=`Scene`,e[e.Texture=2]=`Texture`,e[e.Material=3]=`Material`,e[e.TransformNode=4]=`TransformNode`,e[e.Skeleton=5]=`Skeleton`,e[e.Geometry=6]=`Geometry`,e[e.Mesh=7]=`Mesh`,e[e.Instance=8]=`Instance`,e[e.Animation=9]=`Animation`,e[e.AnalyticPrimitive=10]=`AnalyticPrimitive`,e[e.ThinInstances=11]=`ThinInstances`,e[e.MorphTarget=12]=`MorphTarget`})(jy||={});var My;(function(e){e[e.Cube=0]=`Cube`,e[e.Sphere=1]=`Sphere`,e[e.Cylinder=2]=`Cylinder`,e[e.Cone=3]=`Cone`})(My||={});var Ny;(function(e){e[e.X=0]=`X`,e[e.Y=1]=`Y`,e[e.Z=2]=`Z`})(Ny||={});var Py;(function(e){e[e.Node=0]=`Node`,e[e.Bone=1]=`Bone`,e[e.MorphTarget=2]=`MorphTarget`})(Py||={});var Fy;(function(e){e[e.Position=0]=`Position`,e[e.RotationQuaternion=1]=`RotationQuaternion`,e[e.Scaling=2]=`Scaling`,e[e.Matr
703ix=3]=`Matrix`,e[e.Influence=4]=`Influence`})(Fy||={});var Iy;(function(e){e[e.DoubleSided=1]=`DoubleSided`,e[e.Unlit=2]=`Unlit`,e[e.AlphaBlend=4]=`AlphaBlend`})(Iy||={});var Ly;(function(e){e[e.R=0]=`R`,e[e.G=1]=`G`,e[e.B=2]=`B`,e[e.A=3]=`A`,e[e.RGB=4]=`RGB`})(Ly||={});var Ry;(function(e){e[e.Auto=0]=`Auto`,e[e.Raw=1]=`Raw`,e[e.SRGB=2]=`SRGB`})(Ry||={});var zy;(function(e){e[e.DoubleSided=1]=`DoubleSided`,e[e.LeftHanded=2]=`LeftHanded`})(zy||={});var By;(function(e){e[e.Normals=1]=`Normals`,e[e.Tangents=2]=`Tangents`,e[e.Uv0=4]=`Uv0`,e[e.Colors=8]=`Colors`,e[e.Skin0=16]=`Skin0`,e[e.Skin1=32]=`Skin1`})(By||={});function Vy(e){switch(e){case 1:return 12;case 2:return 48;case 3:return 96;case 4:case 5:return 20;case 6:return 60;case 7:return 40;case 8:return 16;case 9:return 32;case 10:return 44;case 11:return 12;case 12:return 32;default:throw Error(`Unknown OpenUSD Babylon command opcode ${e}.`)}}function Hy(e){let t=new DataView(e);if(t.byteLength<16||t.getUint32(0,!0)!==1111774037)throw Error(`Invalid OpenUSD Babylon command buffer.`);if(t.getUint16(4,!0)!==5)throw Error(`Unsupported OpenUSD Babylon protocol ${t.getUint16(4,!0)}.`);let n=t.getUint32(8,!0),r=[],i=16;for(let e=0;e<n;++e){if(i+8>t.byteLength)throw Error(`Truncated OpenUSD Babylon command header.`);let e=t.getUint16(i,!0),n=t.getUint16(i+2,!0),a=t.getUint32(i+4,!0),o=i+8,s=Vy(e);if(a!==s)throw Error(`Invalid payload length ${a} for command ${e}; expected ${s}.`);if(o+a>t.byteLength)throw Error(`Truncated OpenUSD Babylon command payload.`);r.push({opcode:e,flags:n,payloadOffset:o,payloadLength:a}),i=o+a}if(i!==t.byteLength)throw Error(`Unexpected trailing data in OpenUSD Babylon command buffer.`);return r}var Uy=class{constructor(e,t,n){Dy.add(this),Oy.set(this,void 0),ky.set(this,void 0),lt(this,Oy,new DataView(e),`f`),this.offset=t,lt(this,ky,t+n,`f`)}u32(){D(this,Dy,`m`,Ay).call(this,4);let e=D(this,Oy,`f`).getUint32(this.offset,!0);return this.offset+=4,e}f32(){D(this,Dy,`m`,Ay).call(this,4);let e=D(this,Oy,`f`).getFloat32(this.offset,!0);return this.offset+=4,e}};Oy=new WeakMap,ky=new WeakMap,Dy=new WeakSet,Ay=function(e){if(this.offset+e>D(this,ky,`f`))throw Error(`OpenUSD Babylon command payload read exceeded its bounds.`)},ne(),mn(),We(),kn(),Un(),_(),zn(),lr(),Rt(),ot(),pr(),On(),Ln(),dn(),Rn(),me(),g(),ct(),Se();var Wy=class extends mt{dispose(){for(let e of this.animationGroups.splice(0))e.dispose();for(let e of this.meshes.splice(0))e.dispose();for(let e of this.morphTargetManagers.splice(0))e.dispose();for(let e of this.skeletons.splice(0))e.dispose();for(let e of this.multiMaterials.splice(0))e.dispose();for(let e of this.materials.splice(0))e.dispose();for(let e of this.geometries.splice(0))e.dispose();for(let e of this.transformNodes.splice(0))e.dispose();for(let e of this.textures.splice(0))e.dispose();this.rootNodes.length=0}},Gy=new TextDecoder,Ky=`__babylonUsdLocalMatrix`;function qy(e,t,n,r,i){if(!Number.isInteger(t)||!Number.isInteger(n)||t<0||n<0||t%Math.min(r,4)!==0||n>Math.floor((e.byteLength-t)/r))throw Error(`Invalid ${i} range in OpenUSD Babylon data buffer.`)}function Jy(e,t,n){return qy(e,t,n,1,`string`),Gy.decode(new Uint8Array(e,t,n))}function Yy(e,t){qy(e,t,16,4,`matrix`);let n=new Float32Array(e,t,16);return L.FromValues(n[0],n[1],n[2],n[3],n[4],n[5],n[6],n[7],n[8],n[9],n[10],n[11],n[12],n[13],n[14],n[15])}function Xy(e){switch(e){case 2:return`image/jpeg`;case 3:return`image/bmp`;case 4:return`image/webp`;default:return`image/png`}}function Zy(e){switch(e){case 0:return I.CLAMP_ADDRESSMODE;case 1:return I.WRAP_ADDRESSMODE;case 2:return I.MIRROR_ADDRESSMODE;default:throw Error(`Invalid texture wrap mode ${e}.`)}}async function Qy(e,t){if(!t)return await e;let n,r=new Promise((e,r)=>{n=()=>r(t.reason instanceof Error?t.reason:Error(`USD materialization was aborted.`)),t.addEventListener(`abort`,n,{once:!0}),t.aborted&&n()});try{return await Promise.race([e,r])}finally{n&&t.removeEventListener(`abort`,n)}}async function $y(e,t,n,r,i){i?.throwIfAborted();let a=performance.now(),o=Hy(t),s=r?new Wy:new bt(e),c=new Map,l=[],u=new Map,d=new Map,f=new Map,p=new Map,m=new Map,h=new Map,g=new Map,_=new Map,y=new Map,b=new Set,x=new Set,S=new Map,C=[],w=new Set,D=[],ee=new Map,te=s instanceof bt?s:void 0,O,ne=24,re=!1,ie=e.getEngine().getCaps(),ae=ie.textureHalfFloatRen
703der&&ie.textureHalfFloatLinearFiltering?k.TEXTURETYPE_HALF_FLOAT:ie.textureFloatRender&&ie.textureFloatLinearFiltering?k.TEXTURETYPE_FLOAT:k.TEXTURETYPE_UNSIGNED_BYTE,oe=(e,t)=>{e.push(t),te&&(t._parentContainer=te)},se=(t,n)=>{let r=!(n&2);t.sideOrientation=e.useRightHandedSystem===r?Tn.CounterClockWiseSideOrientation:Tn.ClockWiseSideOrientation},ce=(e,t)=>{let n=d.get(e);if(!n||!t||!n.backFaceCulling)return n??null;let r=f.get(e);return r||(r=n.clone(`${n.name} (double-sided)`),oe(s.materials,r),r.backFaceCulling=!1,r.twoSidedLighting=!0,f.set(e,r)),r},le=(e,t,n)=>{if(e===4294967295){if(t!==4294967295)throw Error(`USD ${n} binding has a channel without a texture.`);return}let r=u.get(e);if(!r)throw Error(`USD ${n} binding references missing texture ${e}.`);if(t<0||t>4)throw Error(`USD ${n} binding has invalid output channel ${t}.`);return{descriptor:r,channel:t}},ue=e=>{if(e===4)throw Error(`A scalar USD texture binding cannot use the RGB output.`);return e},de=e=>{switch(e){case 0:return nr.R;case 1:return nr.G;case 2:return nr.B;case 3:return nr.A;default:return nr.RGBA}},fe=e=>e.sourceColorSpace===1?Vt.Linear:Vt.SRGB,pe=e=>e.descriptor.sourceColorSpace===1,me=(e,t,n)=>t.every((t,n)=>e.scale[n]===t)&&n.every((t,n)=>e.bias[n]===t),he=e=>(oe(s.textures,e),e),ge=async(t,n,r,a,o=n.channel,s=!1)=>{let c=n.descriptor,l=c.texture.getSize(),u=!e.getEngine().needPOTTextures||!(l.width&l.width-1)&&!(l.height&l.height-1),d={textureType:s?ae:k.TEXTURETYPE_UNSIGNED_BYTE,samplingMode:u?k.TEXTURE_TRILINEAR_SAMPLINGMODE:k.TEXTURE_BILINEAR_SAMPLINGMODE,generateMipMaps:u};if(s&&ae===k.TEXTURETYPE_UNSIGNED_BYTE&&r.slice(0,3).some((e,t)=>Math.min(a[t],a[t]+e)<0))throw Error(`USD texture processing for '${t}' requires a floating-point render target to preserve signed values.`);let f=`${c.id}:${o}:${r.join(`,`)}:${a.join(`,`)}:${s}`,p=ee.get(f);if(p)return await p;let m=(async()=>{let n=new F(a[0],a[1],a[2],a[3]),s=new F(a[0]+r[0],a[1]+r[1],a[2]+r[2],a[3]+r[3]),l=e._blockEntityCollection;e._blockEntityCollection=!0;let u;try{u=Ft(t,v(n),v(s),Jt(c.texture,de(o),fe(c)),e,Vt.Linear,void 0,d)}finally{e._blockEntityCollection=l}let f=await u;if(!f.texture)throw Error(`USD texture processing for '${t}' did not produce a texture.`);if(re||i?.aborted)throw f.dispose?.(),i?.aborted&&i.throwIfAborted(),Error(`USD materialization was rolled back.`);te||e.addTexture(f.texture);let p=he(f.texture);p.gammaSpace=!1;let m=p;return m.uRotationCenter=c.texture.uRotationCenter,m.vRotationCenter=c.texture.vRotationCenter,m.wRotationCenter=c.texture.wRotationCenter,m.homogeneousRotationInUVTransform=c.texture.homogeneousRotationInUVTransform,p})();ee.set(f,m);try{return await m}catch(e){throw ee.delete(f),e}},_e=async(e,t)=>{let n=ue(t.channel),r=t.descriptor.scale[n],i=t.descriptor.bias[n];return await ge(e,t,[r,r,r,1],[i,i,i,0],t.channel)},ve=async e=>{let{material:t,normalScale:n,base:r,opacity:i,normal:a,metallic:o,roughness:s,occlusion:c,emissive:l}=e;if(r){if(r.channel!==4)throw Error(`A USD base-color texture must use the RGB output.`);t.albedoColor=N.White(),t.albedoTexture=me(r.descriptor,[1,1,1,1],[0,0,0,0])?r.descriptor.texture:await ge(`${t.name} base color`,r,r.descriptor.scale,r.descriptor.bias)}if(l){if(l.channel!==4)throw Error(`A USD emissive texture must use the RGB output.`);let e=l.descriptor;if(e.bias.slice(0,3).every(e=>e===0))t.emissiveColor=new N(e.scale[0],e.scale[1],e.scale[2]),t.emissiveTexture=e.texture;else{let n=Array.from({length:3},(t,n)=>Math.max(1,Math.abs(e.bias[n]),Math.abs(e.bias[n]+e.scale[n]))),r=e.scale.map((e,t)=>t<3?e/n[t]:e),i=e.bias.map((e,t)=>t<3?e/n[t]:e);t.emissiveColor=new N(n[0],n[1],n[2]),t.emissiveTexture=await ge(`${t.name} emissive`,l,r,i,l.channel,!0)}}if(a){if(a.channel!==4)throw Error(`A USD normal texture must use the RGB output.`);if(a.descriptor.sourceColorSpace===1&&me(a.descriptor,[2,2,2,1],[-1,-1,-1,0]))t.bumpTexture=a.descriptor.texture;else{let e=Array.from(a.descriptor.scale,e=>e*.5),n=Array.from(a.descriptor.bias,(e,t)=>t<3?(e+1)*.5:e);t.bumpTexture=await ge(`${t.name} normal`,a,e,n)}t.bumpTexture.gammaSpace=!1,t.bumpTexture.level=n}let u=o&&s&&o.descriptor===s.descriptor&&(o.channel===0||o.channel===2)&&(s.channel===1||s.channel===3)&&pe(o)&&o.descriptor.bias[ue(o.channel)]===0&&s.descriptor.bias[ue(s.channel)]===0,d=!1;if(u){let e=o.descriptor;t.metallicTexture=e.texture,t.metallic=(t.metallic??1)*e.scale[ue(o.channel)],t.roughness=(t.roughness??1)*e.scale[ue(s.channel)],t.useRoughnessFromMetallicTextureAlpha=s.channel===3,t.useRoughnessFromMetallicTextureGreen=s.channel===1,t.useMetallnessFromMetallicTextureBlue=o.channel===2,d=c?.descriptor===e&&c.channel===0&&e.scale[0]===1&&e.bias[0]===0,t.useAmbientOcclusionFromMetallicTextureRed=d}else{if(o){let e=ue(o.channel),n=pe(o)&&(o.channel===0||o.channel===2)&&o.descriptor.bias[e]===0;t.metallicTexture=n?o.descriptor.texture:await _e(`${t.name} metallic`,o),t.useRoughnessFromMetallicTextureAlpha=!1,t.useRoughnessFromMetallicTextureGreen=!1,t.useMetallnessFromMetallicTextureBlue=n&&o.channel===2,t.metallic=n?(t.metallic??1)*
703o.descriptor.scale[e]:1}if(s){let e=ue(s.channel),n=pe(s)&&s.channel===0&&s.descriptor.bias[e]===0;t.microSurfaceTexture=n?s.descriptor.texture:await _e(`${t.name} roughness`,s),t.microSurfaceTexture.gammaSpace=n?s.descriptor.texture.gammaSpace:!1,t.roughness=n?(t.roughness??1)*s.descriptor.scale[e]:1}}if(c&&!d){let e=ue(c.channel);t.ambientTexture=pe(c)&&c.channel===0&&c.descriptor.scale[e]===1&&c.descriptor.bias[e]===0?c.descriptor.texture:await _e(`${t.name} occlusion`,c),t.useAmbientInGrayScale=!0}if(i){if(r&&t.albedoTexture&&i.descriptor===r.descriptor&&i.channel===3&&i.descriptor.scale[3]===1&&i.descriptor.bias[3]===0)t.albedoTexture.hasAlpha=!0,t.useAlphaFromAlbedoTexture=!0;else{let e=i.channel===3&&i.descriptor.scale[3]===1&&i.descriptor.bias[3]===0;t.opacityTexture=e?i.descriptor.texture:await _e(`${t.name} opacity`,i),t.opacityTexture.gammaSpace=e?i.descriptor.texture.gammaSpace:!1,t.opacityTexture.getAlphaFromRGB=!e}}let p=f.get(e.id);p&&(p.albedoColor.copyFrom(t.albedoColor),p.albedoTexture=t.albedoTexture,p.emissiveColor.copyFrom(t.emissiveColor),p.emissiveTexture=t.emissiveTexture,p.bumpTexture=t.bumpTexture,p.metallic=t.metallic,p.roughness=t.roughness,p.metallicTexture=t.metallicTexture,p.microSurfaceTexture=t.microSurfaceTexture,p.ambientTexture=t.ambientTexture,p.opacityTexture=t.opacityTexture,p.alpha=t.alpha,p.useAlphaFromAlbedoTexture=t.useAlphaFromAlbedoTexture,p.useRoughnessFromMetallicTextureAlpha=t.useRoughnessFromMetallicTextureAlpha,p.useRoughnessFromMetallicTextureGreen=t.useRoughnessFromMetallicTextureGreen,p.useMetallnessFromMetallicTextureBlue=t.useMetallnessFromMetallicTextureBlue,p.useAmbientOcclusionFromMetallicTextureRed=t.useAmbientOcclusionFromMetallicTextureRed,p.useAmbientInGrayScale=t.useAmbientInGrayScale)};try{let f=e._blockEntityCollection;r||(e._blockEntityCollection=!0);try{for(let r of o){let i=new Uy(t,r.payloadOffset,r.payloadLength);switch(r.opcode){case 1:{let t=i.u32()===1,n=i.f32();ne=i.f32()||24,O=new Ge(`USD Root`,e),oe(s.transformNodes,O),s.rootNodes.push(O),O.rotationQuaternion=t?z.FromArray([-.7071068,0,0,.7071068]):z.Identity(),O.scaling.copyFrom(e.useRightHandedSystem?new R(n,n,n):t?new R(n,-n,n):new R(n,n,-n));break}case 2:{let t=i.u32();if(u.has(t))throw Error(`Duplicate USD texture ${t}.`);let r=i.u32(),a=i.u32(),o=Xy(i.u32()),c=i.u32(),l=i.u32(),d=i.u32(),f=i.u32(),p=i.u32(),m=i.u32(),h=i.u32(),g=i.u32();if(qy(n,f,5,4,`texture transform`),qy(n,g,8,4,`texture value transform`),qy(n,c,l,1,`texture image`),h<0||h>2)throw Error(`Invalid USD texture color space ${h}.`);let _=new Float32Array(n,f,5),v=new Float32Array(n,g,8);if(![..._,...v].every(Number.isFinite))throw Error(`USD texture ${t} has a non-finite transform.`);let y=new Uint8Array(n,c,l),b=URL.createObjectURL(new Blob([y],{type:o}));w.add(b);let x,S,T=new Promise((e,t)=>{x=e,S=t});C.push(T);let E=new I(b,e,!1,!1,I.TRILINEAR_SAMPLINGMODE,x,(e,t)=>{URL.revokeObjectURL(b),S(t instanceof Error?t:Error(e||`Could not load texture '${b}'.`))});oe(s.textures,E),E.onDisposeObservable.addOnce(()=>URL.revokeObjectURL(b)),E.name=Jy(n,r,a),E.coordinatesIndex=d,E.uScale=_[0],E.vScale=_[1],E.uRotationCenter=0,E.vRotationCenter=0,E.uOffset=_[2]-_[1]*Math.sin(_[4]),E.vOffset=1-_[1]*Math.cos(_[4])-_[3],E.wAng=-_[4],E.wrapU=Zy(p),E.wrapV=Zy(m),E.gammaSpace=h!==1,u.set(t,{id:t,texture:E,sourceColorSpace:h,scale:v.subarray(0,4),bias:v.subarray(4,8)});break}case 3:{let t=i.u32(),r=i.u32(),a=i.u32(),o=i.u32(),c=i.u32(),l=i.f32(),u=i.f32(),f=i.f32(),p=i.f32(),m=i.u32(),h=Array.from({length:7},()=>i.u32()),g=Array.from({length:7},()=>i.u32());qy(n,o,4,4,`material base color`),qy(n,c,3,4,`material emissive color`);let _=new Float32Array(n,o,4),v=new Float32Array(n,c,3),y=new ut(Jy(n,r,a),e);oe(s.materials,y),y.id=`usd-material-${t}`,y.albedoColor=new N(_[0],_[1],_[2]),y.alpha=_[3],y.metallic=l,y.roughness=u,y.emissiveColor=new N(v[0],v[1],v[2]);let b=!!(m&1);y.backFaceCulling=!b,y.twoSidedLighting=b,y.unlit=!!(m&2),m&4&&(y.transparencyMode=2),p>0&&(y.transparencyMode=1,y.alphaCutOff=p),D.push({id:t,material:y,normalScale:f,base
703:le(h[0],g[0],`base-color texture`),opacity:le(h[1],g[1],`opacity texture`),normal:le(h[2],g[2],`normal texture`),metallic:le(h[3],g[3],`metallic texture`),roughness:le(h[4],g[4],`roughness texture`),occlusion:le(h[5],g[5],`occlusion texture`),emissive:le(h[6],g[6],`emissive texture`)}),d.set(t,y);break}case 4:{let t=i.u32(),r=i.u32(),a=i.u32(),o=i.u32(),u=i.u32(),d=new Ge(Jy(n,a,o),e);oe(s.transformNodes,d),d.setPreTransformMatrix(Yy(n,u)),Object.defineProperty(d,Ky,{configurable:!0,get:()=>d.getPivotMatrix(),set:e=>d.setPreTransformMatrix(e)}),c.set(t,d),r===4294967295?d.parent=O??null:l.push({node:d,parentId:r});break}case 5:{let t=i.u32(),r=i.u32(),a=i.u32(),o=i.u32(),c=i.u32(),l=new Yt(Jy(n,r,a),`usd-skeleton-${t}`,e);oe(s.skeletons,l);let u=new DataView(n);qy(n,c,o*6,4,`skeleton joints`);let d=[];for(let e=0;e<o;++e){let r=c+e*24,i=u.getUint32(r,!0),a=u.getUint32(r+4,!0),o=u.getUint32(r+8,!0),s=u.getUint32(r+12,!0),f=u.getUint32(r+16,!0),p=u.getUint32(r+20,!0);if(i!==4294967295&&i>=e)throw Error(`Skeleton ${t} has an invalid parent joint index.`);let h=new mr(Jy(n,o,s),l,i===4294967295?null:d[i],Yy(n,f),Yy(n,f),Yy(n,p),e);d.push(h),m.set(a,h)}p.set(t,l);break}case 6:{let e=i.u32();h.set(e,{vertexCount:i.u32(),indexCount:i.u32(),flags:i.u32(),positions:i.u32(),normals:i.u32(),tangents:i.u32(),uv0:i.u32(),colors:i.u32(),joints0:i.u32(),weights0:i.u32(),joints1:i.u32(),weights1:i.u32(),indices:i.u32(),influences:i.u32()});break}case 7:{let t=i.u32(),r=i.u32(),a=i.u32(),o=i.u32(),l=i.u32(),u=i.u32(),d=i.u32(),f=i.u32(),m=i.u32(),_=i.u32(),v=h.get(a);if(!v)throw Error(`Mesh ${t} references missing geometry ${a}.`);let y=new At(Jy(n,l,u),e);oe(s.meshes,y),se(y,d),y.parent=c.get(r)??O??null;let b=new E;qy(n,v.positions,v.vertexCount*3,4,`positions`),b.positions=new Float32Array(n,v.positions,v.vertexCount*3),v.flags&1&&(qy(n,v.normals,v.vertexCount*3,4,`normals`),b.normals=new Float32Array(n,v.normals,v.vertexCount*3)),v.flags&2&&(qy(n,v.tangents,v.vertexCount*4,4,`tangents`),b.tangents=new Float32Array(n,v.tangents,v.vertexCount*4)),v.flags&4&&(qy(n,v.uv0,v.vertexCount*2,4,`texture coordinates`),b.uvs=new Float32Array(n,v.uv0,v.vertexCount*2)),v.flags&8&&(qy(n,v.colors,v.vertexCount*4,4,`vertex colors`),b.colors=new Float32Array(n,v.colors,v.vertexCount*4)),v.flags&16&&(qy(n,v.joints0,v.vertexCount*4,2,`joint indices`),qy(n,v.weights0,v.vertexCount*4,4,`joint weights`),b.matricesIndices=Float32Array.from(new Uint16Array(n,v.joints0,v.vertexCount*4)),b.matricesWeights=new Float32Array(n,v.weights0,v.vertexCount*4)),v.flags&32&&(qy(n,v.joints1,v.vertexCount*4,2,`extra joint indices`),qy(n,v.weights1,v.vertexCount*4,4,`extra joint weights`),b.matricesIndicesExtra=Float32Array.from(new Uint16Array(n,v.joints1,v.vertexCount*4)),b.matricesWeightsExtra=new Float32Array(n,v.weights1,v.vertexCount*4)),qy(n,v.indices,v.indexCount,4,`indices`),b.indices=new Uint32Array(n,v.indices,v.indexCount),b.applyToMesh(y,!0),y.geometry&&oe(s.geometries,y.geometry),y.numBoneInfluencers=Math.min(v.influences,8),f!==4294967295&&(y.skeleton=p.get(f)??null);let x=new DataView(n);qy(n,m,_*5,4,`submeshes`);let S=!!(d&1);if(_===1&&o!==4294967295)y.material=ce(o,S);else{let t=new er(`${y.name} materials`,e);oe(s.multiMaterials,t);for(let e=0;e<_;++e){let n=m+e*20;t.subMaterials.push(ce(x.getUint32(n,!0),S))}y.material=t}y.releaseSubMeshes();for(let e=0;e<_;++e){let t=m+e*20;new it(e,x.getUint32(t+12,!0),x.getUint32(t+16,!0),x.getUint32(t+4,!0),x.getUint32(t+8,!0),y)}g.set(t,y);break}case 12:{let t=i.u32(),r=i.u32(),a=i.u32(),o=i.u32(),c=i.u32(),l=i.u32(),u=i.u32(),d=i.f32(),f=g.get(r);if(!f)throw Error(`Morph target references missing mesh ${r}.`);if(y.has(t)||c!==f.getTotalVertices()||!Number.isFinite(d))throw Error(`Morph target ${t} has invalid metadata.`);qy(n,l,c*3,4,`morph target positions`);let p=_.get(r);p||(p=new qn(e,f.name),p.areUpdatesFrozen=!0,oe(s.morphTargetManagers,p),_.set(r,p));let m=new kt(Jy(n,a,o),d,e,p);m.id=`usd-morph-target-${t}`,m.setPositions(new Float32Array(n,l,c*3)),u!==4294967295&&(qy(n,u,c*3,4,`morph target normals`),m.setNormals(new Float32Array(n,u,c*3))),p.addTarget(m),y.set(t,m);break}case 10:{let t=i.u32(),r=i.u32(),a=i.u32(),o=i.u32(),l=i.u32(),u=i.u32(),d=i.u32(),f=i.u32(),p=i.f32(),m=i.f32(),h=i.u32(),_=Jy(n,l,u);if(!Number.isFinite(p)||p<=0)throw Error(`Analytic primitive ${t}
703 has an invalid size or radius.`);if((a===2||a===3)&&(!Number.isFinite(m)||m<=0))throw Error(`Analytic primitive ${t} has an invalid height.`);if(a!==0&&(!Number.isInteger(h)||h<3||h>512))throw Error(`Analytic primitive ${t} has invalid tessellation.`);let v;switch(a){case 0:v=Ue(_,{size:p},e);break;case 1:v=je(_,{diameter:p*2,segments:h},e);break;case 2:case 3:v=T(_,{height:m,diameterTop:a===3?0:p*2,diameterBottom:p*2,tessellation:h},e);break;default:throw Error(`Unsupported analytic primitive type ${a}.`)}if(oe(s.meshes,v),v.geometry&&oe(s.geometries,v.geometry),!(d&2)){let e=v.getIndices();if(!e)throw Error(`Analytic primitive ${t} has no generated indices.`);let n=Array.from(e);for(let e=0;e<n.length;e+=3)[n[e],n[e+2]]=[n[e+2],n[e]];v.setIndices(n)}if(f===0)v.rotationQuaternion=z.RotationAxis(new R(0,0,1),-Math.PI/2);else if(f===2)v.rotationQuaternion=z.RotationAxis(new R(1,0,0),Math.PI/2);else if(f!==1)throw Error(`Unsupported analytic primitive axis ${f}.`);se(v,d),v.parent=c.get(r)??O??null,v.material=ce(o,!!(d&1)),g.set(t,v);break}case 8:{let e=i.u32(),t=i.u32(),r=i.u32(),a=i.u32(),o=g.get(e);if(!o)throw Error(`Instance references missing mesh ${e}.`);if(x.has(e))throw Error(`Mesh ${e} cannot mix classic and thin instances.`);b.add(e);let l=o.createInstance(Jy(n,r,a));oe(s.meshes,l),l.parent=c.get(t)??O??null;break}case 11:{let e=i.u32(),t=i.u32(),r=i.u32(),a=g.get(e);if(!a)throw Error(`Thin instances reference missing mesh ${e}.`);if(x.has(e)||b.has(e))throw Error(`Mesh ${e} has duplicate or mixed thin instances.`);qy(n,t,r*16,4,`thin instance transforms`),a.thinInstanceSetBuffer(`matrix`,new Float32Array(n,t,r*16),16,!0),a.thinInstanceEnablePicking=!0,x.add(e);break}case 9:{let t=i.u32(),r=i.u32(),a=i.u32(),o=i.u32(),l=i.u32(),u=i.u32(),d=i.u32(),f=i.u32();if(t!==0&&t!==1&&t!==2)throw Error(`Invalid animation target kind ${t}.`);if(t===2!=(a===4))throw Error(`Invalid animation property ${a} for target kind ${t}.`);if(f!==(a===4?1:a===0||a===2?3:a===1?4:a===3?16:0))throw Error(`Invalid animation value stride ${f} for property ${a}.`);let p=t===0?c.get(r):t===1?m.get(r):y.get(r);if(!p)break;let h=a===0?`position`:a===1?`rotationQuaternion`:a===2?`scaling`:a===4?`influence`:t===0?Ky:`_matrix`,g=a===4?M.ANIMATIONTYPE_FLOAT:a===1?M.ANIMATIONTYPE_QUATERNION:a===3?M.ANIMATIONTYPE_MATRIX:M.ANIMATIONTYPE_VECTOR3,_=new M(`USD ${h}`,h,ne,g,M.ANIMATIONLOOPMODE_CYCLE);qy(n,u,l,4,`animation times`),qy(n,d,l*f,4,`animation values`);let v=new Float32Array(n,u,l),b=new Float32Array(n,d,l*f);_.setKeys(Array.from({length:l},(e,t)=>({frame:v[t],value:g===M.ANIMATIONTYPE_QUATERNION?z.FromArray(b,t*f):g===M.ANIMATIONTYPE_MATRIX?L.FromArray(b,t*f):g===M.ANIMATIONTYPE_FLOAT?b[t*f]:R.FromArray(b,t*f)})));let x=S.get(o);x||(x=new or(`USD Animation ${o+1}`,e),S.set(o,x),oe(s.animationGroups,x)),x.addTargetedAnimation(_,p);break}}}for(let[e,t]of _)t.areUpdatesFrozen=!1,!t.isUsingTextureForTargets&&t.numTargets<=qn.MaxActiveMorphTargetsInVertexAttributeMode&&(t.optimizeInfluencers=!1,t.numMaxInfluencers=t.numTargets),g.get(e).morphTargetManager=t}finally{r||(e._blockEntityCollection=f)}await Qy(Promise.all(C),i),await Qy(Promise.all(D.map(async e=>{await ve(e)})),i);for(let{node:e,parentId:t}of l)e.parent=c.get(t)??O??null;return{container:s,materializeMs:performance.now()-a}}catch(e){re=!0,Promise.allSettled(C),Promise.allSettled(ee.values()),s.dispose();for(let e of w)URL.revokeObjectURL(e);throw e}}var eb=e({USDFileLoader:()=>sb,_RegisterUSDLoaderDependencies:()=>lb});ot(),wt(),We();var tb=`${P._DefaultCdnUrl}/babylonUsdImporter/5/`,nb=/\.(?:usd|usda|usdc|usdz)$/i;function rb(e){return e instanceof Uint8Array?e.slice():e instanceof ArrayBuffer?new Uint8Array(e.slice(0)):new Uint8Array(e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength))}function ib(e){if(!e)return;let t={};for(let[n,r]of Object.entries(e))t[n]=rb(r);return t}function ab(e,t,n){let r=e?.replace(/\\/g,`/`).replace(/^\.\/+/,``),i=n?r:r?.split(/[?#]/,1)[0],a=i?.split(`/`).filter(Boolean);return i&&!i.startsWith(`/`)&&a?.length&&!a.includes(`..`)&&nb.test(i)?a.join(`/`):t.length>=4&&t[0]===80&&t[1]===75&&t[2]===3&&t[3]===4?`scene.usdz`:`scene.usd`}function ob(e){return{meshes:e.meshes,particleSystems:e.particleSystems,skeletons:e.skeletons,animationGroups:e.animationGroups,transformNodes:e.transformNodes,geometries:e.geometries,lights:e.lights,spriteManagers:e.spriteManagers}}var sb=class e{constructor(t={}){this.name=u.name,this.extensions=u.extensions,this._nextRequestId=1,this._pending=new Map,this._activeLoads=new Set,this._options={...t,resolveByFileName:t.resolveByFileName??!0,glueUrl:t.glueUrl??e.DefaultConfiguration.glueUrl,wasmUrl:t.wasmUrl??e.DefaultConfiguration.wasmUrl,dataUrl:t.dataUrl??e.DefaultConfiguration.dataUrl,workerUrl:t.workerUrl??e.DefaultConfiguration.workerUrl}}createPlugin(t){return lb(),new e(t[u.name])}async importMeshAsync(e,t,n,r,i,a){return ob((await this._loadAsync(t,n,r,i,a,!0)).container)}async loadAsync(e,t,n,r,i){await this._loadAsync(e,t,n,r,i,!0)}async loadAssetContainerAsync(e,t,n,r,i){let a=(await this._loadAsync(e,t,n,r,i,!1)).container;if(!(a instanceof bt))throw Error(`USDFileLoader failed to create an asset container.`);return a}dispose(){this._terminateWorker();let e=Error(`USDFileLoader was disposed.`);for(let t of this._activeLoads)t.abort(e);for(let t of this._pending.values())t.reject(e);this._pending.clear()}async _loadAsync(e,t,n,r,i,a){if(!(t instanceof ArrayBuffer)&&!ArrayBuffer.isView(t))throw Error(`USDFileLoader expects binary USD data.`);let o=rb(t),s=ib(this._options.files),c=this._nextRequestId++,l={type:`extract`,requestId:c,asset:{bytes:o,files:s,fileName:ab(this._options.rootFileName??i,o,this._options.rootFileName!==void 0),resolveByFileName:this._options.resolveByFileName??!0,glueUrl:this._options.glueUrl,wasmUrl:this._options.wasmUrl,dataUrl:this._options.dataUrl}},u=[...new Set([o.buffer,...Object.values(s??{}).map(e=>e.buffer)])],d=new AbortController,f=d.signal;this._activeLoads.add(d);try{let t=this._getWorker(this._options.workerUrl),n=await new Promise((e,n
703)=>{this._pending.set(c,{resolve:e,reject:n,onProgress:e=>{this._options.onProgress?.(e),r?.({lengthComputable:!1,loaded:cb[e.phase],total:4})},onLog:this._options.onLog});try{t.postMessage(l,u)}catch(e){this._pending.delete(c),n(e instanceof Error?e:Error(String(e)))}});this._options.onProgress?.({phase:`materializing`,message:`Creating Babylon.js objects...`}),r?.({lengthComputable:!1,loaded:4,total:4}),f.throwIfAborted();let i=await $y(e,n.commands,n.data,a,f),o={container:i.container,timings:{...n.timings,materializeMs:i.materializeMs},statistics:n.statistics,missingAssets:n.missingAssets};try{f.throwIfAborted(),this._options.onComplete?.({timings:o.timings,statistics:o.statistics,missingAssets:o.missingAssets}),f.throwIfAborted()}catch(e){throw i.container.dispose(),e}return o}finally{this._activeLoads.delete(d),this._pending.size===0&&this._terminateWorker()}}_getWorker(e){if(!e)throw Error(`The USD worker URL was not configured.`);let t=globalThis.location,n=new URL(String(e),t?.href??`http://localhost/`).href;if(this._worker&&this._workerUrl!==n){if(this._pending.size>0)throw Error(`Cannot change the USD worker URL while requests are pending.`);this._terminateWorker()}if(this._worker)return this._worker;this._workerUrl=n,!t||new URL(n).origin===t.origin?this._worker=new Worker(n,{type:`module`}):(this._workerBlobUrl=URL.createObjectURL(new Blob([`import ${JSON.stringify(n)};`],{type:`application/javascript`})),this._worker=new Worker(this._workerBlobUrl,{type:`module`})),this._worker.addEventListener(`message`,e=>{let t=e.data,n=this._pending.get(t.requestId);if(n){if(t.type===`progress`){n.onProgress?.(t.progress);return}if(t.type===`log`){n.onLog?.(t.level>=2?`error`:t.level===1?`warning`:`info`,t.message);return}if(this._pending.delete(t.requestId),t.type===`error`){let e=Error(t.message);e.stack=t.stack,n.reject(e)}else n.resolve(t)}});let r=e=>{this._terminateWorker();for(let t of this._pending.values())t.reject(e);this._pending.clear()};return this._worker.addEventListener(`error`,e=>{r(e.error??Error(e.message||`Could not load the USD worker from '${n}'.`))}),this._worker.addEventListener(`messageerror`,()=>{r(Error(`The USD worker returned a message that could not be deserialized.`))}),this._worker}_terminateWorker(){this._worker?.terminate(),this._worker=void 0,this._workerUrl=void 0,this._workerBlobUrl&&=(URL.revokeObjectURL(this._workerBlobUrl),void 0)}};sb.DefaultConfiguration={glueUrl:`${tb}babylon-usd-importer.js`,wasmUrl:`${tb}babylon-usd-importer.wasm`,dataUrl:`${tb}babylon-usd-importer.data`,workerUrl:`${tb}babylon-usd-importer.worker.js`};var cb={initializing:1,staging:2,extracting:3,materializing:4};function lb(){ge(),Nn(),an()}export{ss as A,uo as B,Gs as C,ws as D,ks as E,Io as F,Ma as G,qa as H,jo as I,_a as J,Da as K,Eo as L,Zo as M,Ko as N,_s as O,Vo as P,xo as R,Xs as S,Ps as T,Ha as U,ao as V,La as W,qi as X,fa as Y,xc as _,R_ as a,oc as b,Xu as c,hu as d,$c as f,Ec as g,Rc as h,fv as i,ns as j,fs as k,Uu as l,Uc as m,Cy as n,Ld as o,Jc as p,Sa as q,yy as r,ad as s,eb as t,wu as u,gc as v,zs as w,tc as x,dc as y,go as z}; 704//# sourceMappingURL=babylon-loaders-a5srscd6.js.map
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.