babylonjs-loaders 9.22.0 → 9.22.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/babylonjs.loaders.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("babylonjs")):"function"==typeof define&&define.amd?define(["exports","babylonjs"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).BABYLON=e.BABYLON||{},e.BABYLON)}(this,function(e,t){"use strict";const n="Xposition",s="Yposition",o="Zposition",r="Xrotation",i="Yrotation",a="Zrotation";class l{constructor(e){this.loopMode=t.Animation.ANIMATIONLOOPMODE_CYCLE,this.list=[],this.root=u(),this.numFrames=0,this.frameRate=0,this.skeleton=e}}function u(){return{name:"",type:"",offset:new t.Vector3,channels:[],children:[],frames:[],parent:null}}function c(e,l,u){const d=function(e){const n=e.offset.x,s=e.offset.y,o=e.offset.z;return t.Matrix.Translation(n,s,o)}(e),h=new t.Bone(e.name,u.skeleton,l,d),m=function(e,l){if(0===e.frames.length)return[];const u=[],c=e.channels.some(e=>e===n||e===s||e===o),d=e.channels.some(e=>e===r||e===i||e===a),h=new t.Animation(`${e.name}_pos`,"position",l.frameRate,t.Animation.ANIMATIONTYPE_VECTOR3,l.loopMode),m=new t.Animation(`${e.name}_rot`,"rotationQuaternion",l.frameRate,t.Animation.ANIMATIONTYPE_QUATERNION,l.loopMode),f=[],p=[];for(let t=0;t<e.frames.length;t++){const n=e.frames[t];c&&n.position&&f.push({frame:n.frame,value:n.position.clone()}),d&&p.push({frame:n.frame,value:n.rotation.clone()})}return f.length>0&&(h.setKeys(f),u.push(h)),p.length>0&&(m.setKeys(p),u.push(m)),u}(e,u);for(const e of m)e.getKeys()&&e.getKeys().length>0&&h.animations.push(e);for(const t of e.children)c(t,h,u)}function d(e,l,u,c){if("ENDSITE"===u.type)return;const h={frame:0,position:new t.Vector3,rotation:new t.Quaternion};h.frame=l,h.position=new t.Vector3,h.rotation=new t.Quaternion,u.frames.push(h);let m=t.Matrix.Identity();for(let l=0;l<u.channels.length;++l){const d=u.channels[l],f=e[c.i++];if(!f)continue;const p=parseFloat(f.trim());if(d.endsWith("position"))switch(d){case n:h.position.x=p;break;case s:h.position.y=p;break;case o:h.position.z=p}else if(d.endsWith("rotation")){const e=t.Tools.ToRadians(p);let n;switch(d){case r:n=t.Matrix.RotationX(e);break;case i:n=t.Matrix.RotationY(e);break;case a:n=t.Matrix.RotationZ(e)}m=n.multiply(m)}}t.Quaternion.FromRotationMatrixToRef(m,h.rotation);for(const t of u.children)d(e,l,t,c)}function h(e,n,s,o){var r,i,a,l;const c=u();c.parent=s,o.list.push(c);let d=n.trim().split(/\s+/);if("END"===d[0].toUpperCase()&&"SITE"===d[1].toUpperCase()?(c.type="ENDSITE",c.name="ENDSITE"):(c.name=d[1],c.type=d[0].toUpperCase()),"{"!=(null===(r=e.shift())||void 0===r?void 0:r.trim()))throw new Error("Expected opening { after type & name");const m=null===(i=e.shift())||void 0===i?void 0:i.trim().split(/\s+/);if(!m)throw new Error("Unexpected end of file: missing OFFSET");if(d=m,"OFFSET"!=d[0].toUpperCase())throw new Error("Expected OFFSET, but got: "+d[0]);if(4!=d.length)throw new Error("OFFSET: Invalid number of values");const f=new t.Vector3(parseFloat(d[1]),parseFloat(d[2]),parseFloat(d[3]));if(isNaN(f.x)||isNaN(f.y)||isNaN(f.z))throw new Error("OFFSET: Invalid values");if(c.offset=f,"ENDSITE"!=c.type){if(d=null===(a=e.shift())||void 0===a?void 0:a.trim().split(/\s+/),!d)throw new Error("Unexpected end of file: missing CHANNELS");if("CHANNELS"!=d[0].toUpperCase())throw new Error("Expected CHANNELS definition");const t=parseInt(d[1]);c.channels=d.splice(2,t),c.children=[]}for(;e.length>0;){const t=null===(l=e.shift())||void 0===l?void 0:l.trim();if("}"===t)return c;t&&c.children.push(h(e,t,c,o))}throw new Error("Unexpected end of file: missing closing brace")}function m(e,n,s,o){const r=e.split("\n"),{loopMode:i}=o;n._blockEntityCollection=!!s;const a=new t.Skeleton("","",n);a._parentContainer=s,n._blockEntityCollection=!1;const u=new l(a);u.loopMode=i;const m=r.shift();if(!m||"HIERARCHY"!==m.trim().toUpperCase())throw new Error("HIERARCHY expected");const f=r.shift();if(!f)throw new Error("Unexpected end of file after HIERARCHY");const p=h(r,f.trim(),null,u),_=r.shift();if(!_||"MOTION"!==_.trim().toUpperCase())throw new Error("MOTION expected");const g=r.shift();if(!g)throw new Error("Unexpected end of file before frame count");const y=g.trim().split(/[\s]+/);if(y.length<2)throw new Error("Invalid frame count line");const v=parseInt(y[1]);if(isNaN(v))throw new Error("Failed to read number of frames.");u.numFrames=v;const b=r.shift();if(!b)throw new Error("Unexpected end of file before frame time");const x=b.trim().split(/[\s]+/);if(x.length<3)throw new Error("Invalid frame time line");const T=parseFloat(x[2]);if(isNaN(T))throw new Error("Failed to read frame time.");if(T<=0)throw new Error("Failed to read frame time. Invalid value "+T);u.frameRate=1/T;for(let e=0;e<v;++e){const t=r.shift();t&&d(t.trim().split(/[\s]+/)||[],e,p,{i:0})}return u.root=p,c(u.root,null,u),u.skeleton.returnToRest(),u.skeleton}const f={name:"bvh",extensions:{".bvh":{isBinary:!1}}};class p{constructor(e){this.name=f.name,this.extensions=f.extensions,this._loadingOptions=Object.assign(Object.assign({},p._DefaultLoadingOptions),null!=e?e:{})}static get _DefaultLoadingOptions(){return{loopMode:t.Animation.ANIMATIONLOOPMODE_CYCLE}}createPlugin(e){return new p(e[f.name])}canDirectLoad(e){return this.isBvhHeader(e)}isBvhHeader(e){return"HIERARCHY"==e.split("\n")[0]}isNotBvhHeader(e){return!this.isBvhHeader(e)}importMeshAsync(e,t,n){if("string"!=typeof n)return Promise.reject("BVH loader expects string data.");if(this.isNotBvhHeader(n))return Promise.reject("BVH loader expects HIERARCHY header.");try{const e=m(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"string"!=typeof t?Promise.reject("BVH loader expects string data."):this.isNotBvhHeader(t)?Promise.reject("BVH loader expects HIERARCHY header."):this.importMeshAsync(null,e,t).then(()=>{})}loadAssetContainerAsync(e,n){if("string"!=typeof n)return Promise.reject("BVH loader expects string data.");if(this.isNotBvhHeader(n))return Promise.reject("BVH loader expects HIERARCHY header.");const s=new t.AssetContainer(e);try{const t=m(n,e,s,this._loadingOptions);return s.skeletons.push(t),Promise.resolve(s)}catch(e){return Promise.reject(e)}}}let _=!1;function g(){_||(_=!0,t.RegisterSceneLoaderPlugin(new p))}g();var y={__proto__:null,BVHFileLoader:p,RegisterBVHFileLoader:g},v={__proto__:null,BVHFileLoader:p,ReadBvh:m,RegisterBVHFileLoader:g};function b(e,t,n,s){return new(n||(n=Promise))(function(o,r){function i(e){try{l(s.next(e))}catch(e){r(e)}}function a(e){try{l(s.throw(e))}catch(e){r(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(i,a)}l((s=s.apply(e,t||[])).next())})}Object.create,Object.create,"function"==typeof SuppressedError&&SuppressedError;const x=[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],T=[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],A=[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],M=[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],w=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];class C{constructor(e,t,n){this.input=e,this.byteOffset=t,this.endOffset=n,this.bitBuffer=0,this.bitCount=0}readBits(e){this.ensureBits(e);const t=this.bitBuffer&(1<<e)-1;return this.bitBuffer>>>=e,this.bitCount-=e,t}readBit(){if(0===this.bitCount){if(this.byteOffset>=this.endOffset)throw new Error("zlib: unexpected end of input");this.bitBuffer=this.input[this.byteOffset++],this.bitCount=8}const e=1&this.bitBuffer;return this.bitBuffer>>>=1,this.bitCount--,e}alignToByte(){this.bitBuffer=0,this.bitCount=0}readUint16LE(){if(this.ensureByteAligned(),this.byteOffset+2>this.endOffset)throw new Error("zlib: unexpected end of input");const 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 new Error("zlib: unexpected end of input");return this.input[this.byteOffset++]}ensureByteAligned(){if(0!==this.bitCount)throw new Error("deflate: expected byte alignment")}ensureBits(e){for(;this.bitCount<e;){if(this.byteOffset>=this.endOffset)throw new Error("zlib: unexpected end of input");this.bitBuffer|=this.input[this.byteOffset++]<<this.bitCount,this.bitCount+=8}}}class R{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 new Error("zlib: output length mismatch");const t=255&e;this.bytes[this.offset++]=t,this.adlerA+=t,this.adlerB+=this.adlerA,this.adlerA%=65521,this.adlerB%=65521}copy(e,t){if(e<=0||e>this.offset)throw new 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 new Error("zlib: output length mismatch")}adler32(){return(this.adlerB<<16|this.adlerA)>>>0}}class S{constructor(e,t={}){const n=new Array(16).fill(0);let s=0,o=0;for(const t of e){if(!Number.isInteger(t)||t<0||t>15)throw new Error("deflate: invalid huffman code lengths");t>0&&(n[t]++,s++,o=Math.max(o,t))}if(0===s){if(t.allowEmpty)return this.symbolsByLength=[],void(this.maxCodeLength=0);throw new Error("deflate: invalid huffman code lengths")}let r=1;for(let e=1;e<=15;e++)if(r=(r<<1)-n[e],r<0)throw new Error("deflate: invalid huffman code lengths");if(0!==r&&1!==s)throw new Error("deflate: invalid huffman code lengths");const i=new Array(16).fill(0);let a=0;for(let e=1;e<=15;e++)a=a+n[e-1]<<1,i[e]=a;this.symbolsByLength=Array.from({length:16},(e,t)=>{if(0===n[t])return;const s=new Int16Array(1<<t);return s.fill(-1),s});for(let t=0;t<e.length;t++){const n=e[t];0!==n&&(this.symbolsByLength[n][i[n]++]=t)}this.maxCodeLength=o}decode(e){var t,n;if(0===this.maxCodeLength)throw new Error("deflate: invalid huffman code");let s=0;for(let o=1;o<=this.maxCodeLength;o++){s=s<<1|e.readBit();const r=null!==(n=null===(t=this.symbolsByLength[o])||void 0===t?void 0:t[s])&&void 0!==n?n:-1;if(r>=0)return r}throw new Error("deflate: invalid huffman code")}}let O,F;function E(){if(!O){const e=new 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;O=new S(e)}return O}function I(){return F||(F=new S(new Array(32).fill(5))),F}function L(e,t){e.alignToByte();const n=e.readUint16LE();if(65535&(n^~e.readUint16LE()))throw new Error("deflate: invalid stored block length");for(let s=0;s<n;s++)t.writeByte(e.readByte())}function P(e,t,n,s){for(;;){const o=n.decode(e);if(o<256){t.writeByte(o);continue}if(256===o)return;if(o>285)throw new Error("deflate: invalid literal/length symbol");const r=o-257,i=x[r]+e.readBits(T[r]),a=s.decode(e);if(a>29)throw new Error("deflate: invalid distance symbol");const l=A[a]+e.readBits(M[a]);t.copy(l,i)}}function B(e){const t=e.readBits(5)+257,n=e.readBits(5)+1,s=e.readBits(4)+4,o=new Array(19).fill(0);for(let t=0;t<s;t++)o[w[t]]=e.readBits(3);const r=function(e,t,n){const s=[];for(;s.length<n;){const o=t.decode(e);if(o<=15){s.push(o);continue}let r,i;switch(o){case 16:if(0===s.length)throw new Error("deflate: invalid code length repeat");i=s[s.length-1],r=e.readBits(2)+3;break;case 17:i=0,r=e.readBits(3)+3;break;case 18:i=0,r=e.readBits(7)+11;break;default:throw new Error("deflate: invalid code length symbol")}if(s.length+r>n)throw new Error("deflate: invalid code length repeat");for(let e=0;e<r;e++)s.push(i)}return s}(e,new S(o),t+n),i=r.slice(0,t),a=r.slice(t);if(0===i[256])throw new Error("deflate: missing end-of-block code");return{literalLengthTree:new S(i),distanceTree:new S(a,{allowEmpty:!0})}}function N(e,t,n,s,o){let r,i,a,l;if(s?(G(t,n,25,o,"FBX node header"),r=V(e,n),i=V(e,n+8),a=V(e,n+16),l=25):(G(t,n,13,o,"FBX node header"),r=e.getUint32(n,!0),i=e.getUint32(n+4,!0),a=e.getUint32(n+8,!0),l=13),0===r)return null;if(r<=n||r>o)throw new Error(`Invalid FBX node end offset ${r} at offset ${n}`);const u=t[n+l-1];G(t,n+l,u,r,"FBX node name");const c=K(t,n+l,u);let d=n+l+u;const h=d+a;if(h>r)throw new Error(`Invalid FBX property list length for node '${c}' at offset ${n}`);const m=[];for(let n=0;n<i;n++){const n=k(e,t,d,h);m.push(n.property),d=n.nextOffset}if(d!==h)throw new Error(`Invalid FBX property list length for node '${c}' at offset ${n}`);const f=[];if(d<r)for(;d<r;){const n=N(e,t,d,s,r);if(null===n)break;if(n.endOffset<=d||n.endOffset>r)throw new Error(`Invalid FBX child node end offset ${n.endOffset} at offset ${d}`);f.push(n.node),d=n.endOffset}return{node:{name:c,properties:m,children:f},endOffset:r}}function k(e,t,n,s){G(t,n,1,s,"FBX property type");const o=String.fromCharCode(t[n]);switch(n+=1,o){case"C":return G(t,n,1,s,"FBX boolean property"),{property:{type:"boolean",value:0!==t[n]},nextOffset:n+1};case"Y":return G(t,n,2,s,"FBX int16 property"),{property:{type:"int16",value:e.getInt16(n,!0)},nextOffset:n+2};case"I":return G(t,n,4,s,"FBX int32 property"),{property:{type:"int32",value:e.getInt32(n,!0)},nextOffset:n+4};case"F":return G(t,n,4,s,"FBX float32 property"),{property:{type:"float32",value:e.getFloat32(n,!0)},nextOffset:n+4};case"D":return G(t,n,8,s,"FBX float64 property"),{property:{type:"float64",value:e.getFloat64(n,!0)},nextOffset:n+8};case"L":return G(t,n,8,s,"FBX int64 property"),{property:{type:"int64",value:H(e,n)},nextOffset:n+8};case"S":{G(t,n,4,s,"FBX string property length");const o=e.getUint32(n,!0);G(t,n+4,o,s,"FBX string property data");const r=function(e,t,n){return new TextDecoder("utf-8").decode(e.subarray(t,t+n))}(t,n+4,o);return{property:{type:"string",value:r},nextOffset:n+4+o}}case"R":{G(t,n,4,s,"FBX raw property length");const o=e.getUint32(n,!0);return G(t,n+4,o,s,"FBX raw property data"),{property:{type:"raw",value:t.slice(n+4,n+4+o)},nextOffset:n+4+o}}case"f":return D(e,t,n,"float32[]",4,s);case"d":return D(e,t,n,"float64[]",8,s);case"i":return D(e,t,n,"int32[]",4,s);case"l":return D(e,t,n,"int64[]",8,s);case"b":return D(e,t,n,"boolean[]",1,s);default:throw new Error(`Unknown FBX property type: '${o}' at offset ${n-1}`)}}function D(e,t,n,s,o,r){G(t,n,12,r,`FBX array property header for ${s}`);const i=e.getUint32(n,!0),a=e.getUint32(n+4,!0),l=e.getUint32(n+8,!0),u=i*o;let c;if(G(t,n+=12,l,r,`FBX array property data for ${s}`),1===a)c=function(e,t){if(!Number.isInteger(t)||t<0)throw new Error("zlib: invalid expected length");if(e.byteLength<6)throw new Error("zlib: unexpected end of input");const n=e[0],s=e[1];if(8!=(15&n)||n>>4>7||((n<<8)+s)%31!=0)throw new Error("zlib: invalid header");if(32&s)throw new Error("zlib: preset dictionary not supported");const o=new C(e,2,e.byteLength-4),r=new R(t);let i=!1;for(;!i;)switch(i=1===o.readBits(1),o.readBits(2)){case 0:L(o,r);break;case 1:P(o,r,E(),I());break;case 2:{const{literalLengthTree:e,distanceTree:t}=B(o);P(o,r,e,t);break}default:throw new Error("deflate: invalid block type")}if(o.byteOffset<e.byteLength-4)throw new Error("zlib: trailing deflate data");r.finish();const a=(e[e.byteLength-4]<<24|e[e.byteLength-3]<<16|e[e.byteLength-2]<<8|e[e.byteLength-1])>>>0;if(r.adler32()!==a)throw new Error("zlib: adler32 mismatch");return r.bytes}(t.subarray(n,n+l),u);else{if(0!==a)throw new Error(`Unsupported FBX array encoding: ${a}`);if(l!==u)throw new Error(`Invalid FBX array byte length for ${s}`);c=t.slice(n,n+l)}const d=c.buffer.slice(c.byteOffset,c.byteOffset+c.byteLength);let h;switch(s){case"float32[]":h=new Float32Array(d);break;case"float64[]":h=new Float64Array(d);break;case"int32[]":h=new Int32Array(d);break;case"boolean[]":h=c;break;case"int64[]":h=function(e){const 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]=H(t,8*e);return n}(c);break;default:throw new Error(`Unexpected array type: ${s}`)}return{property:{type:s,value:h},nextOffset:n+l}}function G(e,t,n,s,o){if(t<0||n<0||t+n>s||t+n>e.byteLength)throw new Error(`${o}: unexpected end of input`)}function V(e,t){const n=e.getUint32(t,!0);return 4294967296*e.getUint32(t+4,!0)+n}function H(e,t){const n=e.getUint32(t,!0);return 4294967296*e.getInt32(t+4,!0)+n}function K(e,t,n){let s="";for(let o=0;o<n;o++)s+=String.fromCharCode(e[t+o]);return s}function $(e){const t=new q(e),n=function(e){const t=e.match(/;\s*FBX\s+(\d+)\.(\d+)\.(\d+)/);if(!t)throw new Error("Cannot determine FBX version from ASCII header");return 1e3*parseInt(t[1])+100*parseInt(t[2])+parseInt(t[3])}(e),s=[];for(;!t.isEOF()&&(t.skipWhitespaceAndComments(),!t.isEOF());){const e=W(t);e&&s.push(e)}return{version:n,nodes:s}}var U;!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"}(U||(U={}));let q=class{constructor(e){this.text=e,this.pos=0,this.len=e.length}isEOF(){return this.skipWhitespaceAndComments(),this.pos>=this.len}peek(){const 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};const 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 new Error(`Unexpected character '${e}' at position ${this.pos}`)}}expect(e){const t=this.next();if(t.type!==e)throw new Error(`Expected token type ${e} but got ${t.type} ('${t.value}') at pos ${t.pos}`);return t}isNextNodeStart(){const 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]||"\t"===this.text[this.pos]);)this.pos++;const 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;){const e=this.text[this.pos];if(" "===e||"\t"===e||"\r"===e||"\n"===e)this.pos++;else{if(";"!==e)break;for(;this.pos<this.len&&"\n"!==this.text[this.pos];)this.pos++}}}readString(){const 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]):t+=this.text[this.pos],this.pos++;return this.pos<this.len&&this.pos++,{type:2,value:t,pos:e}}readNumber(){const e=this.pos;for("-"!==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.isDigit(this.text[this.pos]);)this.pos++;if(this.pos<this.len&&("e"===this.text[this.pos]||"E"===this.text[this.pos]))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++;return{type:1,value:this.text.substring(e,this.pos),pos:e}}readIdentifier(){const e=this.pos;for(;this.pos<this.len&&this.isIdentChar(this.text[this.pos]);)this.pos++;return{type:0,value:this.text.substring(e,this.pos),pos:e}}isDigit(e){return e>="0"&&e<="9"}isNumberStart(e){return!!this.isDigit(e)||("-"===e||"+"===e)&&this.pos+1<this.len&&(this.isDigit(this.text[this.pos+1])||"."===this.text[this.pos+1])}isIdentStart(e){return e>="a"&&e<="z"||e>="A"&&e<="Z"||"_"===e}isIdentChar(e){return this.isIdentStart(e)||this.isDigit(e)||"|"===e}};function W(e){const t=e.peek();if(4===t.type||8===t.type)return null;const n=e.next();if(0!==n.type)throw new Error(`Expected identifier for node name, got '${n.value}' at pos ${n.pos}`);const s=n.value;e.expect(5);const o=[],r=[];let i=e.peek();if(7===i.type){e.next();const t=e.expect(1),n=parseInt(t.value);e.expect(3);const i=e.next();if(0===i.type&&"a"===i.value){e.expect(5);const t=function(e,t){const n=[];for(;;){const t=e.peek();if(4===t.type||8===t.type)break;if(6!==t.type){if(1!==t.type)break;{const t=e.next();n.push(Number(t.value))}}else e.next()}if(n.length!==t)throw new Error(`ASCII FBX array declared ${t} values but parsed ${n.length}`);return n}(e,n);o.push({type:"float64[]",value:new Float64Array(t)})}return e.expect(4),{name:s,properties:o,children:r}}for(i=e.peek();3!==i.type&&4!==i.type&&8!==i.type;){if(1===i.type){const t=e.next(),n=z(t.value);!Number.isInteger(n)||t.value.includes(".")||t.value.includes("e")||t.value.includes("E")?o.push({type:"float64",value:n}):o.push({type:j(n)?"int32":"int64",value:n})}else if(2===i.type){const t=e.next();o.push({type:"string",value:t.value})}else if(0===i.type){if(e.isNextNodeStart())break;const t=e.next();o.push({type:"string",value:t.value})}else{if(6!==i.type)break;e.next()}i=e.peek()}if(i=e.peek(),3===i.type){for(e.next();i=e.peek(),4!==i.type&&8!==i.type;){const t=W(e);if(!t)break;r.push(t)}e.expect(4)}return{name:s,properties:o,children:r}}function z(e){return Number(e)}function j(e){return e>=-2147483648&&e<=2147483647}function X(e,t){return e.children.find(e=>e.name===t)}function Y(e,t){return e.nodes.find(e=>e.name===t)}function Q(e,t){if(t<e.properties.length)return e.properties[t].value}function Z(e){const t=e.indexOf("\0");t>=0&&(e=e.substring(0,t));const n=e.indexOf("::");return n>=0&&(e=e.substring(n+2)),e}function J(e,t,n){var s;const o=null!==(s=e.childrenOf.get(t))&&void 0!==s?s:[],r=[];for(const t of o){const s=e.objects.get(t.id);!s||n&&s.name!==n||r.push({id:t.id,node:s,propertyName:t.propertyName})}return r}function ee(e){return function(e){if("number"==typeof e){if(!Number.isSafeInteger(e))throw new Error(`Unsafe FBX object ID ${e.toString()}: object IDs must be safe integers.`);return e}}(e)}function te(e,t){const n=ee(e);if(void 0!==n)return n;if("string"!=typeof e)return;const s=Z(e);return"Scene"===s?0:t.get(s)}function ne(e,t,n,s,o,r,i,a,l){e.push({type:o,childId:r,parentId:i,propertyName:a}),t.has(i)||t.set(i,[]),t.get(i).push({id:r,propertyName:a}),n.get(r)&&s.push({reason:"duplicate-parent",message:"FBX object has multiple parents; preserving the existing last-parent behavior.",connectionIndex:l,type:o,childId:r,parentId:i,propertyName:a}),n.set(r,{id:i,propertyName:a})}function se(e,t){var n,s;const o=Z(null!==(n=Q(e,0))&&void 0!==n?n:e.name),r=null!==(s=Q(e,1))&&void 0!==s?s:"";return Object.assign(Object.assign({},e),{properties:[{type:"int64",value:t},{type:"string",value:o},{type:"string",value:r}]})}function oe(e,t){var n;return{name:"Geometry",properties:[{type:"int64",value:t},{type:"string",value:Z(null!==(n=Q(e,0))&&void 0!==n?n:"Geometry")},{type:"string",value:"Mesh"}],children:e.children}}function re(e,t){var n,s,o;const r=Z(null!==(n=Q(e,1))&&void 0!==n?n:"Geometry"),i=X(e,"Vertices");if(!i)throw new Error(`Geometry '${r}' has no Vertices node`);const a=fe(_e(i)),l=X(e,"PolygonVertexIndex");if(!l)throw new Error(`Geometry '${r}' has no PolygonVertexIndex node`);const u=[],c=function(e){const t=[];let n=[],s=0;for(let o=0;o<e.length;o++){const r=e[o];r<0?(n.push(-(r+1)),t.push({indices:n,startIndex:s}),n=[],s=o+1):n.push(r)}return t}(pe(_e(l))),d=function(e,t,n){const s=[];for(let o=0;o<e.length;o++){const r=e[o];s.push(...ie(r,o,t,n))}return s}(c,a,u),h=function(e){const t=[];for(let n=0;n<e.length;n++){const s=e[n];for(let e=0;e<s.indices.length;e++)t.push({polyIndex:n,vertexInPoly:e,controlPointIndex:s.indices[e],globalIndex:s.startIndex+e})}return t}(c),m=X(e,"LayerElementNormal");let f=null;m&&(f=he(m,"Normals","NormalsIndex",h,a.length,3,u));const p=e.children.filter(e=>"LayerElementUV"===e.name),_=[];for(const e of p){const t=X(e,"Name"),n=t&&null!==(s=Q(t,0))&&void 0!==s?s:`UVSet${_.length}`,o=he(e,"UV","UVIndex",h,a.length,2,u);o&&_.push({name:n,data:o})}const g=_.length>0?_[0].data:null,y=X(e,"LayerElementColor");let v=null;if(y){const e=he(y,"Colors","ColorIndex",h,a.length,4,u);if(e){v=new Float32Array(e.length);for(let t=0;t<e.length;t++)v[t]=e[t]}}const b=X(e,"LayerElementTangent"),x=X(e,"LayerElementBinormal"),T=x?he(x,"Binormals","BinormalsIndex",h,a.length,3,u):null,A=b?function(e,t,n,s,o,r){const i=function(e,t,n,s,o,r){var i,a,l,u;const c=X(e,"Tangents");if(!c)return 3;const d=fe(_e(c)),h=null!==(a=Q(null!==(i=X(e,"MappingInformationType"))&&void 0!==i?i:{name:"",properties:[],children:[]},0))&&void 0!==a?a:"",m=null!==(u=Q(null!==(l=X(e,"ReferenceInformationType"))&&void 0!==l?l:{name:"",properties:[],children:[]},0))&&void 0!==u?u:"",f=X(e,"TangentsIndex"),p=f?pe(_e(f)):null,_="IndexToDirect"===m&&p?Math.max(...Array.from(p),0)+1:"ByControlPoint"===h||"ByVertice"===h?o:"AllSame"===h?1:s.length;if(_>0&&d.length%_===0){const e=d.length/_;if(3===e||4===e)return e}return r.push({type:"layer-data-too-short",message:`Could not infer stride for layer '${e.name}', defaulting to 3.`,layerName:e.name}),3}(e,0,0,t,n,r),a=he(e,"Tangents","TangentsIndex",t,0,i,r);if(!a)return null;const l=new Float64Array(4*t.length);for(let e=0;e<t.length;e++){const t=e*i,n=4*e;l[n]=a[t],l[n+1]=a[t+1],l[n+2]=a[t+2],l[n+3]=i>=4?a[t+3]:me(e,l,s,o)}return l}(b,h,a.length/3,f,T,u):null,M=X(e,"LayerElementMaterial");let w=null;M&&(w=function(e,t){var n,s;const o=X(e,"MappingInformationType"),r=X(e,"ReferenceInformationType");if(!o||!r)return null;const i=null!==(n=Q(o,0))&&void 0!==n?n:"",a=null!==(s=Q(r,0))&&void 0!==s?s:"";if("AllSame"===i){const n=X(e,"Materials"),s=n?pe(_e(n)):null,o=s&&s.length>0?s[0]:0,r=new Int32Array(t);return 0!==o&&r.fill(o),r}if("ByPolygon"===i){const t=X(e,"Materials");if(!t)return null;const n=pe(_e(t));if("Direct"===a||"IndexToDirect"===a)return n}return null}(M,c.length));const C=function(e,t,n,s,o,r,i,a,l){const u=n.length,c=new Float64Array(3*u),d=new Uint32Array(u);for(let t=0;t<n.length;t++){const s=n[t].controlPointIndex;c[3*t]=e[3*s],c[3*t+1]=e[3*s+1],c[3*t+2]=e[3*s+2],d[t]=s}const h=3*t.length,m=new Uint32Array(h);for(let e=0;e<t.length;e++)m[3*e]=t[e].vertices[0],m[3*e+1]=t[e].vertices[1],m[3*e+2]=t[e].vertices[2];return{positions:c,indices:m,normals:s,uvs:o,uvSets:r,colors:i,tangents:a,binormals:l,controlPointIndices:d}}(a,d,h,f,g,_,v,A,T);let R=null;if(w){let e=!0;const t=w[0];for(let n=1;n<w.length;n++)if(w[n]!==t){e=!1;break}if(!e||0!==t){const e=C.indices.length/3;R=new Int32Array(e);for(let e=0;e<d.length;e++)R[e]=null!==(o=w[d[e].polyIndex])&&void 0!==o?o:0}}return{id:t,name:r,positions:C.positions,indices:C.indices,normals:C.normals,uvs:C.uvs,uvSets:C.uvSets,colors:C.colors,tangents:C.tangents,binormals:C.binormals,controlPointIndices:C.controlPointIndices,materialIndices:R,diagnostics:u}}function ie(e,t,n,s){if(e.indices.length<3)return s.push({type:"degenerate-polygon",message:`Polygon ${t} has fewer than three vertices.`,polygonIndex:t}),[];if(3===e.indices.length)return[{vertices:[e.startIndex,e.startIndex+1,e.startIndex+2],polyIndex:t}];const o=function(e,t){const n=function(e,t){let n=0,s=0,o=0;for(let r=0;r<e.indices.length;r++){const i=3*e.indices[r],a=3*e.indices[(r+1)%e.indices.length],l=t[i],u=t[i+1],c=t[i+2],d=t[a],h=t[a+1],m=t[a+2];n+=(u-h)*(c+m),s+=(c-m)*(l+d),o+=(l-d)*(u+h)}return[n,s,o]}(e,t),s=Math.abs(n[0]),o=Math.abs(n[1]),r=Math.abs(n[2]);if(s+o+r<1e-12)return null;const i=s>o&&s>r?0:o>r?1:2;return e.indices.map(e=>{const s=t[3*e],o=t[3*e+1],r=t[3*e+2];return 0===i?n[0]>=0?[o,r]:[r,o]:1===i?n[1]>=0?[r,s]:[s,r]:n[2]>=0?[s,o]:[o,s]})}(e,n);if(!o)return s.push({type:"degenerate-polygon",message:`Polygon ${t} has a near-zero normal; using fan triangulation.`,polygonIndex:t}),ae(e,t);const r=function(e){let t=0;for(let n=0;n<e.length;n++){const s=e[n],o=e[(n+1)%e.length];t+=s[0]*o[1]-o[0]*s[1]}return t/2}(o);if(Math.abs(r)<1e-12)return s.push({type:"degenerate-polygon",message:`Polygon ${t} projects to near-zero area; using fan triangulation.`,polygonIndex:t}),ae(e,t);const i=r>0,a=e.indices.map((e,t)=>t),l=[];let u=0;for(;a.length>3&&u++<e.indices.length*e.indices.length;){let n=!1;for(let s=0;s<a.length;s++){const r=a[(s+a.length-1)%a.length],u=a[s],c=a[(s+1)%a.length];if(le(o[r],o[u],o[c],i)&&!ue(o,a,r,u,c)){l.push({vertices:[e.startIndex+r,e.startIndex+u,e.startIndex+c],polyIndex:t}),a.splice(s,1),n=!0;break}}if(!n)return s.push({type:"triangulation-fallback",message:`Polygon ${t} could not be fully ear-clipped; using fan triangulation.`,polygonIndex:t}),ae(e,t)}return l.push({vertices:[e.startIndex+a[0],e.startIndex+a[1],e.startIndex+a[2]],polyIndex:t}),l}function ae(e,t){const n=[];for(let s=1;s<e.indices.length-1;s++)n.push({vertices:[e.startIndex,e.startIndex+s,e.startIndex+s+1],polyIndex:t});return n}function le(e,t,n,s){const o=(t[0]-e[0])*(n[1]-e[1])-(t[1]-e[1])*(n[0]-e[0]);return s?o>1e-12:o<-1e-12}function ue(e,t,n,s,o){for(const r of t)if(r!==n&&r!==s&&r!==o&&ce(e[r],e[n],e[s],e[o]))return!0;return!1}function ce(e,t,n,s){const o=Math.abs(de(t,n,s)),r=Math.abs(de(e,t,n)),i=Math.abs(de(e,n,s)),a=Math.abs(de(e,s,t));return Math.abs(o-(r+i+a))<1e-10}function de(e,t,n){return(t[0]-e[0])*(n[1]-e[1])-(t[1]-e[1])*(n[0]-e[0])}function he(e,t,n,s,o,r,i){var a,l;const u=X(e,"MappingInformationType"),c=X(e,"ReferenceInformationType");if(!u||!c)return null;const d=null!==(a=Q(u,0))&&void 0!==a?a:"",h=null!==(l=Q(c,0))&&void 0!==l?l:"",m=X(e,t);if(!m)return null;const f=fe(_e(m));let p=null;if("IndexToDirect"===h){const t=X(e,n);t&&(p=pe(_e(t)))}const _=new Float64Array(s.length*r);for(let t=0;t<s.length;t++){const n=s[t];let o;o="ByPolygonVertex"===d?"IndexToDirect"===h&&p?p[n.globalIndex]:n.globalIndex:"ByControlPoint"===d||"ByVertice"===d?"IndexToDirect"===h&&p?p[n.controlPointIndex]:n.controlPointIndex:"ByPolygon"===d?"IndexToDirect"===h&&p?p[n.polyIndex]:n.polyIndex:"AllSame"===d?0:n.globalIndex;for(let n=0;n<r;n++){const s=o*r+n;o<0||s>=f.length?(i.push({type:s>=f.length?"layer-data-too-short":"layer-index-out-of-bounds",message:`Layer '${e.name}' references unavailable element ${o}.`,layerName:e.name,index:o}),_[t*r+n]=0):_[t*r+n]=f[s]}}return _}function me(e,t,n,s){if(!n||!s)return 1;const o=4*e,r=3*e,i=n[r],a=n[r+1],l=n[r+2],u=t[o],c=t[o+1],d=t[o+2];return(a*d-l*c)*s[r]+(l*u-i*d)*s[r+1]+(i*c-a*u)*s[r+2]<0?-1:1}function fe(e){if(e instanceof Float64Array)return e;if(e instanceof Float32Array)return new Float64Array(e);if(e instanceof Int32Array)return new Float64Array(e);if(Array.isArray(e)){const t=new Float64Array(e.length);for(let n=0;n<e.length;n++)t[n]=Number(e[n]);return t}throw new Error(`Cannot convert ${typeof e} to Float64Array`)}function pe(e){if(e instanceof Int32Array)return e;if(e instanceof Float64Array){const 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){const 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)){const t=new Int32Array(e.length);for(let n=0;n<e.length;n++)t[n]=Math.round(Number(e[n]));return t}throw new Error(`Cannot convert ${typeof e} to Int32Array`)}function _e(e){return 1===e.properties.length?e.properties[0].value:e.properties.map(e=>e.value)}function ge(e,t,n){const s=e.get(t);if(s)return n?s.get(n):s.values().next().value}function ye(e,t,n,s=0){var o;return null===(o=xe(e,t,n))||void 0===o?void 0:o[s]}function ve(e,t,n,s){var o;return null!==(o=Te(ye(e,t,n)))&&void 0!==o?o:s}function be(e,t,n,s){const o=xe(e,t,n);if(!o)return s;const r=Te(o[0]),i=Te(o[1]),a=Te(o[2]);return void 0!==r&&void 0!==i&&void 0!==a?[r,i,a]:s}function xe(e,t,n){var s,o;return null!==(s=function(e,t){const n=[X(e,"Properties70"),X(e,"Properties60")].filter(e=>void 0!==e);for(const e of n)for(const n of e.children)if(("P"===n.name||"Property"===n.name)&&Q(n,0)===t)return n.properties.slice("Property"===n.name?3:4).map(e=>e.value)}(e,n))&&void 0!==s?s:null===(o=null==t?void 0:t.properties.get(n))||void 0===o?void 0:o.values}function Te(e){if("number"==typeof e)return e}function Ae(e,t,n){var s;const o=new Map,r=X(n,"Properties70");for(const e of null!==(s=null==r?void 0:r.children)&&void 0!==s?s:[]){if("P"!==e.name)continue;const t=Me(e);t&&o.set(t.name,t)}return{objectType:e,templateName:t,properties:o}}function Me(e){var t,n,s;const o=Q(e,0);return o?{name:o,propertyType:null!==(t=Q(e,1))&&void 0!==t?t:"",label:null!==(n=Q(e,2))&&void 0!==n?n:"",flags:null!==(s=Q(e,3))&&void 0!==s?s:"",values:e.properties.slice(4).map(e=>e.value)}:null}function we(e,t,n,s){var o,r,i,a;const l=Z(null!==(o=Q(e,1))&&void 0!==o?o:"Material"),u=function(e,t){var n,s;if(!t)return;const o=X(e,"ShadingModel"),r=o?Q(o,0):void 0;return"phong"===(null==r?void 0:r.toLowerCase())?null!==(n=ge(t,"Material","FbxSurfacePhong"))&&void 0!==n?n:ge(t,"Material"):"lambert"===(null==r?void 0:r.toLowerCase())&&null!==(s=ge(t,"Material","FbxSurfaceLambert"))&&void 0!==s?s:ge(t,"Material")}(e,s),c=X(e,"ShadingModel"),d="phong"===(c?null!==(r=Q(c,0))&&void 0!==r?r:"Lambert":null!==(i=ye(e,u,"ShadingModel"))&&void 0!==i?i:"Lambert").toLowerCase()?"Phong":"Lambert",h=function(e,t){var n,s,o,r,i;const a={};return a.diffuseColor=null!==(n=Ce(e,t,"DiffuseColor"))&&void 0!==n?n:Ce(e,t,"Diffuse"),a.diffuseFactor=Re(e,t,"DiffuseFactor"),a.ambientColor=null!==(s=Ce(e,t,"AmbientColor"))&&void 0!==s?s:Ce(e,t,"Ambient"),a.ambientFactor=Re(e,t,"AmbientFactor"),a.specularColor=null!==(o=Ce(e,t,"SpecularColor"))&&void 0!==o?o:Ce(e,t,"Specular"),a.specularFactor=Re(e,t,"SpecularFactor"),a.shininess=null!==(r=Re(e,t,"Shininess"))&&void 0!==r?r:Re(e,t,"ShininessExponent"),a.emissiveColor=null!==(i=Ce(e,t,"EmissiveColor"))&&void 0!==i?i:Ce(e,t,"Emissive"),a.emissiveFactor=Re(e,t,"EmissiveFactor"),a.opacity=Re(e,t,"Opacity"),a.transparencyFactor=Re(e,t,"TransparencyFactor"),a}(e,u),m=function(e,t,n){var s,o,r,i,a;const l=[],u=J(t,e,"Texture");for(const{id:e,node:c,propertyName:d}of u){const u=X(c,"FileName"),h=X(c,"RelativeFilename"),m=u&&null!==(s=Q(u,0))&&void 0!==s?s:"",f=h&&null!==(o=Q(h,0))&&void 0!==o?o:"";let p,_;const g=null!==(r=Re(c,n,"UVRotation"))&&void 0!==r?r:Re(c,n,"Rotation");let y;p=null!==(i=Se(c,n,"UVTranslation"))&&void 0!==i?i:Se(c,n,"Translation"),_=null!==(a=Se(c,n,"UVScaling"))&&void 0!==a?a:Se(c,n,"Scaling");const v=ye(c,n,"UVSet");v&&v.length>0&&(y=v),null!=p||(p=Fe(c,"ModelUVTranslation")),null!=_||(_=Fe(c,"ModelUVScaling"));let b=null;const x=J(t,e,"Video");for(const{node:e}of x){const t=X(e,"Content");if(t&&t.properties.length>0){const e=t.properties[0].value;e instanceof Uint8Array&&e.length>0?b=e:e instanceof ArrayBuffer&&e.byteLength>0&&(b=new Uint8Array(e))}}l.push({propertyName:null!=d?d:"DiffuseColor",fileName:m,relativeFileName:f,id:e,embeddedData:b,uvTranslation:p,uvScaling:_,uvRotation:g,uvSetName:y})}return l}(t,n,s?null!==(a=ge(s,"Texture","FbxFileTexture"))&&void 0!==a?a:ge(s,"Texture"):void 0);return{id:t,name:l,type:d,properties:h,textures:m}}function Ce(e,t,n){const s=xe(e,t,n);if(!s||s.length<3)return;const o=Oe(s[0]),r=Oe(s[1]),i=Oe(s[2]);return void 0!==o&&void 0!==r&&void 0!==i?[o,r,i]:void 0}function Re(e,t,n){return Oe(ye(e,t,n))}function Se(e,t,n){const s=xe(e,t,n);if(!s)return;const o=Oe(s[0]),r=Oe(s[1]);return void 0!==o&&void 0!==r?[o,r]:void 0}function Oe(e){if("number"==typeof e)return e}function Fe(e,t){var n,s;const o=X(e,t);if(!o)return;const r=Oe(null===(n=o.properties[0])||void 0===n?void 0:n.value),i=Oe(null===(s=o.properties[1])||void 0===s?void 0:s.value);return void 0!==r&&void 0!==i?[r,i]:void 0}function Ee(e,t,n){var s;const o=n.parentOf.get(e);if(!o)return null;const r=o.id,i=n.objects.get(r);if(!i||"Geometry"!==i.name)return null;const a=n.parentOf.get(r),l=a?n.objects.get(a.id):void 0,u="Model"===(null==l?void 0:l.name)?a.id:void 0,c=J(n,e,"Deformer");if(0===c.length)return null;const d=new Map;for(const{id:e,node:t}of c){if("Cluster"!==Q(t,2))continue;const s=J(n,e,"Model");s.length>0&&d.set(s[0].id,{clusterId:e,clusterNode:t})}const h=function(e,t){var n,s;const o=t.parentOf.get(e),r=o?t.objects.get(o.id):void 0,i="Model"===(null==r?void 0:r.name)?o.id:void 0;if(void 0===i)return new Map;for(const[,e]of Array.from(t.objects)){if("Pose"!==e.name||"BindPose"!==Q(e,2))continue;const t=new Map;for(const o of e.children){if("PoseNode"!==o.name)continue;const e=X(o,"Node"),r=X(o,"Matrix"),i=null===(n=null==e?void 0:e.properties[0])||void 0===n?void 0:n.value,a=null===(s=null==r?void 0:r.properties[0])||void 0===s?void 0:s.value;if("number"!=typeof i)continue;const l=Ge(a);16===(null==l?void 0:l.length)&&t.set(i,l)}if(t.has(i))return t}return new Map}(r,n),m=[],f=function(e,t,n,s){var o,r,i,a,l;const u=[],c=new Set,d=function(e,t){const n=new Set(Array.from(e.keys()));for(const s of Array.from(e.keys())){let e=Ie(s,t);for(;void 0!==e;){const s=t.objects.get(e);if(!s||"Model"!==s.name)break;n.add(e),e=Ie(e,t)}}return n}(e,n),h=function(e,t){const n=new Map;for(const s of Array.from(e)){let o=Ie(s,t);for(;void 0!==o;){if(e.has(o)){n.set(s,o);break}o=Ie(o,t)}}return n}(d,n),m=function(e,t){const n=new Map;for(const s of Array.from(e)){const e=t.get(s);void 0!==e&&(n.has(e)||n.set(e,[]),n.get(e).push(s))}return n}(d,h),f=Array.from(d).filter(e=>!h.has(e)).map(e=>({modelId:e,parentIndex:-1}));for(;f.length>0;){const{modelId:d,parentIndex:h}=f.shift();if(c.has(d))continue;c.add(d);const p=n.objects.get(d);if(!p)continue;const _=u.length,g=e.get(d),y=Pe(p),{bindPoseMatrix:v,transformLinkMatrix:b,transformAssociateModelMatrix:x,clusterMode:T}=g?Be(g.clusterNode):{bindPoseMatrix:null,transformLinkMatrix:null,transformAssociateModelMatrix:null,clusterMode:"Unknown"},A=Ne(d,Z(null!==(o=Q(p,1))&&void 0!==o?o:`Bone${_}`),void 0!==g,T,v,b,x,null!==(r=t.get(d))&&void 0!==r?r:null);s.push(...A),u.push({modelId:d,name:Z(null!==(i=Q(p,1))&&void 0!==i?i:`Bone${_}`),index:_,parentIndex:h,isCluster:void 0!==g,translation:y.translation,rotation:y.rotation,preRotation:y.preRotation,postRotation:y.postRotation,rotationPivot:y.rotationPivot,scalingPivot:y.scalingPivot,rotationOffset:y.rotationOffset,scalingOffset:y.scalingOffset,scale:y.scale,rotationOrder:y.rotationOrder,inheritType:y.inheritType,clusterMode:T,bindPoseMatrix:v,transformLinkMatrix:b,transformAssociateModelMatrix:x,modelBindPoseMatrix:null!==(a=t.get(d))&&void 0!==a?a:null,diagnostics:A});for(const e of null!==(l=m.get(d))&&void 0!==l?l:[])c.has(e)||f.push({modelId:e,parentIndex:_})}return u}(d,h,n,m);if(0===f.length)return null;const{boneIndices:p,boneWeights:_}=function(e,t){var n,s,o;let r=0;for(const s of e){const e=t.get(s.modelId);if(!e)continue;const o=X(e.clusterNode,"Indexes");if(!o)continue;const i=De(null===(n=o.properties[0])||void 0===n?void 0:n.value);if(i)for(let e=0;e<i.length;e++)i[e]>r&&(r=i[e])}const i=r+1,a=new Array(i),l=new Array(i);for(let e=0;e<i;e++)a[e]=[],l[e]=[];for(const n of e){const e=t.get(n.modelId);if(!e)continue;const r=X(e.clusterNode,"Indexes"),i=X(e.clusterNode,"Weights");if(!r||!i)continue;const u=De(null===(s=r.properties[0])||void 0===s?void 0:s.value),c=Ge(null===(o=i.properties[0])||void 0===o?void 0:o.value);if(u&&c)for(let e=0;e<u.length;e++){const t=u[e];a[t].push(n.index),l[t].push(c[e])}}for(let e=0;e<i;e++){if(0===a[e].length)continue;const t=a[e].map((t,n)=>({index:t,weight:l[e][n]}));t.sort((e,t)=>t.weight-e.weight);const n=t.slice(0,8);a[e]=n.map(e=>e.index),l[e]=n.map(e=>e.weight)}for(let e=0;e<i;e++){const t=l[e].reduce((e,t)=>e+t,0);if(t>0)for(let n=0;n<l[e].length;n++)l[e][n]/=t}return{boneIndices:a,boneWeights:l}}(f,d);return{id:e,geometryId:r,meshBindPoseMatrix:void 0!==u&&null!==(s=h.get(u))&&void 0!==s?s:null,bones:f,boneIndices:p,boneWeights:_,diagnostics:m}}function Ie(e,t){const n=t.connections.find(n=>{var s;return"OO"===n.type&&n.childId===e&&"Model"===(null===(s=t.objects.get(n.parentId))||void 0===s?void 0:s.name)});return null==n?void 0:n.parentId}function Le(e){const t=Q(e,2);return"Root"===t||"LimbNode"===t}function Pe(e){var t,n,s,o,r,i,a,l,u,c,d,h,m,f,p,_,g,y,v,b,x,T,A,M,w,C,R,S,O,F,E,I,L,P,B,N,k,D,G,V,H,K,$,U,q,W,z,j,Y,Z,J,ee,te,ne,se,oe,re,ie;const ae=[0,0,0],le=[0,0,0],ue=[0,0,0],ce=[0,0,0],de=[0,0,0],he=[0,0,0],me=[0,0,0],fe=[0,0,0],pe=[1,1,1];let _e=0,ge=1;const ye=X(e,"Properties70");if(!ye)return{translation:ae,rotation:le,preRotation:ue,postRotation:ce,rotationPivot:de,scalingPivot:he,rotationOffset:me,scalingOffset:fe,scale:pe,rotationOrder:_e,inheritType:ge};for(const e of ye.children){if("P"!==e.name)continue;const X=Q(e,0);if(X)switch(X){case"Lcl Translation":ae[0]=null!==(n=ke(null===(t=e.properties[4])||void 0===t?void 0:t.value))&&void 0!==n?n:0,ae[1]=null!==(o=ke(null===(s=e.properties[5])||void 0===s?void 0:s.value))&&void 0!==o?o:0,ae[2]=null!==(i=ke(null===(r=e.properties[6])||void 0===r?void 0:r.value))&&void 0!==i?i:0;break;case"Lcl Rotation":le[0]=null!==(l=ke(null===(a=e.properties[4])||void 0===a?void 0:a.value))&&void 0!==l?l:0,le[1]=null!==(c=ke(null===(u=e.properties[5])||void 0===u?void 0:u.value))&&void 0!==c?c:0,le[2]=null!==(h=ke(null===(d=e.properties[6])||void 0===d?void 0:d.value))&&void 0!==h?h:0;break;case"PreRotation":ue[0]=null!==(f=ke(null===(m=e.properties[4])||void 0===m?void 0:m.value))&&void 0!==f?f:0,ue[1]=null!==(_=ke(null===(p=e.properties[5])||void 0===p?void 0:p.value))&&void 0!==_?_:0,ue[2]=null!==(y=ke(null===(g=e.properties[6])||void 0===g?void 0:g.value))&&void 0!==y?y:0;break;case"PostRotation":ce[0]=null!==(b=ke(null===(v=e.properties[4])||void 0===v?void 0:v.value))&&void 0!==b?b:0,ce[1]=null!==(T=ke(null===(x=e.properties[5])||void 0===x?void 0:x.value))&&void 0!==T?T:0,ce[2]=null!==(M=ke(null===(A=e.properties[6])||void 0===A?void 0:A.value))&&void 0!==M?M:0;break;case"RotationPivot":de[0]=null!==(C=ke(null===(w=e.properties[4])||void 0===w?void 0:w.value))&&void 0!==C?C:0,de[1]=null!==(S=ke(null===(R=e.properties[5])||void 0===R?void 0:R.value))&&void 0!==S?S:0,de[2]=null!==(F=ke(null===(O=e.properties[6])||void 0===O?void 0:O.value))&&void 0!==F?F:0;break;case"ScalingPivot":he[0]=null!==(I=ke(null===(E=e.properties[4])||void 0===E?void 0:E.value))&&void 0!==I?I:0,he[1]=null!==(P=ke(null===(L=e.properties[5])||void 0===L?void 0:L.value))&&void 0!==P?P:0,he[2]=null!==(N=ke(null===(B=e.properties[6])||void 0===B?void 0:B.value))&&void 0!==N?N:0;break;case"RotationOffset":me[0]=null!==(D=ke(null===(k=e.properties[4])||void 0===k?void 0:k.value))&&void 0!==D?D:0,me[1]=null!==(V=ke(null===(G=e.properties[5])||void 0===G?void 0:G.value))&&void 0!==V?V:0,me[2]=null!==(K=ke(null===(H=e.properties[6])||void 0===H?void 0:H.value))&&void 0!==K?K:0;break;case"ScalingOffset":fe[0]=null!==(U=ke(null===($=e.properties[4])||void 0===$?void 0:$.value))&&void 0!==U?U:0,fe[1]=null!==(W=ke(null===(q=e.properties[5])||void 0===q?void 0:q.value))&&void 0!==W?W:0,fe[2]=null!==(j=ke(null===(z=e.properties[6])||void 0===z?void 0:z.value))&&void 0!==j?j:0;break;case"Lcl Scaling":pe[0]=null!==(Z=ke(null===(Y=e.properties[4])||void 0===Y?void 0:Y.value))&&void 0!==Z?Z:1,pe[1]=null!==(ee=ke(null===(J=e.properties[5])||void 0===J?void 0:J.value))&&void 0!==ee?ee:1,pe[2]=null!==(ne=ke(null===(te=e.properties[6])||void 0===te?void 0:te.value))&&void 0!==ne?ne:1;break;case"RotationOrder":_e=null!==(oe=ke(null===(se=e.properties[4])||void 0===se?void 0:se.value))&&void 0!==oe?oe:0;break;case"InheritType":ge=null!==(ie=ke(null===(re=e.properties[4])||void 0===re?void 0:re.value))&&void 0!==ie?ie:1}}return{translation:ae,rotation:le,preRotation:ue,postRotation:ce,rotationPivot:de,scalingPivot:he,rotationOffset:me,scalingOffset:fe,scale:pe,rotationOrder:_e,inheritType:ge}}function Be(e){let t=null,n=null,s=null,o="Normalize";const r=X(e,"Transform");if(r&&r.properties[0]){const e=r.properties[0].value;e instanceof Float64Array&&16===e.length?t=e:e instanceof Float32Array&&16===e.length&&(t=new Float64Array(e))}const i=X(e,"TransformLink");if(i&&i.properties[0]){const e=i.properties[0].value;e instanceof Float64Array&&16===e.length?n=e:e instanceof Float32Array&&16===e.length&&(n=new Float64Array(e))}const a=X(e,"TransformAssociateModel");if(a&&a.properties[0]){const e=a.properties[0].value;e instanceof Float64Array&&16===e.length?s=e:e instanceof Float32Array&&16===e.length&&(s=new Float64Array(e))}const l=X(e,"Mode"),u=l?Q(l,0):void 0;return"Normalize"===u||"Additive"===u||"TotalOne"===u?o=u:u&&(o="Unknown"),{bindPoseMatrix:t,transformLinkMatrix:n,transformAssociateModelMatrix:s,clusterMode:o}}function Ne(e,t,n,s,o,r,i,a){if(!n)return[];const l=[];return"Additive"!==s&&"TotalOne"!==s||l.push({type:"cluster-mode-runtime-unsupported",message:`Cluster mode '${s}' is preserved but not applied by Babylon linear blend skinning.`,boneModelId:e,boneName:t,clusterMode:s}),o||l.push({type:"missing-cluster-transform",message:"Cluster is missing Transform matrix; falling back to rest/bind-pose data.",boneModelId:e,boneName:t,clusterMode:s}),r||l.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:s}),a||l.push({type:"missing-bind-pose-matrix",message:"No BindPose matrix was found for this bone model.",boneModelId:e,boneName:t,clusterMode:s}),i&&l.push({type:"associate-model-present",message:"TransformAssociateModel is preserved for future associate-model skinning semantics.",boneModelId:e,boneName:t,clusterMode:s}),l}function ke(e){if("number"==typeof e)return e}function De(e){if(e instanceof Int32Array)return e;if(e instanceof Float64Array){const t=new Int32Array(e.length);for(let n=0;n<e.length;n++)t[n]=Math.round(e[n]);return t}return null}function Ge(e){return e instanceof Float64Array?e:e instanceof Float32Array?new Float64Array(e):null}function Ve(e,t){var n;const s=null!==(n=function(e,t){if(0===e.length)return;const n=e.map(e=>He(e,t)),s=new Set(n[0]);for(const e of n.slice(1))for(const t of Array.from(s))e.includes(t)||s.delete(t);return n[0].find(e=>s.has(e))}(e,t))&&void 0!==n?n:e[0];let o=s,r=Ke(o,t);for(;void 0!==r;){const e=t.objects.get(r);if(!e||"Model"!==e.name||!Le(e))break;o=r,r=Ke(r,t)}return o}function He(e,t){const n=[];let s=e;for(;void 0!==s;){const e=t.objects.get(s);if(!e||"Model"!==e.name)break;n.push(s),s=Ke(s,t)}return n}function Ke(e,t){const n=t.connections.find(n=>{var s;return"OO"===n.type&&n.childId===e&&"Model"===(null===(s=t.objects.get(n.parentId))||void 0===s?void 0:s.name)});return null==n?void 0:n.parentId}function $e(e){var t,n,s;return null!==(s=null!==(n=null!==(t=e.find(e=>e.isCluster&&e.transformLinkMatrix))&&void 0!==t?t:e.find(e=>e.isCluster))&&void 0!==n?n:e.find(e=>e.modelBindPoseMatrix))&&void 0!==s?s:e[0]}function Ue(e,t,n){if(e.length!==t.length)return!1;for(let s=0;s<e.length;s++)if(Math.abs(e[s]-t[s])>n)return!1;return!0}function qe(e,t){var n;const s=t.objects.get(e);if(!s||"Model"!==s.name)return null;const o=Pe(s);return{modelId:e,name:Z(null!==(n=Q(s,1))&&void 0!==n?n:`Bone${e.toString()}`),index:-1,parentIndex:-1,isCluster:!1,translation:o.translation,rotation:o.rotation,preRotation:o.preRotation,postRotation:o.postRotation,rotationPivot:o.rotationPivot,scalingPivot:o.scalingPivot,rotationOffset:o.rotationOffset,scalingOffset:o.scalingOffset,scale:o.scale,rotationOrder:o.rotationOrder,inheritType:o.inheritType,clusterMode:"Unknown",bindPoseMatrix:null,transformLinkMatrix:null,transformAssociateModelMatrix:null,modelBindPoseMatrix:null,diagnostics:[]}}function We(e,t){return e<t?-1:e>t?1:0}function ze(e,t,n){var s,o;return(null!==(s=n.get(e))&&void 0!==s?s:Number.MAX_SAFE_INTEGER)-(null!==(o=n.get(t))&&void 0!==o?o:Number.MAX_SAFE_INTEGER)||We(e,t)}const je=46186158e3,Xe=1/23,Ye=1e-5,Qe=[24,25,30,48,50,60,100,120];function Ze(e,t,n){var s,o,r,i;const a=Z(null!==(s=Q(t,1))&&void 0!==s?s:"Animation"),l=function(e){var t,n,s,o;const r=X(e,"Properties70");if(!r)return null;let i=0,a=null;for(const e of r.children){if("P"!==e.name)continue;const r=Q(e,0);"LocalStart"===r||"ReferenceStart"===r?i=null!==(n=lt(null===(t=e.properties[4])||void 0===t?void 0:t.value))&&void 0!==n?n:i:"LocalStop"!==r&&"ReferenceStop"!==r||(a=null!==(o=lt(null===(s=e.properties[4])||void 0===s?void 0:s.value))&&void 0!==o?o:a)}return null!==a?{start:i,stop:a}:null}(t),u=J(n,e,"AnimationLayer");if(0===u.length)return null;const c=[],d=[],h=[],m=[];let f=1/0,p=0;for(const{id:e,node:t}of u){const s=Z(null!==(o=Q(t,1))&&void 0!==o?o:"Layer");let a=100,l=0;const u=X(t,"Properties70");if(u)for(const e of u.children){if("P"!==e.name)continue;const t=Q(e,0);if("Weight"===t){const t=null===(r=e.properties[4])||void 0===r?void 0:r.value;"number"==typeof t&&(a=t)}else if("BlendMode"===t){const t=null===(i=e.properties[4])||void 0===i?void 0:i.value;"number"==typeof t&&(l=t)}}const _=J(n,e,"AnimationCurveNode"),g=[],y=[],v=[];for(const{id:e,node:t}of _){const o=Je(e,t,n);if(!o){const o=et(e,t,n);if(o){tt(o.curves,e=>{e<f&&(f=e),e>p&&(p=e)}),y.push(o),d.push(o);const t={type:"unsupported-curve-node",message:`AnimationCurveNode '${o.type}' is preserved as diagnostic data but not evaluated at runtime.`,layerName:s,curveNodeId:e,curveNodeType:o.type,targetId:o.targetId,propertyName:o.propertyName};v.push(t),m.push(t)}continue}for(const e of o.curves)for(const t of e.keys)t.time<f&&(f=t.time),t.time>p&&(p=t.time);g.push(o),c.push(o)}h.push({name:s,weight:a,normalizedWeight:a/100,blendMode:l,curveNodes:g,unsupportedCurveNodes:y,diagnostics:v})}if(0===c.length&&0===d.length)return null;h.length>1&&m.push({type:"multiple-animation-layers",message:"Multiple animation layers are preserved, but runtime blending is not yet evaluated."});for(const e of h){if(0!==e.blendMode){const t={type:"unsupported-layer-blend-mode",message:`Animation layer blend mode ${e.blendMode} is preserved but not yet blended at runtime.`,layerName:e.name};e.diagnostics.push(t),m.push(t)}if(100!==e.weight){const t={type:"partial-layer-weight",message:`Animation layer weight ${e.weight} is preserved but not yet applied at runtime.`,layerName:e.name};e.diagnostics.push(t),m.push(t)}}const _=f>0&&isFinite(f)?f:0;if(_>0){for(const e of c)for(const t of e.curves)for(const e of t.keys)e.time-=_;for(const e of d)for(const t of e.curves)for(const e of t.keys)e.time-=_;p-=_}const g=l?Math.max(l.start-_,0):0,y=l?Math.max(l.stop-_,g):0,v=y>g,b=v?g:0,x=v?y:p;return{name:a,startTime:b,stopTime:x,duration:Math.max(x-b,0),curveNodes:c,layers:h,unsupportedCurveNodes:d,diagnostics:m}}function Je(e,t,n){var s;const o=Z(null!==(s=Q(t,1))&&void 0!==s?s:"");if("T"===o||"R"===o||"S"===o){const t=function(e,t){for(const n of t.connections)if(n.childId===e&&"OP"===n.type){const e=t.objects.get(n.parentId);if(e&&"Model"===e.name)return n.parentId}return null}(e,n);if(null===t)return null;const s=nt(e,n);return 0===s.length?null:{type:o,targetModelId:t,curves:s}}if("DeformPercent"===o){const t=function(e,t){for(const n of t.connections)if(n.childId===e&&"OP"===n.type){const e=t.objects.get(n.parentId);if(e&&"Deformer"===e.name&&"BlendShapeChannel"===Q(e,2))return n.parentId}for(const n of t.connections)if(n.childId===e&&"OO"===n.type){const e=t.objects.get(n.parentId);if(e&&"Deformer"===e.name&&"BlendShapeChannel"===Q(e,2))return n.parentId}return null}(e,n);if(null===t)return null;const s=nt(e,n);return 0===s.length?null:{type:"DeformPercent",targetModelId:t,curves:s}}return null}function et(e,t,n){var s;const o=Z(null!==(s=Q(t,1))&&void 0!==s?s:""),r=nt(e,n),i=function(e){var t,n;const s={},o=X(e,"Properties70");for(const e of null!==(t=null==o?void 0:o.children)&&void 0!==t?t:[]){if("P"!==e.name)continue;const t=Q(e,0);if(!(null==t?void 0:t.startsWith("d|")))continue;const o=ut(null===(n=e.properties[4])||void 0===n?void 0:n.value);null!==o&&(s[t]=o)}return s}(t);if(0===r.length&&0===Object.keys(i).length)return null;let a,l=null;for(const t of n.connections)if(t.childId===e&&"OP"===t.type){l=t.parentId,a=t.propertyName;break}return{type:o,id:e,targetId:l,propertyName:a,curveCount:r.length,curves:r,defaultValues:i}}function tt(e,t){for(const n of e)for(const e of n.keys)t(e.time)}function nt(e,t){var n;const s=[];for(const o of t.connections)if(o.parentId===e&&"OP"===o.type){const e=t.objects.get(o.childId);if(!e||"AnimationCurve"!==e.name)continue;const r=null!==(n=o.propertyName)&&void 0!==n?n:"d|X",i=st(e);if(i.length>0){const t=ot(e,i);s.push({channel:r,keys:t?rt(i):i,isSampled:t})}}if(0===s.length){const n=J(t,e,"AnimationCurve"),o=["d|X","d|Y","d|Z"];for(let e=0;e<n.length&&e<3;e++){const t=st(n[e].node);if(t.length>0){const r=ot(n[e].node,t);s.push({channel:o[e],keys:r?rt(t):t,isSampled:r})}}}return s}function st(e){var t,n,s,o,r,i,a,l,u;const c=X(e,"KeyTime"),d=X(e,"KeyValueFloat");if(!c||!d)return[];const h=(g=null===(t=c.properties[0])||void 0===t?void 0:t.value)instanceof Float64Array?g:null,m=ct(null===(n=d.properties[0])||void 0===n?void 0:n.value),f=at(null===(o=null===(s=X(e,"KeyAttrFlags"))||void 0===s?void 0:s.properties[0])||void 0===o?void 0:o.value),p=ct(null===(i=null===(r=X(e,"KeyAttrDataFloat"))||void 0===r?void 0:r.properties[0])||void 0===i?void 0:i.value),_=at(null===(l=null===(a=X(e,"KeyAttrRefCount"))||void 0===a?void 0:a.properties[0])||void 0===l?void 0:l.value);var g;if(!h||!m)return[];if(h.length!==m.length)return[];const y=function(e,t,n){if(!t||0===t.length)return new Array(e).fill(-1);if(n&&n.length>0){let t=0;for(const e of n)t+=e;if(t===e){const e=[];for(let t=0;t<n.length;t++){const s=n[t];for(let n=0;n<s;n++)e.push(t)}return e}}return t.length===e?Array.from({length:e},(e,t)=>t):1===t.length?new Array(e).fill(0):Array.from({length:e},(e,n)=>Math.min(n,t.length-1))}(h.length,f,_),v=[];for(let e=0;e<h.length;e++){const t=y[e],n=t>=0&&null!==(u=null==f?void 0:f[t])&&void 0!==u?u:0,s=4*t;v.push({time:Number(h[e])/je,value:m[e],interpolation:dt(n),constantMode:256&n?"next":"standard",rightSlope:ht(p,s),nextLeftSlope:ht(p,s+1)})}return v}function ot(e,t){var n;return"FbxMayaSample Curve"===Z(null!==(n=Q(e,1))&&void 0!==n?n:"")||function(e){if(e.length<8)return!1;const t=[];for(let n=1;n<e.length;n++){const s=e[n].time-e[n-1].time;if(!(s>0))return!1;t.push(s)}const n=t.reduce((e,t)=>e+t,0)/t.length;if(n>Xe)return!1;const s=Math.max(1e-6,.05*n);if(t.some(e=>Math.abs(e-n)>s))return!1;const o=1/n;return!!Qe.some(e=>Math.abs(o-e)<=Math.max(.25,.02*e))&&!function(e){let t=!1,n=!0,s=!0,o=Number.POSITIVE_INFINITY,r=Number.NEGATIVE_INFINITY,i=0;for(const t of e)o=Math.min(o,t.value),r=Math.max(r,t.value);for(let o=0;o<e.length-1;o++){const r=e[o],a=e[o+1];if("cubic"!==r.interpolation)continue;t=!0;const l=a.time-r.time;if(!(l>0))continue;const u=(a.value-r.value)/l,c=r.rightSlope,d=r.nextLeftSlope;if(void 0!==c&&void 0!==d){(Math.abs(c)>Ye||Math.abs(d)>Ye)&&(s=!1);for(const e of[.25,.5,.75]){const t=mt(r.value,a.value,c,d,l,e),n=r.value+e*l*u;i=Math.max(i,Math.abs(t-n))}}else n=!1}if(!t||!n||s)return!1;const a=r-o;return i>Math.max(1e-4,.01*a)}(e)}(t)}function rt(e){return e.map(e=>({time:e.time,value:e.value,interpolation:"linear"}))}function it(e,t){var n,s;if(!e||0===e.keys.length)return null;const o=e.keys;if(t<=o[0].time)return o[0].value;if(t>=o[o.length-1].time)return o[o.length-1].value;for(let r=0;r<o.length-1;r++){const i=o[r],a=o[r+1];if(t<i.time||t>a.time)continue;if(a.time===i.time)return i.value;if("constant"===i.interpolation)return"next"===i.constantMode?a.value:i.value;const l=a.time-i.time,u=(t-i.time)/l;if("cubic"===i.interpolation&&!e.isSampled){const e=(a.value-i.value)/l,t=null!==(n=i.rightSlope)&&void 0!==n?n:e,o=null!==(s=i.nextLeftSlope)&&void 0!==s?s:e;return mt(i.value,a.value,t,o,l,u)}return i.value+u*(a.value-i.value)}return o[o.length-1].value}function at(e){if(e instanceof Int32Array)return e;if(e instanceof Float32Array||e instanceof Float64Array){const t=new Int32Array(e.length);for(let n=0;n<e.length;n++)t[n]=e[n];return t}return null}function lt(e){return"number"==typeof e?e/je:null}function ut(e){return"number"==typeof e?e:null}function ct(e){if(e instanceof Float32Array)return e;if(e instanceof Float64Array){const t=new Float32Array(e.length);for(let n=0;n<e.length;n++)t[n]=e[n];return t}return null}function dt(e){return 8&e?"cubic":4&e?"linear":2&e?"constant":"linear"}function ht(e,t){if(!e||t<0||t>=e.length)return;const n=e[t];return Number.isFinite(n)?n:void 0}function mt(e,t,n,s,o,r){const i=r*r,a=i*r;return(2*a-3*i+1)*e+(a-2*i+r)*o*n+(-2*a+3*i)*t+(a-i)*o*s}function ft(e,t,n){var s,o;const r=n.parentOf.get(e);if(!r)return null;const i=n.objects.get(r.id);if(!i||"Geometry"!==i.name)return null;const a=r.id,l=[],u=J(n,e,"Deformer");for(const{id:e,node:t}of u){if("BlendShapeChannel"!==Q(t,2))continue;const r=Z(null!==(s=Q(t,1))&&void 0!==s?s:"MorphTarget");let i=0;const a=X(t,"Properties70");if(a)for(const e of a.children)if("P"===e.name&&"DeformPercent"===Q(e,0)){const t=null===(o=e.properties[4])||void 0===o?void 0:o.value;"number"==typeof t&&(i=t)}const u=pt(t),c=[],d=J(n,e,"Geometry");for(const{node:e}of d){if("Shape"!==Q(e,2))continue;const t=yt(e);t&&c.push(t)}if(c.length>0){const t=[],n=_t(u,c,e,r,t);l.push({name:r,id:e,deformPercent:i,shapes:gt(c,n),fullWeights:n?[...n].sort((e,t)=>e-t):null,diagnostics:t})}}return 0===l.length?null:{id:e,geometryId:a,channels:l}}function pt(e){var t;const n=X(e,"FullWeights"),s=null===(t=null==n?void 0:n.properties[0])||void 0===t?void 0:t.value;return s&&(s instanceof Float64Array||s instanceof Float32Array||s instanceof Int32Array)?Array.from(s,e=>Number(e)):null}function _t(e,t,n,s,o){return e?e.length!==t.length?(1===t.length||o.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:s}),null):e:(t.length>1&&o.push({type:"missing-full-weights",message:"Blend shape channel has multiple shapes but no FullWeights; using the first shape for compatibility.",channelId:n,channelName:s}),null)}function gt(e,t){return t&&t.length===e.length?e.map((e,n)=>({shape:e,weight:t[n]})).sort((e,t)=>e.weight-t.weight).map(e=>e.shape):e.length>1?[e[0]]:e}function yt(e){var t,n,s;const o=X(e,"Indexes"),r=X(e,"Vertices");if(!o||!r)return null;const i=null===(t=o.properties[0])||void 0===t?void 0:t.value,a=null===(n=r.properties[0])||void 0===n?void 0:n.value;if(!i||!a)return null;const l=function(e){if(e instanceof Uint32Array)return e;if(e instanceof Int32Array||e instanceof Float32Array||e instanceof Float64Array){const t=new Uint32Array(e.length);for(let n=0;n<e.length;n++)t[n]=e[n];return t}return null}(i);if(!l)return null;let u;if(a instanceof Float64Array)u=a;else{if(!(a instanceof Float32Array))return null;u=new Float64Array(a)}let c=null;const d=X(e,"Normals");if(d){const e=null===(s=d.properties[0])||void 0===s?void 0:s.value;e instanceof Float64Array?c=e:e instanceof Float32Array&&(c=new Float64Array(e))}return{indices:l,vertices:u,normals:c}}const vt=new Set(["Character","CharacterPose","ControlSet","ControlSetPlug","SelectionSet","CollectionExclusive"]);function bt(e){return"Skin"===e||"Cluster"===e||"BlendShape"===e||"BlendShapeChannel"===e}function xt(e,t,n,s,o){var r,i,a,l;return{type:s,message:o,objectId:t,objectName:Z(null!==(r=Q(n,1))&&void 0!==r?r:n.name),nodeName:n.name,subType:null!==(i=Q(n,2))&&void 0!==i?i:"",parentCount:e.connections.filter(e=>e.childId===t).length,childCount:null!==(l=null===(a=e.childrenOf.get(t))||void 0===a?void 0:a.length)&&void 0!==l?l:0}}function Tt(e){const t=function(e){var t,n;const s=new Map,o=[],r=new Map,i=new Map,a=[],l=[],u=[],c=new Map,d=new Map;let h=-1;const m=e=>{let t=c.get(e);return void 0===t&&(t=h--,c.set(e,t)),t},f=(e,t)=>{let n=d.get(e);n||(n=new Map,d.set(e,n));let s=n.get(t);return void 0===s&&(s=h--,n.set(t,s)),s},p=Y(e,"Objects");if(p)for(const e of p.children){const t=e.properties[0];if(t){const n=ee(t.value);if(void 0!==n)s.set(n,e),o.push({id:n,node:e,source:"Objects",synthetic:!1});else if("string"==typeof t.value){const n=Z(t.value),l=m(n),c=se(e,l);if(s.set(l,c),o.push({id:l,node:c,source:"Objects",legacyName:n,synthetic:!1}),"Model"===e.name&&"Mesh"===Q(e,1)){const t=f("Geometry",n),c=oe(e,t);s.set(t,c),o.push({id:t,node:c,source:"legacySyntheticGeometry",legacyName:n,synthetic:!0}),ne(a,r,i,u,"OO",t,l)}}}}const _=Y(e,"Connections");if(_)for(const e of _.children){if("C"!==e.name&&"Connect"!==e.name)continue;const o=l.length,d=Q(e,0),h=null===(t=e.properties[1])||void 0===t?void 0:t.value,m=null===(n=e.properties[2])||void 0===n?void 0:n.value,f={source:e.name,rawType:d,accepted:!1};if(l.push(f),"OO"!==d&&"OP"!==d){const e=void 0===h?void 0:te(h,c),t=void 0===m?void 0:te(m,c);u.push({reason:"unsupported-connection-type",message:`Unsupported FBX connection type '${null!=d?d:""}' was not added to the graph.`,connectionIndex:o,type:d,childId:e,parentId:t});continue}if(void 0===h||void 0===m){u.push({reason:"missing-connection-endpoint",message:"FBX connection is missing a child or parent endpoint.",connectionIndex:o,type:d});continue}const p=te(h,c),_=te(m,c);if(void 0===p||void 0===_){u.push({reason:"unresolved-legacy-endpoint",message:"FBX connection references a legacy string endpoint that is not present in the object table.",connectionIndex:o,type:d});continue}const g="OP"===d&&e.properties.length>3?Q(e,3):void 0;f.childId=p,f.parentId=_,f.propertyName=g,p===_&&u.push({reason:"self-loop",message:"FBX connection references the same object as child and parent.",connectionIndex:o,type:d,childId:p,parentId:_,propertyName:g}),s.has(p)||u.push({reason:"unresolved-object-reference",message:"FBX connection child ID is not present in the object table.",connectionIndex:o,type:d,childId:p,parentId:_,propertyName:g}),0===_||s.has(_)||u.push({reason:"unresolved-object-reference",message:"FBX connection parent ID is not present in the object table.",connectionIndex:o,type:d,childId:p,parentId:_,propertyName:g}),ne(a,r,i,u,d,p,_,g,o),f.accepted=!0}return{objects:s,objectEntries:o,childrenOf:r,parentOf:i,connections:a,connectionEntries:l,diagnostics:u}}(e),n=function(e){const t=new Map,n=Y(e,"Definitions");if(!n)return t;for(const e of n.children){if("ObjectType"!==e.name)continue;const n=Q(e,0);if(n)for(const s of e.children){if("PropertyTemplate"!==s.name)continue;const e=Q(s,0);if(!e)continue;const o=Ae(n,e,s);let r=t.get(n);r||(r=new Map,t.set(n,r)),r.set(e,o)}}return t}(e),s=function(e){var t;const n={upAxis:1,upAxisSign:1,frontAxis:2,frontAxisSign:1,coordAxis:0,coordAxisSign:1,unitScaleFactor:1},s=Y(e,"GlobalSettings");if(!s)return n;const o=s.children.find(e=>"Properties70"===e.name);if(!o)return n;for(const e of o.children){if("P"!==e.name)continue;const s=Q(e,0),o=Rt(null===(t=e.properties[4])||void 0===t?void 0:t.value);if(s&&void 0!==o)switch(s){case"UpAxis":n.upAxis=o;break;case"UpAxisSign":n.upAxisSign=o;break;case"FrontAxis":n.frontAxis=o;break;case"FrontAxisSign":n.frontAxisSign=o;break;case"CoordAxis":n.coordAxis=o;break;case"CoordAxisSign":n.coordAxisSign=o;break;case"UnitScaleFactor":n.unitScaleFactor=o}}return n}(e),o=[];for(const[e,s]of Array.from(t.objects))"Material"===s.name&&o.push(we(s,e,t,n));const r=[];for(const[e,n]of Array.from(t.objects))"Geometry"===n.name&&"Mesh"===Q(n,2)&&r.push(re(n,e));const i=function(e){const t=[];for(const[n,s]of Array.from(e.objects))if("Deformer"===s.name&&"Skin"===Q(s,2)){const s=Ee(n,0,e);s&&t.push(s)}return t}(t),a=function(e,t){if(0===t.length)return[];const n=new Map;for(const s of t){const t=s.bones.filter(e=>e.isCluster).map(e=>e.modelId);if(0===t.length)continue;const o=Ve(t,e),r=n.get(o);r?r.push(s):n.set(o,[s])}return Array.from(n.entries()).sort(([e],[t])=>We(e,t)).map(([t,n])=>function(e,t,n){var s,o;const r=new Set,i=new Set,a=new Map,l=new Map;for(const e of t)for(const t of e.bones){l.has(t.modelId)||l.set(t.modelId,l.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(const e of He(t.modelId,n))i.add(e)}}const u=function(e){const t=[];for(const[n,s]of Array.from(e)){const e=s.filter(e=>e.isCluster&&e.transformLinkMatrix).map(e=>e.transformLinkMatrix);if(e.length<2)continue;const o=e[0];e.some(e=>!Ue(o,e,1e-5))&&t.push(`Model ${n.toString()} has differing Cluster.TransformLink matrices across skins`)}return t}(a),c=new Map;for(const[e,t]of Array.from(a))c.set(e,$e(t));const d=function(e,t){const n=new Map;for(const s of Array.from(e)){const o=Ke(s,t);void 0!==o&&e.has(o)&&n.set(s,o)}return n}(i,n),h=function(e,t,n){var s;const o=new Map;for(const n of Array.from(e)){const e=t.get(n);if(void 0===e)continue;let s=o.get(e);s||(s=[],o.set(e,s)),s.push(n)}for(const e of Array.from(o.values()))e.sort((e,t)=>ze(e,t,n));const r=[],i=[...Array.from(e).filter(e=>!t.has(e)).sort((e,t)=>ze(e,t,n))];for(;i.length>0;){const e=i.shift();r.push(e),i.push(...null!==(s=o.get(e))&&void 0!==s?s:[])}return r}(i,d,l),m=[],f=new Map;for(const e of h){const t=null!==(s=c.get(e))&&void 0!==s?s:qe(e,n);if(!t)continue;const i=d.get(e),a=void 0===i?-1:null!==(o=f.get(i))&&void 0!==o?o:-1,l=m.length,u=Object.assign(Object.assign({},t),{index:l,parentIndex:a,isCluster:r.has(e)});m.push(u),f.set(e,l)}const p=t.map(t=>function(e,t,n){const s=e.bones.map(e=>{const s=n.get(e.modelId);if(void 0===s&&e.isCluster)throw new Error(`FBX rig resolver: cluster bone ${e.name} is missing from resolved rig ${t}`);return null!=s?s:-1});return{skinId:e.id,geometryId:e.geometryId,rigId:t,skinBoneIndexToRigBoneIndex:s,clusterModelIds:new Set(e.bones.filter(e=>e.isCluster).map(e=>e.modelId))}}(t,`rig_${e.toString()}`,f));return{id:`rig_${e.toString()}`,rootModelIds:m.filter(e=>e.parentIndex<0).map(e=>e.modelId),bones:m,modelIdToBoneIndex:f,clusterModelIds:r,skinBindings:p,warnings:u}}(t,n,e))}(t,i),l=function(e){const t=[];for(const[n,s]of Array.from(e.objects))if("Deformer"===s.name&&"BlendShape"===Q(s,2)){const s=ft(n,0,e);s&&t.push(s)}return t}(t),u=function(e){const t=[];for(const[n,s]of Array.from(e.objects))if("AnimationStack"===s.name){const o=Ze(n,s,e);o&&t.push(o)}return t}(t),c=function(e,t){var n,s,o,r;const i=[],a=null!==(n=ge(t,"NodeAttribute","FbxCamera"))&&void 0!==n?n:ge(t,"NodeAttribute");for(const[t,n]of Array.from(e.objects)){if("NodeAttribute"!==n.name)continue;if("Camera"!==Q(n,2))continue;const l=e.parentOf.get(t);if(!l)continue;const u=e.objects.get(l.id);if(!u||"Model"!==u.name)continue;const c=Z(null!==(s=Q(u,1))&&void 0!==s?s:"Camera"),d=ve(n,a,"NearPlane",.1),h=ve(n,a,"FarPlane",1e4),m=Ot(n,a),f=1===ve(n,a,"CameraProjectionType",0)||1===ve(n,a,"ProjectionType",0)?"orthographic":"perspective",p=Rt(ye(n,a,"FocalLength")),_=null!==(o=Rt(ye(n,a,"FilmWidth")))&&void 0!==o?o:Rt(ye(n,a,"ApertureWidth")),g=null!==(r=Rt(ye(n,a,"FilmHeight")))&&void 0!==r?r:Rt(ye(n,a,"ApertureHeight")),y=Rt(ye(n,a,"OrthoZoom")),v=Rt(ye(n,a,"Roll")),b=Ft(n,a,m,p,g),x=[];"orthographic"===f&&void 0===y&&x.push("Orthographic camera has no OrthoZoom; runtime orthographic bounds use a fallback."),void 0!==p&&void 0===g&&void 0===ye(n,a,"FieldOfView")&&x.push("FocalLength is present without FilmHeight; default field of view fallback may be used."),i.push({modelId:l.id,name:c,fieldOfView:b,nearPlane:d,farPlane:h,aspectRatio:m,projectionType:f,focalLength:p,filmWidth:_,filmHeight:g,orthoZoom:y,roll:v,unknownProperties:Et(n,wt),diagnostics:x})}return i}(t,n),d=function(e,t){var n,s,o,r,i;const a=[],l=null!==(n=ge(t,"NodeAttribute","FbxLight"))&&void 0!==n?n:ge(t,"NodeAttribute");for(const[t,n]of Array.from(e.objects)){if("NodeAttribute"!==n.name)continue;if("Light"!==Q(n,2))continue;const u=e.parentOf.get(t);if(!u)continue;const c=e.objects.get(u.id);if(!c||"Model"!==c.name)continue;const d=Z(null!==(s=Q(c,1))&&void 0!==s?s:"Light"),h=ve(n,l,"LightType",0),m=be(n,l,"Color",[1,1,1]),f=ve(n,l,"Intensity",100)/100,p=null!==(o=Rt(ye(n,l,"OuterAngle")))&&void 0!==o?o:Rt(ye(n,l,"ConeAngle")),_=Rt(ye(n,l,"InnerAngle")),g=null!=p?p:45,y=ve(n,l,"DecayType",2),v=Rt(ye(n,l,"DecayStart")),b=St(ye(n,l,"EnableNearAttenuation")),x=St(ye(n,l,"EnableFarAttenuation")),T=null!==(i=null!==(r=St(ye(n,l,"CastShadow")))&&void 0!==r?r:St(ye(c,void 0,"CastShadow")))&&void 0!==i?i:St(ye(c,void 0,"Shadow")),A=[];2!==y&&A.push(`DecayType ${y} is preserved as metadata; Babylon falloff is not remapped in this pass.`),void 0!==v&&A.push("DecayStart is preserved as metadata and is not mapped to Babylon light range."),a.push({modelId:u.id,name:d,lightType:h,color:m,intensity:f,coneAngle:g,decayType:y,innerAngle:_,outerAngle:p,decayStart:v,enableNearAttenuation:b,enableFarAttenuation:x,castShadows:T,unknownProperties:Et(n,Ct),diagnostics:A})}return a}(t,n),h=function(e){var t,n;const s=e.diagnostics.map(t=>({type:"connection-graph",message:t.message,objectId:t.childId,subType:t.reason,parentCount:void 0===t.childId?void 0:e.connections.filter(e=>e.childId===t.childId).length}));for(const[o,r]of Array.from(e.objects)){const i=null!==(t=Q(r,2))&&void 0!==t?t:"";"Constraint"!==r.name?vt.has(r.name)?s.push(xt(e,o,r,"unsupported-helper",`${r.name} helper data is preserved as diagnostic data but not evaluated at runtime.`)):"LayeredTexture"!==r.name?"Pose"!==r.name||"BindPose"===i?"Deformer"!==r.name||bt(i)?"NodeAttribute"===r.name&&i&&"Camera"!==i&&"Light"!==i&&s.push(xt(e,o,r,"unsupported-node-attribute",`NodeAttribute subtype '${i}' is preserved as diagnostic data but not converted to a Babylon object.`)):s.push(xt(e,o,r,"unsupported-deformer",`Deformer subtype '${i}' is preserved as diagnostic data but not evaluated at runtime.`)):s.push(xt(e,o,r,"unsupported-pose",`Pose subtype '${i}' is preserved as diagnostic data but not evaluated at runtime.`)):s.push(xt(e,o,r,"unsupported-layered-texture","LayeredTexture is preserved as diagnostic data; runtime texture layer blending is not implemented.")):s.push(xt(e,o,r,"unsupported-constraint",`Constraint '${i||Z(null!==(n=Q(r,1))&&void 0!==n?n:"")}' is preserved as diagnostic data but not evaluated at runtime.`))}return s}(t),m=function(e,t,n,s){var o;const r=new Map;for(const e of t)r.set(e.id,e);const i=new Map;for(const e of n)i.set(e.id,e);const a=null!==(o=e.childrenOf.get(0))&&void 0!==o?o:[],l=[];for(const{id:t}of a){const n=e.objects.get(t);n&&"Model"===n.name&&l.push(At(t,n,e,r,i,s))}return l}(t,r,o,n);return Object.assign({rootModels:m,geometries:r,materials:o,skins:i,rigs:a,blendShapes:l,animations:u,cameras:c,lights:d,diagnostics:h},s)}function At(e,t,n,s,o,r){var i,a,l;const u=Z(null!==(i=Q(t,1))&&void 0!==i?i:"Model"),c=null!==(a=Q(t,2))&&void 0!==a?a:"Null",d=J(n,e,"Geometry"),h=d.length>0?s.get(d[0].id):void 0,m=J(n,e,"Material"),f=[];for(const{id:e}of m){const t=o.get(e);t&&f.push(t)}const p=function(e,t){const n=be(e,t,"Lcl Translation",[0,0,0]),s=be(e,t,"Lcl Rotation",[0,0,0]),o=be(e,t,"Lcl Scaling",[1,1,1]),r=be(e,t,"PreRotation",[0,0,0]),i=be(e,t,"PostRotation",[0,0,0]),a=be(e,t,"RotationPivot",[0,0,0]),l=be(e,t,"ScalingPivot",[0,0,0]),u=be(e,t,"RotationOffset",[0,0,0]),c=be(e,t,"ScalingOffset",[0,0,0]),d=be(e,t,"GeometricTranslation",[0,0,0]),h=be(e,t,"GeometricRotation",[0,0,0]),m=be(e,t,"GeometricScaling",[1,1,1]),f=ve(e,t,"RotationOrder",0),p=ve(e,t,"InheritType",1);return{translation:n,rotation:s,scale:o,preRotation:r,postRotation:i,rotationPivot:a,scalingPivot:l,rotationOffset:u,scalingOffset:c,geometricTranslation:d,geometricRotation:h,geometricScaling:m,rotationOrder:f,inheritType:p,diagnostics:1!==p&&2!==p?[`InheritType ${p} is parsed and preserved; runtime parent-scale inheritance remains gated to avoid changing existing visual behavior without a fixture-specific baseline.`]:[]}}(t,null!==(l=ge(r,"Model","FbxNode"))&&void 0!==l?l:ge(r,"Model")),_=J(n,e,"Model"),g=[];for(const{id:e,node:t}of _)g.push(At(e,t,n,s,o,r));const y=t.children.find(e=>"Culling"===e.name),v=!!y&&"CullingOff"===Q(y,0),b=function(e){var t;const n=X(e,"Properties70");if(!n)return;const s={};let o=!1;for(const e of n.children){if("P"!==e.name)continue;const n=Q(e,0);if(!n||Mt.has(n))continue;const r=null===(t=e.properties[4])||void 0===t?void 0:t.value;void 0!==r&&("string"==typeof r||"number"==typeof r||"boolean"==typeof r)&&(s[n]=r,o=!0)}return o?s:void 0}(t);return Object.assign({id:e,name:u,subType:c,geometry:h,materials:f,children:g,cullingOff:v,customProperties:b},p)}const Mt=new Set(["Lcl Translation","Lcl Rotation","Lcl Scaling","PreRotation","PostRotation","RotationPivot","ScalingPivot","RotationOffset","ScalingOffset","RotationOrder","GeometricTranslation","GeometricRotation","GeometricScaling","Visibility","InheritType","ScalingMax","DefaultAttributeIndex","currentUVSet","lockInfluenceWeights"]),wt=new Set(["FieldOfView","FieldOfViewX","FieldOfViewY","NearPlane","FarPlane","AspectWidth","AspectHeight","FilmAspectRatio","FocalLength","FilmWidth","FilmHeight","ApertureWidth","ApertureHeight","CameraProjectionType","ProjectionType","OrthoZoom","Roll","ApertureMode"]),Ct=new Set(["LightType","Color","Intensity","InnerAngle","OuterAngle","ConeAngle","DecayType","DecayStart","EnableNearAttenuation","EnableFarAttenuation","CastShadow","Shadow"]);function Rt(e){if("number"==typeof e)return e}function St(e){return"boolean"==typeof e?e:"number"==typeof e?0!==e:void 0}function Ot(e,t){const n=Rt(ye(e,t,"FilmAspectRatio"));if(void 0!==n&&n>0)return n;const s=Rt(ye(e,t,"AspectWidth")),o=Rt(ye(e,t,"AspectHeight"));return void 0!==s&&void 0!==o&&s>0&&o>0?s/o:0}function Ft(e,t,n,s,o){var r;const i=null!==(r=Rt(ye(e,t,"FieldOfViewY")))&&void 0!==r?r:Rt(ye(e,t,"FieldOfView"));if(void 0!==i)return i;const a=Rt(ye(e,t,"FieldOfViewX"));return void 0!==a?n>0?It(2*Math.atan(Math.tan(a*Math.PI/180/2)/n)):a:void 0!==s&&s>0&&void 0!==o&&o>0?It(2*Math.atan(25.4*o/(2*s))):45}function Et(e,t){var n;const s=new Set;for(const o of["Properties70","Properties60"]){const r=X(e,o);for(const e of null!==(n=null==r?void 0:r.children)&&void 0!==n?n:[]){if("P"!==e.name&&"Property"!==e.name)continue;const n=Q(e,0);n&&!t.has(n)&&s.add(n)}}return Array.from(s).sort()}function It(e){return 180*e/Math.PI}function Lt(e,n,s){const o=t.Matrix.RotationX(e),r=t.Matrix.RotationY(n),i=t.Matrix.RotationZ(s);return o.multiply(r).multiply(i)}function Pt(e,n,s,o){const r=t.Matrix.RotationX(e),i=t.Matrix.RotationY(n),a=t.Matrix.RotationZ(s);switch(o){case 0:default:return r.multiply(i).multiply(a);case 1:return r.multiply(a).multiply(i);case 2:return i.multiply(a).multiply(r);case 3:return i.multiply(r).multiply(a);case 4:return a.multiply(r).multiply(i);case 5:return a.multiply(i).multiply(r)}}function Bt(e,n){const s=Math.PI/180,o=t.Matrix.Scaling(n[0],n[1],n[2]),r=Lt(e[0]*s,e[1]*s,e[2]*s);return o.multiply(r)}const Nt={name:"fbx",extensions:{".fbx":{isBinary:!0}}};class kt{constructor(e={}){var t;this.name=Nt.name,this.extensions=Nt.extensions,this._bindRestBones=new WeakSet,this._sourceBonesBySkeleton=new WeakMap,this._scaleCompensationHelpersBySkeleton=new WeakMap,this._options={normalMapCoordinateSystem:null!==(t=e.normalMapCoordinateSystem)&&void 0!==t?t:"y-up"}}createPlugin(e){return new kt(e[Nt.name])}importMeshAsync(e,t,n,s,o,r){return b(this,void 0,void 0,function*(){const o=Tt(this._parse(n));return this._buildScene(o,t,s,e)})}loadAsync(e,t,n,s,o){return b(this,void 0,void 0,function*(){const s=Tt(this._parse(t));this._buildScene(s,e,n,null)})}loadAssetContainerAsync(e,n,s,o,r){return b(this,void 0,void 0,function*(){const o=Tt(this._parse(n)),r=new t.AssetContainer(e),i=this._buildScene(o,e,s,null);for(const e of i.meshes)r.meshes.push(e);for(const e of i.skeletons)r.skeletons.push(e);for(const e of i.animationGroups)r.animationGroups.push(e);for(const e of i.transformNodes)r.transformNodes.push(e);for(const e of i.lights)r.lights.push(e);for(const e of i.cameras)r.cameras.push(e);for(const e of i.materials)this._addMaterialToContainer(e,r);for(const e of i.textures)this._addTextureToContainer(e,r);for(const e of i.meshes)this._addMaterialToContainer(e.material,r);return this._setAssetContainer(r),r.removeAllFromScene(),r})}_parse(e){if(e instanceof ArrayBuffer)return this._parseFromArrayBuffer(e);if(ArrayBuffer.isView(e)){const t=e,n=t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength);return this._parseFromArrayBuffer(n)}if("string"==typeof e)return $(e);throw new Error("FBXFileLoader: unsupported data type")}_parseFromArrayBuffer(e){const t=new Uint8Array(e,0,Math.min(21,e.byteLength));if(String.fromCharCode(...t).startsWith("Kaydara FBX Binary"))return function(e){const t=new DataView(e),n=new Uint8Array(e);if("Kaydara FBX Binary \0"!==K(n,0,21))throw new Error("Not a valid binary FBX file");if(e.byteLength<27)throw new Error("Truncated binary FBX header");const s=t.getUint32(23,!0),o=s>=7500,r=[];let i=27;for(;i<e.byteLength;){const s=N(t,n,i,o,e.byteLength);if(null===s)break;r.push(s.node),i=s.endOffset}return{version:s,nodes:r}}(e);const n=new TextDecoder("utf-8").decode(e);if(n.trimStart().startsWith("; FBX"))return $(n);throw new Error("FBXFileLoader: unrecognized FBX format")}_buildScene(e,n,s,o){var r;const i=this._buildNameFilter(o),a=new Map;for(const t of e.materials){const e=this._createMaterial(t,n,s);a.set(t.id,e)}const l=[],u=new Map,c=new Map,d=new Map,h=new Map,m=new Map;for(const t of e.skins)m.set(t.id,t);for(const t of e.rigs){const e=this._createSkeleton(t.id,t.bones,n);l.push(e),u.set(t.id,e);for(const n of t.skinBindings){const t=m.get(n.skinId);t&&(c.set(n.geometryId,e),d.set(n.geometryId,t),h.set(n.geometryId,n))}}const f=new Map,p=e=>{for(const t of e)f.set(t.id,t),p(t.children)};p(e.rootModels);const _=kt._collectCullingConflictMaterialIds(e.rootModels),g=new Map,y=new t.TransformNode("__fbx_root__",n);n.useRightHandedSystem||(y.rotation.y=Math.PI,y.scaling.z=-1);const v=[],b=[y];let x=y;const T=kt._computeFBXAxisConversionMatrix(e);T.equals(t.Matrix.Identity())||(x=new t.TransformNode("__fbx_axis_conversion__",n),x.parent=y,kt._applyMatrixToTransform(x,T),b.push(x));const A=new Map,M=t.Matrix.Identity();for(const t of e.rootModels)this._buildModel(t,n,x,x,M,a,i,v,b,c,d,h,A,_,g);this._linkSkeletonsToTransformNodes(e.rigs,u,A,b,n);for(const n of e.rigs){const e=u.get(n.id);if(!e)continue;const s=null!==(r=v.find(t=>t.skeleton===e))&&void 0!==r?r:null,o=null!=s?s:y,i=new Set;for(const t of e.bones){const e=t.getTransformNode();e&&i.add(e)}for(const r of n.bones){if(!r.isCluster)continue;const n=A.get(r.modelId),a=this._getSourceBone(e,r.index);if(n&&a)for(const r of[...n.getChildren()]){const n=r;if(!i.has(n)){const r=n.computeWorldMatrix(!0).clone(),i=kt._getBoneReferenceWorldMatrix(e,a,o,s),l=new t.Matrix;i.invertToRef(l);const u=r.multiply(l);n.parent=null,n.attachToBone(a,o),kt._applyMatrixToTransform(n,u)}}}}e.blendShapes.length>0&&this._applyBlendShapes(e.blendShapes,v,n);const w=[];for(const t of e.animations){const s=this._createAnimationGroup(t,e.rigs,u,n,A,f,v);s&&w.push(s)}const C=[];for(const t of e.cameras){const e=this._createCamera(t,A,n);e&&C.push(e)}const R=[];for(const t of e.lights){const e=this._createLight(t,A,n);e&&R.push(e)}return{meshes:v,particleSystems:[],skeletons:l,animationGroups:w,transformNodes:b,geometries:[],lights:R,spriteManagers:[],materials:Array.from(a.values()),textures:Array.from(new Set(Array.from(a.values()).flatMap(e=>e.getActiveTextures()))),cameras:C}}_addMaterialToContainer(e,n){if(e){if(e instanceof t.MultiMaterial){n.multiMaterials.includes(e)||n.multiMaterials.push(e);for(const t of e.subMaterials)this._addMaterialToContainer(t,n)}else n.materials.includes(e)||n.materials.push(e);for(const t of e.getActiveTextures())this._addTextureToContainer(t,n)}}_addTextureToContainer(e,t){t.textures.includes(e)||t.textures.push(e)}_setAssetContainer(e){for(const t of e.meshes)t._parentContainer=e;for(const t of e.transformNodes)t._parentContainer=e;for(const t of e.skeletons)t._parentContainer=e;for(const t of e.animationGroups)t._parentContainer=e;for(const t of e.lights)t._parentContainer=e;for(const t of e.cameras)t._parentContainer=e;for(const t of e.materials)t._parentContainer=e;for(const t of e.multiMaterials)t._parentContainer=e;for(const t of e.textures)t._parentContainer=e}static _computeFBXAxisConversionMatrix(e){const n=[[0,0,0],[0,0,0],[0,0,0]],s=(e,t,s)=>{if(e<0||e>2)return;const o=[0,0,0];o[s]=t>=0?1:-1,n[e]=o};return s(e.coordAxis,e.coordAxisSign,0),s(e.upAxis,e.upAxisSign,1),s(e.frontAxis,e.frontAxisSign,2),n.some(e=>e.every(e=>0===e))?t.Matrix.Identity():t.Matrix.FromValues(n[0][0],n[0][1],n[0][2],0,n[1][0],n[1][1],n[1][2],0,n[2][0],n[2][1],n[2][2],0,0,0,0,1)}_buildModel(e,n,s,o,r,i,a,l,u,c,d,h,m,f,p){var _,g;const y=kt._computeFBXModelLocalMatrix(e).multiply(r);if(!e.geometry||"Mesh"!==e.subType||a&&!a(e.name)){if(e.geometry&&"Mesh"===e.subType&&a&&!kt._modelSubtreeMatchesNameFilter(e,a))return;const r=new t.TransformNode(e.name,n);s&&(r.parent=s),kt._applyFBXTransform(r,e),u.push(r),m.set(e.id,r),kt._applyModelMetadata(r,e);for(const t of e.children)this._buildModel(t,n,r,o,y,i,a,l,u,c,d,h,m,f,p)}else{const r=c.get(e.geometry.id),v=d.get(e.geometry.id),b=h.get(e.geometry.id);r&&v&&(r.needInitialSkinMatrix=!0);const x=this._createMesh(e,e.geometry,n,r,v,b);if(r&&v){const e=v.meshBindPoseMatrix?t.Matrix.FromArray(v.meshBindPoseMatrix):y;x.parent=o,kt._applyMatrixToTransform(x,e),x.computeWorldMatrix(!0),x.updatePoseMatrix(t.Matrix.Invert(e)),x.alwaysSelectAsActiveMesh=!0}else s&&(x.parent=s),kt._applyFBXTransform(x,e);if(e.materials.length>1&&(null===(_=e.geometry)||void 0===_?void 0:_.materialIndices))this._applyMultiMaterial(x,e,i,n,f,p);else if(e.materials.length>0){const t=i.get(e.materials[0].id);t&&(x.material=kt._getModelMaterial(t,e,p,f.has(e.materials[0].id)))}(null===(g=e.geometry)||void 0===g?void 0:g.colors)&&this._useUnmodulatedVertexColorMaterials(x,n),this._applyMaterialUVSetCoordinates(x.material,e.geometry),l.push(x),m.set(e.id,x),kt._applyModelMetadata(x,e);for(const t of e.children)this._buildModel(t,n,x,o,y,i,a,l,u,c,d,h,m,f,p)}}_linkSkeletonsToTransformNodes(e,n,s,o,r){for(const i of e){const e=n.get(i.id);if(e)for(const n of i.bones){const i=this._getSourceBone(e,n.index),a=s.get(n.modelId);if(!i||!a)continue;const l=this._getScaleCompensationHelper(e,n.index);if(l){const e=new t.TransformNode(l.name,r);e.parent=a.parent,a.parent=e,kt._applyMatrixToTransform(e,l.getLocalMatrix()),kt._applyMatrixToTransform(a,i.getLocalMatrix()),l.linkTransformNode(e),o.push(e)}else kt._applyMatrixToTransform(a,i.getLocalMatrix());i.linkTransformNode(a)}}}static _modelSubtreeMatchesNameFilter(e,t){for(const n of e.children){if(n.geometry&&"Mesh"===n.subType&&t(n.name))return!0;if(kt._modelSubtreeMatchesNameFilter(n,t))return!0}return!1}static _applyModelMetadata(e,t){var n;(t.customProperties||0!==t.diagnostics.length)&&(e.metadata=Object.assign(Object.assign(Object.assign({},null!==(n=e.metadata)&&void 0!==n?n:{}),t.customProperties?{fbxCustomProperties:t.customProperties}:{}),t.diagnostics.length>0?{fbxDiagnostics:t.diagnostics}:{}))}_createMesh(e,n,s,o,r,i){var a;const l=new t.Mesh(e.name,s);l.sideOrientation=s.useRightHandedSystem?t.Material.CounterClockWiseSideOrientation:t.Material.ClockWiseSideOrientation;const u=new t.VertexData,c=Dt(n.positions),d=e.geometricTranslation,h=e.geometricRotation,m=e.geometricScaling,f=kt._computeFBXGeometricMatrix(d,h,m),p=kt._computeFBXGeometricDeltaMatrix(h,m),_=kt._computeFBXGeometricNormalMatrix(h,m),g=!f.equals(t.Matrix.Identity()),y=!p.equals(t.Matrix.Identity()),v=!_.equals(t.Matrix.Identity());if(g)for(let e=0;e<c.length;e+=3){const n=t.Vector3.TransformCoordinates(new t.Vector3(c[e],c[e+1],c[e+2]),f);c[e]=n.x,c[e+1]=n.y,c[e+2]=n.z}let b;if(u.positions=c,u.indices=Array.from(n.indices),n.normals){if(b=Dt(n.normals),v)for(let e=0;e<b.length;e+=3){const n=t.Vector3.TransformNormal(new t.Vector3(b[e],b[e+1],b[e+2]),_);n.lengthSquared()>0&&n.normalize(),b[e]=n.x,b[e+1]=n.y,b[e+2]=n.z}u.normals=b}if(n.uvs&&(u.uvs=Dt(n.uvs)),n.uvSets.length>1&&(u.uvs2=Dt(n.uvSets[1].data)),n.uvSets.length>2&&(u.uvs3=Dt(n.uvSets[2].data)),n.uvSets.length>3&&(u.uvs4=Dt(n.uvSets[3].data)),n.uvSets.length>4&&(u.uvs5=Dt(n.uvSets[4].data)),n.uvSets.length>5&&(u.uvs6=Dt(n.uvSets[5].data)),n.tangents){const e=Dt(n.tangents);if(v)for(let n=0;n<e.length;n+=4){const s=t.Vector3.TransformNormal(new t.Vector3(e[n],e[n+1],e[n+2]),_);s.lengthSquared()>0&&s.normalize(),e[n]=s.x,e[n+1]=s.y,e[n+2]=s.z}!function(e,t){if(1!==t)for(let n=3;n<e.length;n+=4)e[n]*=t}(e,this._getNormalMapTangentHandednessScale()),u.tangents=e}else b&&u.uvs&&(u.tangents=function(e,t,n,s,o=1,r=null,i=null){var a,l,u,c,d,h;const m=e.length/3,f=new Map,p=new Array(m).fill(null);for(let o=0;o+2<s.length;o+=3){const a=i?i[o/3]:0,l=s[o],u=s[o+1],c=s[o+2],d=3*l,h=3*u,m=3*c,_=2*l,g=2*u,y=2*c,v=e[h]-e[d],b=e[m]-e[d],x=e[h+1]-e[d+1],T=e[m+1]-e[d+1],A=e[h+2]-e[d+2],M=e[m+2]-e[d+2],w=n[g]-n[_],C=n[y]-n[_],R=n[g+1]-n[_+1],S=n[y+1]-n[_+1],O=w*S-C*R;if(Math.abs(O)<1e-8)continue;const F=1/O,E=(S*v-R*b)*F,I=(S*x-R*T)*F,L=(S*A-R*M)*F,P=(w*b-C*v)*F,B=(w*T-C*x)*F,N=(w*M-C*A)*F;Gt(l,u,c,E,I,L,P,B,N,e,t,n,r,a,f,p),Gt(u,c,l,E,I,L,P,B,N,e,t,n,r,a,f,p),Gt(c,l,u,E,I,L,P,B,N,e,t,n,r,a,f,p)}const _=new Float32Array(4*m);for(let e=0;e<m;e++){const n=3*e,s=4*e,[r,i,m]=Vt(t[n],t[n+1],t[n+2]),g=p[e]?f.get(p[e]):void 0,y=null!==(a=null==g?void 0:g.tx)&&void 0!==a?a:0,v=null!==(l=null==g?void 0:g.ty)&&void 0!==l?l:0,b=null!==(u=null==g?void 0:g.tz)&&void 0!==u?u:0,x=r*y+i*v+m*b;let T=y-r*x,A=v-i*x,M=b-m*x;const w=Math.hypot(T,A,M);w>1e-8?(T/=w,A/=w,M/=w):[T,A,M]=Kt(r,i,m);const C=null!==(c=null==g?void 0:g.bx)&&void 0!==c?c:0,R=null!==(d=null==g?void 0:g.by)&&void 0!==d?d:0,S=null!==(h=null==g?void 0:g.bz)&&void 0!==h?h:0,O=i*M-m*A,F=m*T-r*M,E=r*A-i*T,I=Math.hypot(C,R,S)>1e-8&&O*C+F*R+E*S<0?-1:1;_[s]=T,_[s+1]=A,_[s+2]=M,_[s+3]=I*o}return _}(c,b,u.uvs,n.indices,this._getNormalMapTangentHandednessScale(),n.controlPointIndices,n.materialIndices));if(n.colors){const 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;u.colors=e,l.hasVertexAlpha=!1}if(o&&r){const{matricesIndices:e,matricesWeights:t,matricesIndicesExtra:s,matricesWeightsExtra:o,numBoneInfluencers:a}=this._buildSkinningData(n,r,i);u.matricesIndices=e,u.matricesWeights=t,s&&o&&(u.matricesIndicesExtra=s,u.matricesWeightsExtra=o),l.numBoneInfluencers=a}return u.applyToMesh(l),l.metadata=Object.assign(Object.assign({},null!==(a=l.metadata)&&void 0!==a?a:{}),{fbxGeometryId:n.id,fbxControlPointIndices:n.controlPointIndices,fbxGeometryDeltaMatrix:y?p:null,fbxGeometryNormalMatrix:v?_:null,fbxPreRotMatrix:y?p:null}),o&&(l.skeleton=o),l}_applyMultiMaterial(e,n,s,o,r,i){const a=n.geometry.materialIndices,l=e.getIndices();if(!l)return;const u=l.length/3,c=new Map;for(let e=0;e<u;e++){const t=e<a.length?a[e]:0;let n=c.get(t);n||(n=[],c.set(t,n)),n.push(e)}const d=Array.from(c.keys()).sort((e,t)=>e-t),h=[],m=[];for(const e of d){const t=c.get(e),n=h.length;for(const e of t)h.push(l[3*e],l[3*e+1],l[3*e+2]);m.push({start:n,count:3*t.length,matIdx:e})}e.setIndices(h);const f=new t.MultiMaterial(n.name+"_multi",o);for(const e of m){const t=n.materials[e.matIdx];if(t){const e=s.get(t.id);e?f.subMaterials.push(kt._getModelMaterial(e,n,i,r.has(t.id))):f.subMaterials.push(null)}else f.subMaterials.push(null)}e.material=f,e.subMeshes=[];const p=e.getTotalVertices();for(let n=0;n<m.length;n++){const s=m[n];new t.SubMesh(n,0,p,s.start,s.count,e)}}static _collectCullingConflictMaterialIds(e){const t=new Map,n=e=>{var s;for(const n of e.materials){const o=null!==(s=t.get(n.id))&&void 0!==s?s:{cullingOff:!1,cullingOn:!1};e.cullingOff?o.cullingOff=!0:o.cullingOn=!0,t.set(n.id,o)}for(const t of e.children)n(t)};for(const t of e)n(t);const s=new Set;for(const[e,n]of Array.from(t))n.cullingOff&&n.cullingOn&&s.add(e);return s}static _getModelMaterial(e,t,n,s=!0){if(!t.cullingOff||!e.backFaceCulling)return e;if(!s)return e.backFaceCulling=!1,e;const o=null==n?void 0:n.get(e);if(o)return o;const r=e.clone(`${e.name}_CullingOff`);return r.backFaceCulling=!1,null==n||n.set(e,r),r}_applyMaterialUVSetCoordinates(e,n){if(e)if(e instanceof t.MultiMaterial)for(const s of e.subMaterials)s instanceof t.StandardMaterial&&this._applyStandardMaterialUVSetCoordinates(s,n);else e instanceof t.StandardMaterial&&this._applyStandardMaterialUVSetCoordinates(e,n)}_applyStandardMaterialUVSetCoordinates(e,t){var n;for(const s of[e.diffuseTexture,e.bumpTexture,e.emissiveTexture,e.ambientTexture,e.specularTexture,e.opacityTexture,e.reflectionTexture]){if(!s)continue;const e=null===(n=s.metadata)||void 0===n?void 0:n.fbxUVSetName;if(!e)continue;const o=t.uvSets.findIndex(t=>t.name===e);o>=0&&(s.coordinatesIndex=o)}}_useUnmodulatedVertexColorMaterials(e,n){const s=e.material;if(s)if(s instanceof t.StandardMaterial){if(!s.diffuseTexture){const n=s.clone(`${s.name}_VertexColor`);n.diffuseColor=new t.Color3(1,1,1),e.material=n}}else if(s instanceof t.MultiMaterial){const o=new t.MultiMaterial(`${s.name}_VertexColor`,n);o.subMaterials=s.subMaterials.map(e=>{if(e instanceof t.StandardMaterial&&!e.diffuseTexture){const n=e.clone(`${e.name}_VertexColor`);return n.diffuseColor=new t.Color3(1,1,1),n}return e}),e.material=o}}_buildSkinningData(e,t,n){var s,o,r;const i=e.positions.length/3,a=new Float32Array(4*i),l=new Float32Array(4*i);let u=null,c=null,d=0;if(e.controlPointIndices){for(let n=0;n<i;n++){const o=e.controlPointIndices[n],r=null!==(s=t.boneIndices[o])&&void 0!==s?s:[];d=Math.max(d,Math.min(r.length,8))}d>4&&(u=new Float32Array(4*i),c=new Float32Array(4*i));for(let s=0;s<i;s++){const i=e.controlPointIndices[s],d=null!==(o=t.boneIndices[i])&&void 0!==o?o:[],h=null!==(r=t.boneWeights[i])&&void 0!==r?r:[];for(let e=0;e<8;e++){const t=e<4?a:u,o=e<4?l:c;if(!t||!o)continue;const r=4*s+e%4;if(e<d.length){const s=d[e],o=n?n.skinBoneIndexToRigBoneIndex[s]:s;if(void 0===o||o<0)throw new Error(`FBXFileLoader: missing rig bone mapping for skin bone index ${s}`);t[r]=o}else t[r]=0;o[r]=e<h.length?h[e]:0}}}return{matricesIndices:a,matricesWeights:l,matricesIndicesExtra:u,matricesWeightsExtra:c,numBoneInfluencers:Math.max(d,1)}}_createMaterial(e,n,s){var o,r,i,a,l;const u=new t.StandardMaterial(e.name,n),c=e.properties,d=(...t)=>e.textures.some(e=>t.includes(e.propertyName));if("Lambert"===e.type&&(u.specularColor=t.Color3.Black()),c.diffuseColor){const e=d("DiffuseColor","Diffuse")?1:null!==(o=c.diffuseFactor)&&void 0!==o?o:1;u.diffuseColor=new t.Color3(c.diffuseColor[0]*e,c.diffuseColor[1]*e,c.diffuseColor[2]*e)}if(c.ambientColor){const e=d("AmbientColor","Ambient")?1:null!==(r=c.ambientFactor)&&void 0!==r?r:1;u.ambientColor=new t.Color3(c.ambientColor[0]*e,c.ambientColor[1]*e,c.ambientColor[2]*e)}if("Phong"===e.type&&c.specularColor){const e=d("SpecularColor","Specular","Shininess","ShininessExponent")?1:null!==(i=c.specularFactor)&&void 0!==i?i:1;u.specularColor=new t.Color3(c.specularColor[0]*e,c.specularColor[1]*e,c.specularColor[2]*e)}if(c.emissiveColor){const e=d("EmissiveColor","Emissive")?1:null!==(a=c.emissiveFactor)&&void 0!==a?a:1;u.emissiveColor=new t.Color3(c.emissiveColor[0]*e,c.emissiveColor[1]*e,c.emissiveColor[2]*e)}void 0!==c.opacity?u.alpha=c.opacity:void 0!==c.transparencyFactor&&(u.alpha=1-c.transparencyFactor),u.alpha<1&&(u.transparencyMode=t.Material.MATERIAL_ALPHABLEND),void 0!==c.shininess&&(u.specularPower=c.shininess);for(const o of e.textures){if(!kt._isSupportedMaterialTextureSlot(o.propertyName))continue;const e=kt._createTexture(o,n,s,kt._isNormalMapTextureSlot(o.propertyName));if(e){switch(o.propertyName){case"DiffuseColor":u.diffuseTexture=e,u.diffuseColor=new t.Color3(1,1,1);break;case"NormalMap":case"NormalMapTexture":case"normalCamera":case"Bump":case"BumpFactor":u.bumpTexture=e,this._configureNormalTexture(e,u);break;case"EmissiveColor":u.emissiveTexture=e;break;case"AmbientColor":u.ambientTexture=e;break;case"SpecularColor":u.specularTexture=e;break;case"TransparencyFactor":case"TransparentColor":u.opacityTexture=e,u.transparencyMode=t.Material.MATERIAL_ALPHATESTANDBLEND;break;case"ReflectionColor":case"ReflectionFactor":u.reflectionTexture=e}o.uvTranslation&&(e.uOffset=o.uvTranslation[0],e.vOffset=o.uvTranslation[1]),o.uvScaling&&(e.uScale=o.uvScaling[0],e.vScale=o.uvScaling[1]),void 0!==o.uvRotation&&(e.wAng=o.uvRotation*(Math.PI/180)),void 0!==o.uvSetIndex&&(e.coordinatesIndex=o.uvSetIndex),o.uvSetName&&(e.metadata=Object.assign(Object.assign({},null!==(l=e.metadata)&&void 0!==l?l:{}),{fbxUVSetName:o.uvSetName}))}}return u}_configureNormalTexture(e,t){e.gammaSpace=!1,t.invertNormalMapX=!1,t.invertNormalMapY="y-down"===this._options.normalMapCoordinateSystem}_getNormalMapTangentHandednessScale(){return"y-down"===this._options.normalMapCoordinateSystem?-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(e,n,s,o){const r=kt._getTextureSourceName(e),i=kt._getTextureCreationOptions(r,o,e.embeddedData);if(e.embeddedData){const s=new t.Texture(null,n,i),o=null!=r?r:`embeddedTexture_${e.id.toString()}`;return s.updateURL(`data:fbx-embedded-texture/${encodeURIComponent(o)}`,new Uint8Array(e.embeddedData),void 0,i.forcedExtension),s.name=o,s}const a=kt._getExternalTextureUrls(e,s),l=a.shift();return l?kt._createExternalTexture(l,a,n,i):null}static _createExternalTexture(e,n,s,o){n.push(...kt._buildTextureFallbackUrls(e));let r=0;const i=new t.Texture(e,s,Object.assign(Object.assign({},o),{onError:()=>{const e=n[r++];e&&i.getScene()&&i.updateURL(e,null,void 0,kt._getForcedExtension(e))}}));return i}static _buildTextureFallbackUrls(e){const t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\")),n=e.lastIndexOf(".");if(n<=t)return[];const s=e.slice(0,n),o=e.slice(n+1).toLowerCase();return["png","jpg","jpeg","webp","bmp","tga"].filter(e=>e!==o).map(e=>`${s}.${e}`)}static _getTextureCreationOptions(e,t,n){const s=n?e?kt._getMimeType(e):"image/png":void 0;return{buffer:n?new Uint8Array(n):void 0,forcedExtension:e?kt._getForcedExtension(e,s):n?".png":void 0,gammaSpace:!t,mimeType:s}}static _getExternalTextureUrls(e,t){const n=[e.relativeFileName,e.fileName].filter(e=>!!e),s=[];for(const e of n){const n=e.replace(/\\/g,"/");kt._isSafeRelativeTexturePath(n)&&s.push(t+n);const o=kt._getTextureSourceNameFromPath(n);o&&s.push(t+o)}return Array.from(new Set(s))}static _getTextureSourceName(e){const t=e.relativeFileName||e.fileName;if(!t)return null;const n=t.replace(/\\/g,"/");return kt._getTextureSourceNameFromPath(n)}static _getTextureSourceNameFromPath(e){var t;return null!==(t=e.split("/").pop())&&void 0!==t?t:e}static _isSafeRelativeTexturePath(e){return!(/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(e)||e.startsWith("/")||e.startsWith("//")||e.split("/").some(e=>".."===e))}static _getForcedExtension(e,t){const n=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\")),s=e.lastIndexOf(".");if(s>n)return e.slice(s).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(e){const n=t.GetMimeType(e);if(n)return n;switch(kt._getForcedExtension(e)){case".tga":return"image/x-tga";case".bmp":return"image/bmp";case".gif":return"image/gif";default:return"image/png"}}_applyBlendShapes(e,n,s){var o,r,i,a,l,u,c,d;for(const h of e){const e=n.find(e=>{var t;return(null===(t=e.metadata)||void 0===t?void 0:t.fbxGeometryId)===h.geometryId});if(!e)continue;const m=new t.MorphTargetManager(s);m.optimizeInfluencers=!1;const f=null!==(a=null!==(r=null===(o=e.metadata)||void 0===o?void 0:o.fbxGeometryDeltaMatrix)&&void 0!==r?r:null===(i=e.metadata)||void 0===i?void 0:i.fbxPreRotMatrix)&&void 0!==a?a:null,p=null!==(u=null===(l=e.metadata)||void 0===l?void 0:l.fbxGeometryNormalMatrix)&&void 0!==u?u:f;for(const n of h.channels){const o=null===(c=e.metadata)||void 0===c?void 0:c.fbxControlPointIndices;if(!o)continue;const r=e.getVerticesData("position"),i=e.getVerticesData("normal");if(!r)continue;const a=Ut(n.deformPercent,n.fullWeights,n.shapes.length),l=[];for(let e=0;e<n.shapes.length;e++){const u=n.shapes[e];if(!u)continue;const c=$t(u,o,r,i,f,p);if(!c)continue;const h=n.fullWeights&&n.shapes.length>1?`${n.name}_${n.fullWeights[e]}`:n.name,_=new t.MorphTarget(h,null!==(d=a[e])&&void 0!==d?d:0,s);_.setPositions(c.positions),c.normals&&_.setNormals(c.normals),l.push(m.numTargets),m.addTarget(_)}0!==l.length&&(e.metadata||(e.metadata={}),e.metadata.fbxBlendShapeChannelIds||(e.metadata.fbxBlendShapeChannelIds=new Map),e.metadata.fbxBlendShapeChannelIds.set(n.id,l[0]),e.metadata.fbxBlendShapeChannelTargets||(e.metadata.fbxBlendShapeChannelTargets=new Map),e.metadata.fbxBlendShapeChannelTargets.set(n.id,{targetIndices:l,fullWeights:n.fullWeights}))}m.numTargets>0&&(m.numMaxInfluencers=m.numTargets,e.morphTargetManager=m)}}_createCamera(e,n,s){var o;const r=n.get(e.modelId),i=r?r.computeWorldMatrix(!0):t.Matrix.Identity(),a=t.Vector3.TransformCoordinates(t.Vector3.Zero(),i),l=new t.FreeCamera(e.name,a,s);if(l.fov=e.fieldOfView*(Math.PI/180),l.minZ=e.nearPlane,l.maxZ=e.farPlane,l.metadata=Object.assign(Object.assign({},null!==(o=l.metadata)&&void 0!==o?o:{}),{fbxCamera:{projectionType:e.projectionType,focalLength:e.focalLength,filmWidth:e.filmWidth,filmHeight:e.filmHeight,orthoZoom:e.orthoZoom,roll:e.roll,aspectRatio:e.aspectRatio,unknownProperties:e.unknownProperties,diagnostics:e.diagnostics}}),"orthographic"===e.projectionType){const n=e.orthoZoom&&e.orthoZoom>0?e.orthoZoom:1,s=e.aspectRatio>0?e.aspectRatio:1;l.mode=t.Camera.ORTHOGRAPHIC_CAMERA,l.orthoTop=n/2,l.orthoBottom=-n/2,l.orthoRight=n*s/2,l.orthoLeft=-n*s/2}const u=t.Vector3.TransformCoordinates(new t.Vector3(1,0,0),i);return l.setTarget(u),l}_createLight(e,n,s){var o;const r=n.get(e.modelId),i=r?r.computeWorldMatrix(!0):t.Matrix.Identity(),a=t.Vector3.TransformCoordinates(t.Vector3.Zero(),i),l=new t.Color3(e.color[0],e.color[1],e.color[2]),u=t.Vector3.TransformCoordinates(new t.Vector3(0,0,-1),i).subtract(a).normalize();let c;switch(e.lightType){case 1:c=new t.DirectionalLight(e.name,u,s),c.diffuse=l,c.intensity=e.intensity;break;case 2:{const n=e.coneAngle*(Math.PI/180);c=new t.SpotLight(e.name,a,u,n,2,s),c.diffuse=l,c.intensity=e.intensity;break}default:c=new t.PointLight(e.name,a,s),c.diffuse=l,c.intensity=e.intensity}return c.metadata=Object.assign(Object.assign({},null!==(o=c.metadata)&&void 0!==o?o:{}),{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,unknownProperties:e.unknownProperties,diagnostics:e.diagnostics}}),c}_createSkeleton(e,n,s){var o;const r=new t.Skeleton("Skeleton",`skeleton_${e}`,s),i=[],a=new Map,l=[],u=[],c=[];for(let e=0;e<n.length;e++){const t=n[e],s=kt._computeFBXLocalMatrix(t.translation,t.rotation,t.scale,t.preRotation,t.postRotation,t.rotationPivot,t.scalingPivot,t.rotationOffset,t.scalingOffset,t.rotationOrder);l[e]=s,c[e]=kt._computeFBXRuntimeLocalMatrix(n,s,e)}u.push(...kt._computeFBXAbsoluteMatrices(n,c));const d=n.map((e,n)=>e.transformLinkMatrix?t.Matrix.FromArray(e.transformLinkMatrix):e.modelBindPoseMatrix?t.Matrix.FromArray(e.modelBindPoseMatrix):u[n]),h=d.map((e,s)=>{const o=n[s].parentIndex;if(o<0)return e;const r=new t.Matrix;return d[o].invertToRef(r),e.multiply(r)}),m=kt._shouldUseBindMatricesAsRest(n,l,h);for(let e=0;e<n.length;e++){let s=m?h[e]:c[e],u=n[e].parentIndex>=0?i[n[e].parentIndex]:null;if(!m&&2===n[e].inheritType&&n[e].parentIndex>=0&&u){const i=kt._splitParentScaleCompensatedLocalMatrix(l[e],n[n[e].parentIndex].scale),c=new t.Bone(`${n[e].name}__fbx_scaleCompensation`,r,u,i.helperLocalMatrix,i.helperLocalMatrix.clone(),t.Matrix.Identity(),-1);c.metadata=Object.assign(Object.assign({},null!==(o=c.metadata)&&void 0!==o?o:{}),{fbxScaleCompensationForBoneIndex:e,fbxScaleCompensationForBoneName:n[e].name}),a.set(e,c),u=c,s=i.boneLocalMatrix}const d=new t.Bone(n[e].name,r,u,s,m?s.clone():null,m?s.clone():null,e);m&&n[e].isCluster&&kt._getMaxScaleRatio(l[e],h[e])>=10&&this._bindRestBones.add(d),i.push(d)}if(this._sourceBonesBySkeleton.set(r,i),this._scaleCompensationHelpersBySkeleton.set(r,a),!m){for(let e=0;e<n.length;e++)i[e].updateMatrix(h[e],!1,!1);for(const e of Array.from(a.values()))e.updateMatrix(t.Matrix.Identity(),!1,!1);for(const e of r.bones)e.getParent()||e._updateAbsoluteBindMatrices(void 0,!0)}return r}_getSourceBone(e,t){var n,s;return null!==(s=null===(n=this._sourceBonesBySkeleton.get(e))||void 0===n?void 0:n[t])&&void 0!==s?s:e.bones[t]}_getScaleCompensationHelper(e,t){var n;return null===(n=this._scaleCompensationHelpersBySkeleton.get(e))||void 0===n?void 0:n.get(t)}static _computeFBXAbsoluteMatrices(e,t){const n=[];for(let s=0;s<e.length;s++){const o=e[s].parentIndex;n[s]=o<0?t[s].clone():t[s].multiply(n[o])}return n}static _computeFBXRuntimeLocalMatrix(e,t,n,s){const o=e[n].parentIndex;if(2!==e[n].inheritType||o<0)return t;const r=null!=s?s:e[o].scale;return kt._applyParentScaleCompensation(t,r)}static _applyParentScaleCompensation(e,t){const n=kt._splitParentScaleCompensatedLocalMatrix(e,t);return n.boneLocalMatrix.multiply(n.helperLocalMatrix)}static _splitParentScaleCompensatedLocalMatrix(e,n){const s=e.getTranslation(),o=e.clone();return o.setTranslation(t.Vector3.Zero()),{boneLocalMatrix:o,helperLocalMatrix:t.Matrix.Compose(kt._getInverseScaleVector(n),t.Quaternion.Identity(),s)}}static _safeInverseScale(e){return Math.abs(e)>1e-8?1/e:1}static _getInverseScaleVector(e){return new t.Vector3(kt._safeInverseScale(e[0]),kt._safeInverseScale(e[1]),kt._safeInverseScale(e[2]))}static _shouldUseBindMatricesAsRest(e,t,n){return e.some((e,s)=>!!e.isCluster&&kt._getMaxScaleRatio(t[s],n[s])>=10)}static _getMaxScaleRatio(e,n){const s=new t.Vector3,o=new t.Quaternion,r=new t.Vector3,i=new t.Vector3,a=new t.Quaternion,l=new t.Vector3;return e.decompose(s,o,r),n.decompose(i,a,l),Math.max(kt._getScaleRatio(s.x,i.x),kt._getScaleRatio(s.y,i.y),kt._getScaleRatio(s.z,i.z))}static _getScaleRatio(e,t){const n=Math.abs(e),s=Math.abs(t);return n<1e-6||s<1e-6?n<1e-6&&s<1e-6?1:Number.POSITIVE_INFINITY:Math.max(n/s,s/n)}static _computeFBXGeometricMatrix(e,n,s){return function(e,n,s){const o=t.Matrix.Translation(e[0],e[1],e[2]);return Bt(n,s).multiply(o)}(e,n,s)}static _computeFBXGeometricDeltaMatrix(e,t){return Bt(e,t)}static _computeFBXGeometricNormalMatrix(e,n){return function(e,n){const s=Math.PI/180,o=t.Matrix.Scaling(0===n[0]?0:1/n[0],0===n[1]?0:1/n[1],0===n[2]?0:1/n[2]),r=Lt(e[0]*s,e[1]*s,e[2]*s);return o.multiply(r)}(e,n)}static _computeFBXLocalMatrix(e,n,s,o,r,i,a,l,u,c=0){return function(e){const{translation:n,rotation:s,scale:o,preRotation:r,postRotation:i,rotationPivot:a,scalingPivot:l,rotationOffset:u,scalingOffset:c,rotationOrder:d}=e,h=Math.PI/180,m=0!==a[0]||0!==a[1]||0!==a[2]||0!==l[0]||0!==l[1]||0!==l[2],f=0!==u[0]||0!==u[1]||0!==u[2]||0!==c[0]||0!==c[1]||0!==c[2],p=0!==i[0]||0!==i[1]||0!==i[2];if(!m&&!f&&!p){const e=Lt(r[0]*h,r[1]*h,r[2]*h),i=Pt(s[0]*h,s[1]*h,s[2]*h,d),a=t.Matrix.Translation(n[0],n[1],n[2]),l=i.multiply(e);return t.Matrix.Scaling(o[0],o[1],o[2]).multiply(l).multiply(a)}const _=t.Matrix.Translation(n[0],n[1],n[2]),g=t.Matrix.Translation(u[0],u[1],u[2]),y=t.Matrix.Translation(a[0],a[1],a[2]),v=t.Matrix.Translation(-a[0],-a[1],-a[2]),b=t.Matrix.Translation(c[0],c[1],c[2]),x=t.Matrix.Translation(l[0],l[1],l[2]),T=t.Matrix.Translation(-l[0],-l[1],-l[2]),A=Lt(r[0]*h,r[1]*h,r[2]*h),M=Pt(s[0]*h,s[1]*h,s[2]*h,d),w=t.Matrix.Scaling(o[0],o[1],o[2]);let C;if(p){const e=Lt(i[0]*h,i[1]*h,i[2]*h);C=new t.Matrix,e.invertToRef(C)}else C=t.Matrix.Identity();let R=T;return R=R.multiply(w),R=R.multiply(x),R=R.multiply(b),R=R.multiply(v),R=R.multiply(C),R=R.multiply(M),R=R.multiply(A),R=R.multiply(y),R=R.multiply(g),R=R.multiply(_),R}({translation:e,rotation:n,scale:s,preRotation:o,postRotation:r,rotationPivot:i,scalingPivot:a,rotationOffset:l,scalingOffset:u,rotationOrder:c})}static _applyFBXTransform(e,n){const s=kt._computeFBXModelLocalMatrix(n),o=new t.Vector3,r=new t.Quaternion,i=new t.Vector3;s.decompose(o,r,i),e.position=i,e.rotationQuaternion=r,e.scaling=o}static _computeFBXModelLocalMatrix(e){return kt._computeFBXLocalMatrix(e.translation,e.rotation,e.scale,e.preRotation,e.postRotation,e.rotationPivot,e.scalingPivot,e.rotationOffset,e.scalingOffset,e.rotationOrder)}static _getBoneReferenceWorldMatrix(e,t,n,s){return s?e.getTransformMatrices(s):e.prepare(!0),n.computeWorldMatrix(!0),t.getFinalMatrix().multiply(n.getWorldMatrix())}static _applyMatrixToTransform(e,n){const s=new t.Vector3,o=new t.Quaternion,r=new t.Vector3;n.decompose(s,o,r),e.position=r,e.rotationQuaternion=o,e.scaling=s}_createAnimationGroup(e,n,s,o,r,i,a){if(0===e.curveNodes.length)return null;const l=new t.AnimationGroup(e.name,o),u=new Map,c=(e,t)=>{var n;const s=null!==(n=t.getTransformNode())&&void 0!==n?n:t;let o=u.get(s);if(o){if(o.has(e.targetProperty))return}else o=new Set,u.set(s,o);o.add(e.targetProperty),l.addTargetedAnimation(e,s)},d=new Map;for(const e of n){const t=s.get(e.id);if(t)for(const n of e.bones){const e=this._getSourceBone(t,n.index);if(!e)continue;const s=d.get(n.modelId);s?s.push(e):d.set(n.modelId,[e])}}const h=new Map,m=new Map,f=[];for(const t of e.curveNodes)"DeformPercent"!==t.type?d.has(t.targetModelId)?(h.has(t.targetModelId)||h.set(t.targetModelId,[]),h.get(t.targetModelId).push(t)):(m.has(t.targetModelId)||m.set(t.targetModelId,[]),m.get(t.targetModelId).push(t)):f.push(t);const p=new Set;for(const t of n){const n=new Set(t.bones.filter(e=>2===e.inheritType).map(e=>e.modelId));if(0===n.size)continue;const o=s.get(t.id);if(o&&!o.bones.some(e=>this._bindRestBones.has(e))){for(const e of Array.from(n))p.add(e);for(const{bone:s,animations:r}of this._buildInheritedRigBoneAnimations(t,o,h,i,n,e.startTime,e.stopTime))for(const e of r)c(e,s)}}for(const[t,n]of Array.from(h)){if(p.has(t))continue;const s=d.get(t),o=i.get(t);if(s&&0!==s.length&&o)for(const t of s){const s=this._buildBoneAnimations(n,t.name,o,e.startTime,e.stopTime,this._bindRestBones.has(t)?t.getBindMatrix():void 0);for(const e of s)c(e,t)}}for(const[t,n]of Array.from(m)){const s=r.get(t);if(!s)continue;const o=i.get(t);if(!o)continue;const a=this._buildNodeAnimations(n,s.name,o,e.startTime,e.stopTime);for(const e of a)l.addTargetedAnimation(e,s)}for(const n of f){const s=n.targetModelId;let o=!1;for(const r of a){if(!r.morphTargetManager||o)continue;const i=r.metadata,a=null==i?void 0:i.fbxBlendShapeChannelTargets,u=null==a?void 0:a.get(s);if(u&&n.curves.length>0){const s=30;for(let o=0;o<u.targetIndices.length;o++){const i=r.morphTargetManager.getTarget(u.targetIndices[o]);if(!i)continue;const a=new t.Animation(`${i.name}_influence`,"influence",s,t.Animation.ANIMATIONTYPE_FLOAT,t.Animation.ANIMATIONLOOPMODE_CYCLE),c=jt(n.curves[0],s,e.startTime,e.stopTime,e=>{var t;return null!==(t=Ut(e,u.fullWeights,u.targetIndices.length)[o])&&void 0!==t?t:0});a.setKeys(c),l.addTargetedAnimation(a,i)}o=!0;continue}const c=null==i?void 0:i.fbxBlendShapeChannelIds;if(!c)continue;const d=c.get(s);if(void 0===d)continue;const h=r.morphTargetManager.getTarget(d);if(h&&n.curves.length>0){const s=30,r=new t.Animation(`${h.name}_influence`,"influence",s,t.Animation.ANIMATIONTYPE_FLOAT,t.Animation.ANIMATIONLOOPMODE_CYCLE),i=jt(n.curves[0],s,e.startTime,e.stopTime,e=>e/100);r.setKeys(i),l.addTargetedAnimation(r,h),o=!0}}}return l.targetedAnimations.length>0?(l.normalize(30*e.startTime,30*e.stopTime),l):(l.dispose(),null)}_buildInheritedRigBoneAnimations(e,n,s,o,r,i,a){const l=30,u=new Set;for(let t=0;t<e.bones.length;t++)if(r.has(e.bones[t].modelId))for(let n=t;n>=0;n=e.bones[n].parentIndex)u.add(e.bones[n].modelId);const c=Wt(e.bones.filter(e=>u.has(e.modelId)).flatMap(e=>{var t;return null!==(t=s.get(e.modelId))&&void 0!==t?t:[]}),l,i,a);if(0===c.length)return[];const d=e.bones.map(()=>({posKeys:[],rotKeys:[],sclKeys:[],prevQuat:null})),h=e.bones.map(()=>({posKeys:[],rotKeys:[],sclKeys:[],prevQuat:null})),m=e.bones.map((e,s)=>{const r=this._getSourceBone(n,s),i=o.get(e.modelId);if(!r||!i||!this._bindRestBones.has(r))return null;const a=kt._computeFBXModelLocalMatrix(i),l=new t.Matrix;return a.invertToRef(l),l});for(const i of c){const a=e.bones.map((e,r)=>{var a,l;const u=o.get(e.modelId),c=null!==(a=s.get(e.modelId))&&void 0!==a?a:[];let d=u?this._sampleModelLocalMatrix(u,c,i):t.Matrix.Identity();const h=m[r];if(h){const e=this._getSourceBone(n,r);d=(null!==(l=null==e?void 0:e.getBindMatrix())&&void 0!==l?l:t.Matrix.Identity()).multiply(h).multiply(d)}return d}),u=e.bones.map(e=>{var t;const n=o.get(e.modelId),r=null!==(t=s.get(e.modelId))&&void 0!==t?t:[];return n?this._sampleModelScale(n,r,i):e.scale}),c=i*l;for(let t=0;t<a.length;t++){if(!r.has(e.bones[t].modelId))continue;const n=e.bones[t].parentIndex,s=n>=0?u[n]:e.bones[t].scale,o=kt._splitParentScaleCompensatedLocalMatrix(a[t],s);kt._pushMatrixKeys(d[t],c,o.boneLocalMatrix),kt._pushMatrixKeys(h[t],c,o.helperLocalMatrix)}}const f=[];for(let s=0;s<e.bones.length;s++){if(!r.has(e.bones[s].modelId))continue;const o=this._getSourceBone(n,s);if(!o)continue;const{posKeys:i,rotKeys:a,sclKeys:u}=d[s],c=[];if(!this._isVector3KeysConstant(i)){const e=new t.Animation(`${o.name}_position`,"position",l,t.Animation.ANIMATIONTYPE_VECTOR3,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(i),c.push(e)}if(!zt(a)){const e=new t.Animation(`${o.name}_rotation`,"rotationQuaternion",l,t.Animation.ANIMATIONTYPE_QUATERNION,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(a),c.push(e)}if(!this._isVector3KeysConstant(u)){const e=new t.Animation(`${o.name}_scaling`,"scaling",l,t.Animation.ANIMATIONTYPE_VECTOR3,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(u),c.push(e)}c.length>0&&f.push({bone:o,animations:c});const m=this._getScaleCompensationHelper(n,s);if(!m)continue;const p=[],{posKeys:_,rotKeys:g,sclKeys:y}=h[s];if(!this._isVector3KeysConstant(_)){const e=new t.Animation(`${m.name}_position`,"position",l,t.Animation.ANIMATIONTYPE_VECTOR3,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(_),p.push(e)}if(!zt(g)){const e=new t.Animation(`${m.name}_rotation`,"rotationQuaternion",l,t.Animation.ANIMATIONTYPE_QUATERNION,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(g),p.push(e)}if(!this._isVector3KeysConstant(y)){const e=new t.Animation(`${m.name}_scaling`,"scaling",l,t.Animation.ANIMATIONTYPE_VECTOR3,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(y),p.push(e)}p.length>0&&f.push({bone:m,animations:p})}return f}static _pushMatrixKeys(e,n,s){const o=new t.Vector3,r=new t.Quaternion,i=new t.Vector3;s.decompose(o,r,i),e.prevQuat&&t.Quaternion.Dot(e.prevQuat,r)<0&&r.scaleInPlace(-1),e.prevQuat=r,e.posKeys.push({frame:n,value:i}),e.rotKeys.push({frame:n,value:r}),e.sclKeys.push({frame:n,value:o})}_buildNodeAnimations(e,n,s,o,r){var i,a,l,u,c,d,h,m,f;const p=e.find(e=>"T"===e.type),_=e.find(e=>"R"===e.type),g=e.find(e=>"S"===e.type),y=Wt(e,30,o,r);if(0===y.length)return[];const v=null==p?void 0:p.curves.find(e=>"d|X"===e.channel),b=null==p?void 0:p.curves.find(e=>"d|Y"===e.channel),x=null==p?void 0:p.curves.find(e=>"d|Z"===e.channel),T=null==_?void 0:_.curves.find(e=>"d|X"===e.channel),A=null==_?void 0:_.curves.find(e=>"d|Y"===e.channel),M=null==_?void 0:_.curves.find(e=>"d|Z"===e.channel),w=null==g?void 0:g.curves.find(e=>"d|X"===e.channel),C=null==g?void 0:g.curves.find(e=>"d|Y"===e.channel),R=null==g?void 0:g.curves.find(e=>"d|Z"===e.channel),S=[],O=[],F=[];let E=null;for(const e of y){const n=30*e,o=null!==(i=it(v,e))&&void 0!==i?i:s.translation[0],r=null!==(a=it(b,e))&&void 0!==a?a:s.translation[1],p=null!==(l=it(x,e))&&void 0!==l?l:s.translation[2],_=null!==(u=it(T,e))&&void 0!==u?u:s.rotation[0],g=null!==(c=it(A,e))&&void 0!==c?c:s.rotation[1],y=null!==(d=it(M,e))&&void 0!==d?d:s.rotation[2],I=null!==(h=it(w,e))&&void 0!==h?h:s.scale[0],L=null!==(m=it(C,e))&&void 0!==m?m:s.scale[1],P=null!==(f=it(R,e))&&void 0!==f?f:s.scale[2],B=kt._computeFBXLocalMatrix([o,r,p],[_,g,y],[I,L,P],s.preRotation,s.postRotation,s.rotationPivot,s.scalingPivot,s.rotationOffset,s.scalingOffset,s.rotationOrder),N=new t.Vector3,k=new t.Quaternion,D=new t.Vector3;B.decompose(N,k,D),E&&t.Quaternion.Dot(E,k)<0&&k.scaleInPlace(-1),E=k,S.push({frame:n,value:D}),O.push({frame:n,value:k}),F.push({frame:n,value:N})}const I=[];if(!this._isVector3KeysConstant(S)){const e=new t.Animation(`${n}_position`,"position",30,t.Animation.ANIMATIONTYPE_VECTOR3,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(S),I.push(e)}if(_){const e=new t.Animation(`${n}_rotation`,"rotationQuaternion",30,t.Animation.ANIMATIONTYPE_QUATERNION,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(O),I.push(e)}if(!this._isVector3KeysConstant(F)){const e=new t.Animation(`${n}_scaling`,"scaling",30,t.Animation.ANIMATIONTYPE_VECTOR3,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(F),I.push(e)}return I}_isVector3KeysConstant(e){if(e.length<2)return!0;const t=e[0].value;for(let n=1;n<e.length;n++){const s=e[n].value;if(Math.abs(s.x-t.x)>1e-4||Math.abs(s.y-t.y)>1e-4||Math.abs(s.z-t.z)>1e-4)return!1}return!0}_sampleModelLocalMatrix(e,t,n,s){var o,r,i,a,l,u,c,d,h;const m=t.find(e=>"T"===e.type),f=t.find(e=>"R"===e.type),p=t.find(e=>"S"===e.type),_=null==m?void 0:m.curves.find(e=>"d|X"===e.channel),g=null==m?void 0:m.curves.find(e=>"d|Y"===e.channel),y=null==m?void 0:m.curves.find(e=>"d|Z"===e.channel),v=null==f?void 0:f.curves.find(e=>"d|X"===e.channel),b=null==f?void 0:f.curves.find(e=>"d|Y"===e.channel),x=null==f?void 0:f.curves.find(e=>"d|Z"===e.channel),T=null==p?void 0:p.curves.find(e=>"d|X"===e.channel),A=null==p?void 0:p.curves.find(e=>"d|Y"===e.channel),M=null==p?void 0:p.curves.find(e=>"d|Z"===e.channel);return kt._computeFBXLocalMatrix([null!==(o=it(_,n))&&void 0!==o?o:e.translation[0],null!==(r=it(g,n))&&void 0!==r?r:e.translation[1],null!==(i=it(y,n))&&void 0!==i?i:e.translation[2]],[null!==(a=it(v,n))&&void 0!==a?a:e.rotation[0],null!==(l=it(b,n))&&void 0!==l?l:e.rotation[1],null!==(u=it(x,n))&&void 0!==u?u:e.rotation[2]],null!=s?s:[null!==(c=it(T,n))&&void 0!==c?c:e.scale[0],null!==(d=it(A,n))&&void 0!==d?d:e.scale[1],null!==(h=it(M,n))&&void 0!==h?h:e.scale[2]],e.preRotation,e.postRotation,e.rotationPivot,e.scalingPivot,e.rotationOffset,e.scalingOffset,e.rotationOrder)}_sampleModelScale(e,t,n){var s,o,r;const i=t.find(e=>"S"===e.type),a=null==i?void 0:i.curves.find(e=>"d|X"===e.channel),l=null==i?void 0:i.curves.find(e=>"d|Y"===e.channel),u=null==i?void 0:i.curves.find(e=>"d|Z"===e.channel);return[null!==(s=it(a,n))&&void 0!==s?s:e.scale[0],null!==(o=it(l,n))&&void 0!==o?o:e.scale[1],null!==(r=it(u,n))&&void 0!==r?r:e.scale[2]]}_buildBoneAnimations(e,n,s,o,r,i){var a,l,u,c,d,h,m,f,p;const _=e.find(e=>"T"===e.type),g=e.find(e=>"R"===e.type),y=e.find(e=>"S"===e.type),v=Wt(e,30,o,r);if(0===v.length)return[];const b=null==_?void 0:_.curves.find(e=>"d|X"===e.channel),x=null==_?void 0:_.curves.find(e=>"d|Y"===e.channel),T=null==_?void 0:_.curves.find(e=>"d|Z"===e.channel),A=null==g?void 0:g.curves.find(e=>"d|X"===e.channel),M=null==g?void 0:g.curves.find(e=>"d|Y"===e.channel),w=null==g?void 0:g.curves.find(e=>"d|Z"===e.channel),C=null==y?void 0:y.curves.find(e=>"d|X"===e.channel),R=null==y?void 0:y.curves.find(e=>"d|Y"===e.channel),S=null==y?void 0:y.curves.find(e=>"d|Z"===e.channel),O=[],F=[],E=[];let I=null,L=null;if(i){const e=kt._computeFBXLocalMatrix(s.translation,s.rotation,s.scale,s.preRotation,s.postRotation,s.rotationPivot,s.scalingPivot,s.rotationOffset,s.scalingOffset,s.rotationOrder);L=new t.Matrix,e.invertToRef(L)}for(const e of v){const n=30*e,o=null!==(a=it(b,e))&&void 0!==a?a:s.translation[0],r=null!==(l=it(x,e))&&void 0!==l?l:s.translation[1],_=null!==(u=it(T,e))&&void 0!==u?u:s.translation[2],g=null!==(c=it(A,e))&&void 0!==c?c:s.rotation[0],y=null!==(d=it(M,e))&&void 0!==d?d:s.rotation[1],v=null!==(h=it(w,e))&&void 0!==h?h:s.rotation[2],P=null!==(m=it(C,e))&&void 0!==m?m:s.scale[0],B=null!==(f=it(R,e))&&void 0!==f?f:s.scale[1],N=null!==(p=it(S,e))&&void 0!==p?p:s.scale[2],k=kt._computeFBXLocalMatrix([o,r,_],[g,y,v],[P,B,N],s.preRotation,s.postRotation,s.rotationPivot,s.scalingPivot,s.rotationOffset,s.scalingOffset,s.rotationOrder),D=L&&i?i.multiply(L).multiply(k):k,G=new t.Vector3,V=new t.Quaternion,H=new t.Vector3;D.decompose(G,V,H),I&&t.Quaternion.Dot(I,V)<0&&V.scaleInPlace(-1),I=V,O.push({frame:n,value:H}),F.push({frame:n,value:V}),E.push({frame:n,value:G})}const P=[];if(!this._isVector3KeysConstant(O)){const e=new t.Animation(`${n}_position`,"position",30,t.Animation.ANIMATIONTYPE_VECTOR3,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(O),P.push(e)}if(g){const e=new t.Animation(`${n}_rotation`,"rotationQuaternion",30,t.Animation.ANIMATIONTYPE_QUATERNION,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(F),P.push(e)}if(!this._isVector3KeysConstant(E)){const e=new t.Animation(`${n}_scaling`,"scaling",30,t.Animation.ANIMATIONTYPE_VECTOR3,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(E),P.push(e)}return P}_buildNameFilter(e){if(!e)return null;if("string"==typeof e)return""===e?null:t=>t===e;if(0===e.length)return null;const t=new Set(e);return e=>t.has(e)}}function Dt(e){const t=new Float32Array(e.length);for(let n=0;n<e.length;n++)t[n]=e[n];return t}function Gt(e,t,n,s,o,r,i,a,l,u,c,d,h,m,f,p){var _;const g=function(e,t,n,s){const o=3*t,r=3*n,i=3*s,a=e[r]-e[o],l=e[r+1]-e[o+1],u=e[r+2]-e[o+2],c=e[i]-e[o],d=e[i+1]-e[o+1],h=e[i+2]-e[o+2],m=Math.hypot(a,l,u),f=Math.hypot(c,d,h);if(m<=1e-8||f<=1e-8)return 0;const p=(a*c+l*d+u*h)/(m*f);return Math.acos(Math.max(-1,Math.min(1,p)))}(u,e,t,n);if(g<=1e-8)return;const y=function(e,t,n,s,o,r,i,a,l,u,c,d){const h=3*e,m=3*e,f=2*e,[p,_,g]=Vt(l[m],l[m+1],l[m+2]),y=function(e,t,n,s,o,r,i,a,l){return(t*r-n*o)*i+(n*s-e*r)*a+(e*o-t*s)*l<0?-1:1}(p,_,g,t,n,s,o,r,i);return[c?`cp:${c[e]}`:`p:${Ht(a[h])},${Ht(a[h+1])},${Ht(a[h+2])}`,Ht(p),Ht(_),Ht(g),Ht(u[f]),Ht(u[f+1]),y,d].join("|")}(e,s,o,r,i,a,l,u,c,d,h,m);let v=f.get(y);v||(v={tx:0,ty:0,tz:0,bx:0,by:0,bz:0},f.set(y,v)),v.tx+=s*g,v.ty+=o*g,v.tz+=r*g,v.bx+=i*g,v.by+=a*g,v.bz+=l*g,null!==(_=p[e])&&void 0!==_||(p[e]=y)}function Vt(e,t,n){const s=Math.hypot(e,t,n);return s>1e-8?[e/s,t/s,n/s]:[0,0,1]}function Ht(e){const t=Math.round(1e6*e);return Object.is(t,-0)?0:t}function Kt(e,t,n){const s=Math.abs(e)<.9?1:0,o=1===s?0:1,r=e*s+t*o;let i=s-e*r,a=o-t*r,l=-n*r;const u=Math.hypot(i,a,l);return u<=1e-8?[1,0,0]:(i/=u,a/=u,l/=u,[i,a,l])}function $t(e,n,s,o,r,i){const a=s.length/3,l=new Float32Array(3*a),u=null!==e.normals&&null!==o?new Float32Array(3*a):null;for(let e=0;e<l.length;e++)l[e]=s[e];if(u&&o)for(let e=0;e<u.length;e++)u[e]=o[e];const c=new Map;for(let t=0;t<e.indices.length;t++)c.set(e.indices[t],t);for(let s=0;s<a;s++){const o=n[s],a=c.get(o);if(void 0===a)continue;let d=e.vertices[3*a],h=e.vertices[3*a+1],m=e.vertices[3*a+2];if(r){const e=t.Vector3.TransformNormal(new t.Vector3(d,h,m),r);d=e.x,h=e.y,m=e.z}if(l[3*s]+=d,l[3*s+1]+=h,l[3*s+2]+=m,u&&e.normals){let n=e.normals[3*a],o=e.normals[3*a+1],r=e.normals[3*a+2];if(i){const e=t.Vector3.TransformNormal(new t.Vector3(n,o,r),i);e.lengthSquared()>0&&e.normalize(),n=e.x,o=e.y,r=e.z}u[3*s]+=n,u[3*s+1]+=o,u[3*s+2]+=r}}return{positions:l,normals:u}}function Ut(e,t,n){if(n<=0)return[];if(!t||t.length!==n||1===n)return[qt(e/((null==t?void 0:t[0])&&0!==t[0]?t[0]:100))];const s=new Array(n).fill(0);if(e<=t[0])return s[0]=0===t[0]?e<=0?1:0:qt(e/t[0]),s;for(let n=1;n<t.length;n++){const o=t[n-1],r=t[n];if(e>r)continue;const i=r-o;if(Math.abs(i)<1e-6)return s[n]=1,s;const a=qt((e-o)/i);return s[n-1]=1-a,s[n]=a,s}return s[n-1]=1,s}function qt(e){return Math.max(0,Math.min(1,e))}function Wt(e,t,n,s){let o=Number.POSITIVE_INFINITY,r=Number.NEGATIVE_INFINITY;const i=new Set;for(const t of e)for(const e of t.curves)for(const t of e.keys)o=Math.min(o,t.time),r=Math.max(r,t.time),t.time>=n&&t.time<=s&&i.add(t.time);if(!Number.isFinite(o)||!Number.isFinite(r))return[];const a=s>n?n:o,l=s>n?s:r,u=new Set([a,l,...Array.from(i)]),c=Math.ceil(a*t),d=Math.floor(l*t);for(let e=c;e<=d;e++)u.add(e/t);return Array.from(u).sort((e,t)=>e-t)}function zt(e){if(e.length<2)return!0;const t=e[0].value;for(let n=1;n<e.length;n++){const s=e[n].value;if(Math.abs(s.x-t.x)>1e-4||Math.abs(s.y-t.y)>1e-4||Math.abs(s.z-t.z)>1e-4||Math.abs(s.w-t.w)>1e-4)return!1}return!0}function jt(e,t,n,s,o){var r,i,a,l,u,c;const d=function(e,t,n){var s,o,r,i;return n>t?{start:t,stop:n}:{start:null!==(o=null===(s=e.keys[0])||void 0===s?void 0:s.time)&&void 0!==o?o:0,stop:null!==(i=null===(r=e.keys[e.keys.length-1])||void 0===r?void 0:r.time)&&void 0!==i?i:0}}(e,n,s),h=e.keys.filter(e=>e.time>=d.start&&e.time<=d.stop).map(e=>({source:e,frame:e.time*t,value:o(e.value)}));h.some(e=>Math.abs(e.source.time-d.start)<1e-6)||h.unshift({source:{time:d.start,value:null!==(r=it(e,d.start))&&void 0!==r?r:0,interpolation:"linear"},frame:d.start*t,value:o(null!==(i=it(e,d.start))&&void 0!==i?i:0)}),h.some(e=>Math.abs(e.source.time-d.stop)<1e-6)||h.push({source:{time:d.stop,value:null!==(a=it(e,d.stop))&&void 0!==a?a:0,interpolation:"linear"},frame:d.stop*t,value:o(null!==(l=it(e,d.stop))&&void 0!==l?l:0)});const m=h.map(e=>({frame:e.frame,value:e.value}));for(let e=0;e<h.length-1;e++){const n=h[e].source,s=m[e+1];if("constant"===n.interpolation){m[e].interpolation=1;continue}if("cubic"!==n.interpolation)continue;const r=h[e+1].source,i=Math.max(r.time-n.time,1e-6),a=(r.value-n.value)/i;m[e].outTangent=Xt(null!==(u=n.rightSlope)&&void 0!==u?u:a,o)/t,s.inTangent=Xt(null!==(c=n.nextLeftSlope)&&void 0!==c?c:a,o)/t}return m}function Xt(e,t){return t(e)-t(0)}let Yt=!1;function Qt(){Yt||(Yt=!0,t.RegisterSceneLoaderPlugin(new kt))}Qt();var Zt={__proto__:null,FBXFileLoader:kt,RegisterFBXFileLoader:Qt};function Jt(e,t,n,s){const o={externalResourceFunction:s};return n&&(o.uri="file:"===t?n:t+n),ArrayBuffer.isView(e)?GLTFValidator.validateBytes(e,o):GLTFValidator.validateString(e,o)}function en(){const e=[];onmessage=t=>{const n=t.data;switch(n.id){case"init":importScripts(n.url);break;case"validate":Jt(n.data,n.rootUrl,n.fileName,t=>new Promise((n,s)=>{const o=e.length;e.push({resolve:n,reject:s}),postMessage({id:"getExternalResource",index:o,uri:t})})).then(e=>{postMessage({id:"validate.resolve",value:e})},e=>{postMessage({id:"validate.reject",reason:e})});break;case"getExternalResource.resolve":e[n.index].resolve(n.value);break;case"getExternalResource.reject":e[n.index].reject(n.reason)}}}class tn{static ValidateAsync(e,n,s,o){return"function"==typeof Worker?new Promise((r,i)=>{const a=`${Jt}(${en})()`,l=URL.createObjectURL(new Blob([a],{type:"application/javascript"})),u=new Worker(l),c=e=>{u.removeEventListener("error",c),u.removeEventListener("message",d),i(e)},d=e=>{const t=e.data;switch(t.id){case"getExternalResource":o(t.uri).then(e=>{u.postMessage({id:"getExternalResource.resolve",index:t.index,value:e},[e.buffer])},e=>{u.postMessage({id:"getExternalResource.reject",index:t.index,reason:e})});break;case"validate.resolve":u.removeEventListener("error",c),u.removeEventListener("message",d),tn._LastResults=t.value,r(t.value),u.terminate();break;case"validate.reject":u.removeEventListener("error",c),u.removeEventListener("message",d),i(t.reason),u.terminate()}};if(u.addEventListener("error",c),u.addEventListener("message",d),u.postMessage({id:"init",url:t.Tools.GetBabylonScriptURL(this.Configuration.url)}),ArrayBuffer.isView(e)){const t=e.slice();u.postMessage({id:"validate",data:t,rootUrl:n,fileName:s},[t.buffer])}else u.postMessage({id:"validate",data:e,rootUrl:n,fileName:s})}):(this._LoadScriptPromise||(this._LoadScriptPromise=t.Tools.LoadBabylonScriptAsync(this.Configuration.url)),this._LoadScriptPromise.then(()=>Jt(e,n,s,o)))}}tn.Configuration={url:`${t.Tools._DefaultCdnUrl}/gltf_validator.js`},tn._LastResults=null;var nn={__proto__:null,GLTFValidation:tn};const sn="Z2xURg",on={name:"gltf",extensions:{".gltf":{isBinary:!1,mimeType:"model/gltf+json"},".glb":{isBinary:!0,mimeType:"model/gltf-binary"}},canDirectLoad:e=>-1!==e.indexOf("asset")&&-1!==e.indexOf("version")||e.startsWith("data:base64,"+sn)||e.startsWith("data:;base64,"+sn)||e.startsWith("data:application/octet-stream;base64,"+sn)||e.startsWith("data:model/gltf-binary;base64,"+sn)};function rn(e,t,n){try{return Promise.resolve(new Uint8Array(e,t,n))}catch(e){return Promise.reject(e)}}var an,ln,un;e.GLTFLoaderCoordinateSystemMode=void 0,(an=e.GLTFLoaderCoordinateSystemMode||(e.GLTFLoaderCoordinateSystemMode={}))[an.AUTO=0]="AUTO",an[an.FORCE_RIGHT_HANDED=1]="FORCE_RIGHT_HANDED",e.GLTFLoaderAnimationStartMode=void 0,(ln=e.GLTFLoaderAnimationStartMode||(e.GLTFLoaderAnimationStartMode={}))[ln.NONE=0]="NONE",ln[ln.FIRST=1]="FIRST",ln[ln.ALL=2]="ALL",e.GLTFLoaderState=void 0,(un=e.GLTFLoaderState||(e.GLTFLoaderState={}))[un.LOADING=0]="LOADING",un[un.READY=1]="READY",un[un.COMPLETE=2]="COMPLETE";class cn{constructor(){this.alwaysComputeBoundingBox=!1,this.alwaysComputeSkeletonRootNode=!1,this.animationStartMode=e.GLTFLoaderAnimationStartMode.FIRST,this.compileMaterials=!1,this.compileShadowGenerators=!1,this.coordinateSystemMode=e.GLTFLoaderCoordinateSystemMode.AUTO,this.createInstances=!0,this.loadAllMaterials=!1,this.loadMorphTargets=!0,this.useMaxMorphTargetInfluencers=!0,this.loadNodeAnimations=!0,this.loadOnlyMaterials=!1,this.loadSkins=!0,this.skipMaterials=!1,this.targetFps=60,this.transparencyAsCoverage=!1,this.useClipPlane=!1,this.useGltfTextureNames=!1,this.useRangeRequests=!1,this.useSRGBBuffers=!0,this.validate=!1,this.useOpenPBR=!1,this.dontUseTransmissionHelper=!1}}const dn=new cn;class hn extends cn{constructor(){super(...arguments),this.extensionOptions={},this.preprocessUrlAsync=e=>Promise.resolve(e)}copyFrom(e){var t,n,s,o,r,i,a,l,u,c,d,h,m,f,p,_,g,y,v,b,x,T,A,M,w,C,R;e&&(this.alwaysComputeBoundingBox=null!==(t=e.alwaysComputeBoundingBox)&&void 0!==t?t:this.alwaysComputeBoundingBox,this.alwaysComputeSkeletonRootNode=null!==(n=e.alwaysComputeSkeletonRootNode)&&void 0!==n?n:this.alwaysComputeSkeletonRootNode,this.animationStartMode=null!==(s=e.animationStartMode)&&void 0!==s?s:this.animationStartMode,this.capturePerformanceCounters=null!==(o=e.capturePerformanceCounters)&&void 0!==o?o:this.capturePerformanceCounters,this.compileMaterials=null!==(r=e.compileMaterials)&&void 0!==r?r:this.compileMaterials,this.compileShadowGenerators=null!==(i=e.compileShadowGenerators)&&void 0!==i?i:this.compileShadowGenerators,this.coordinateSystemMode=null!==(a=e.coordinateSystemMode)&&void 0!==a?a:this.coordinateSystemMode,this.createInstances=null!==(l=e.createInstances)&&void 0!==l?l:this.createInstances,this.customRootNode=e.customRootNode,this.extensionOptions=null!==(u=e.extensionOptions)&&void 0!==u?u:this.extensionOptions,this.loadAllMaterials=null!==(c=e.loadAllMaterials)&&void 0!==c?c:this.loadAllMaterials,this.loadMorphTargets=null!==(d=e.loadMorphTargets)&&void 0!==d?d:this.loadMorphTargets,this.loadNodeAnimations=null!==(h=e.loadNodeAnimations)&&void 0!==h?h:this.loadNodeAnimations,this.loadOnlyMaterials=null!==(m=e.loadOnlyMaterials)&&void 0!==m?m:this.loadOnlyMaterials,this.loadSkins=null!==(f=e.loadSkins)&&void 0!==f?f:this.loadSkins,this.loggingEnabled=null!==(p=e.loggingEnabled)&&void 0!==p?p:this.loggingEnabled,this.onCameraLoaded=e.onCameraLoaded,this.onMaterialLoaded=e.onMaterialLoaded,this.onMeshLoaded=e.onMeshLoaded,this.onParsed=e.onParsed,this.onSkinLoaded=e.onSkinLoaded,this.onTextureLoaded=e.onTextureLoaded,this.onValidated=e.onValidated,this.preprocessUrlAsync=null!==(_=e.preprocessUrlAsync)&&void 0!==_?_:this.preprocessUrlAsync,this.skipMaterials=null!==(g=e.skipMaterials)&&void 0!==g?g:this.skipMaterials,this.targetFps=null!==(y=e.targetFps)&&void 0!==y?y:this.targetFps,this.transparencyAsCoverage=null!==(v=e.transparencyAsCoverage)&&void 0!==v?v:this.transparencyAsCoverage,this.useClipPlane=null!==(b=e.useClipPlane)&&void 0!==b?b:this.useClipPlane,this.useGltfTextureNames=null!==(x=e.useGltfTextureNames)&&void 0!==x?x:this.useGltfTextureNames,this.useMaxMorphTargetInfluencers=null!==(T=e.useMaxMorphTargetInfluencers)&&void 0!==T?T:this.useMaxMorphTargetInfluencers,this.useOpenPBR=null!==(A=e.useOpenPBR)&&void 0!==A?A:this.useOpenPBR,this.useRangeRequests=null!==(M=e.useRangeRequests)&&void 0!==M?M:this.useRangeRequests,this.useSRGBBuffers=null!==(w=e.useSRGBBuffers)&&void 0!==w?w:this.useSRGBBuffers,this.validate=null!==(C=e.validate)&&void 0!==C?C:this.validate,this.dontUseTransmissionHelper=null!==(R=e.dontUseTransmissionHelper)&&void 0!==R?R:this.dontUseTransmissionHelper)}}class mn extends hn{constructor(e){super(),this.onParsedObservable=new t.Observable,this.onMeshLoadedObservable=new t.Observable,this.onSkinLoadedObservable=new t.Observable,this.onTextureLoadedObservable=new t.Observable,this.onMaterialLoadedObservable=new t.Observable,this.onCameraLoadedObservable=new t.Observable,this.onCompleteObservable=new t.Observable,this.onErrorObservable=new t.Observable,this.onDisposeObservable=new t.Observable,this.onExtensionLoadedObservable=new t.Observable,this.onValidatedObservable=new t.Observable,this._loader=null,this._state=null,this._requests=new Array,this.name=on.name,this.extensions=on.extensions,this.onLoaderStateChangedObservable=new t.Observable,this._logIndentLevel=0,this._loggingEnabled=!1,this._log=this._logDisabled,this._capturePerformanceCounters=!1,this._startPerformanceCounter=this._startPerformanceCounterDisabled,this._endPerformanceCounter=this._endPerformanceCounterDisabled,this.copyFrom(Object.assign(Object.assign({},dn),e))}set onParsed(e){this._onParsedObserver&&this.onParsedObservable.remove(this._onParsedObserver),e&&(this._onParsedObserver=this.onParsedObservable.add(e))}set onMeshLoaded(e){this._onMeshLoadedObserver&&this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver),e&&(this._onMeshLoadedObserver=this.onMeshLoadedObservable.add(e))}set onSkinLoaded(e){this._onSkinLoadedObserver&&this.onSkinLoadedObservable.remove(this._onSkinLoadedObserver),e&&(this._onSkinLoadedObserver=this.onSkinLoadedObservable.add(t=>e(t.node,t.skinnedNode)))}set onTextureLoaded(e){this._onTextureLoadedObserver&&this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver),e&&(this._onTextureLoadedObserver=this.onTextureLoadedObservable.add(e))}set onMaterialLoaded(e){this._onMaterialLoadedObserver&&this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver),e&&(this._onMaterialLoadedObserver=this.onMaterialLoadedObservable.add(e))}set onCameraLoaded(e){this._onCameraLoadedObserver&&this.onCameraLoadedObservable.remove(this._onCameraLoadedObserver),e&&(this._onCameraLoadedObserver=this.onCameraLoadedObservable.add(e))}set onComplete(e){this._onCompleteObserver&&this.onCompleteObservable.remove(this._onCompleteObserver),this._onCompleteObserver=this.onCompleteObservable.add(e)}set onError(e){this._onErrorObserver&&this.onErrorObservable.remove(this._onErrorObserver),this._onErrorObserver=this.onErrorObservable.add(e)}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}set onExtensionLoaded(e){this._onExtensionLoadedObserver&&this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver),this._onExtensionLoadedObserver=this.onExtensionLoadedObservable.add(e)}get loggingEnabled(){return this._loggingEnabled}set loggingEnabled(e){this._loggingEnabled!==e&&(this._loggingEnabled=e,this._loggingEnabled?this._log=this._logEnabled:this._log=this._logDisabled)}get capturePerformanceCounters(){return this._capturePerformanceCounters}set capturePerformanceCounters(e){this._capturePerformanceCounters!==e&&(this._capturePerformanceCounters=e,this._capturePerformanceCounters?(this._startPerformanceCounter=this._startPerformanceCounterEnabled,this._endPerformanceCounter=this._endPerformanceCounterEnabled):(this._startPerformanceCounter=this._startPerformanceCounterDisabled,this._endPerformanceCounter=this._endPerformanceCounterDisabled))}set onValidated(e){this._onValidatedObserver&&this.onValidatedObservable.remove(this._onValidatedObserver),this._onValidatedObserver=this.onValidatedObservable.add(e)}dispose(){this._loader&&(this._loader.dispose(),this._loader=null);for(const e of this._requests)e.abort();this._requests.length=0,delete this._progressCallback,this.preprocessUrlAsync=e=>Promise.resolve(e),this.onMeshLoadedObservable.clear(),this.onSkinLoadedObservable.clear(),this.onTextureLoadedObservable.clear(),this.onMaterialLoadedObservable.clear(),this.onCameraLoadedObservable.clear(),this.onCompleteObservable.clear(),this.onExtensionLoadedObservable.clear(),this.onDisposeObservable.notifyObservers(void 0),this.onDisposeObservable.clear()}loadFile(e,n,s,o,r,i,a,l){if(ArrayBuffer.isView(n))return this._loadBinary(e,n,s,o,a,l),null;this._progressCallback=r;const u=n.name||t.Tools.GetFilename(n);if(i){if(this.useRangeRequests){this.validate&&t.Logger.Warn("glTF validation is not supported when range requests are enabled");const s={abort:()=>{},onCompleteObservable:new t.Observable},r={readAsync:(t,s)=>new Promise((o,r)=>{this._loadFile(e,n,e=>{o(new Uint8Array(e))},!0,e=>{r(e)},e=>{e.setRequestHeader("Range",`bytes=${t}-${t+s-1}`)})}),byteLength:0};return this._unpackBinaryAsync(new t.DataReader(r)).then(e=>{s.onCompleteObservable.notifyObservers(s),o(e)},a?e=>a(void 0,e):void 0),s}return this._loadFile(e,n,n=>{this._validate(e,new Uint8Array(n,0,n.byteLength),s,u),this._unpackBinaryAsync(new t.DataReader({readAsync:(e,t)=>rn(n,e,t),byteLength:n.byteLength})).then(e=>{o(e)},a?e=>a(void 0,e):void 0)},!0,a)}return this._loadFile(e,n,t=>{try{this._validate(e,t,s,u),o({json:this._parseJson(t)})}catch(e){a&&a()}},!1,a)}_loadBinary(e,n,s,o,r,i){this._validate(e,new Uint8Array(n.buffer,n.byteOffset,n.byteLength),s,i),this._unpackBinaryAsync(new t.DataReader({readAsync:(e,t)=>function(e,t,n){try{if(t<0||t>=e.byteLength)throw new RangeError("Offset is out of range.");if(t+n>e.byteLength)throw new RangeError("Length is out of range.");return Promise.resolve(new Uint8Array(e.buffer,e.byteOffset+t,n))}catch(e){return Promise.reject(e)}}(n,e,t),byteLength:n.byteLength})).then(e=>{o(e)},r?e=>r(void 0,e):void 0)}importMeshAsync(e,t,n,s,o,r){return Promise.resolve().then(()=>(this.onParsedObservable.notifyObservers(n),this.onParsedObservable.clear(),this._log(`Loading ${r||""}`),this._loader=this._getLoader(n),this._loader.importMeshAsync(e,t,null,n,s,o,r)))}loadAsync(e,t,n,s,o){return Promise.resolve().then(()=>(this.onParsedObservable.notifyObservers(t),this.onParsedObservable.clear(),this._log(`Loading ${o||""}`),this._loader=this._getLoader(t),this._loader.loadAsync(e,t,n,s,o)))}loadAssetContainerAsync(e,n,s,o,r){return Promise.resolve().then(()=>{this.onParsedObservable.notifyObservers(n),this.onParsedObservable.clear(),this._log(`Loading ${r||""}`),this._loader=this._getLoader(n);const i=new t.AssetContainer(e),a=[];this.onMaterialLoadedObservable.add(e=>{a.push(e)});const l=[];this.onTextureLoadedObservable.add(e=>{l.push(e)});const u=[];this.onCameraLoadedObservable.add(e=>{u.push(e)});const c=[];return this.onMeshLoadedObservable.add(e=>{e.morphTargetManager&&c.push(e.morphTargetManager)}),this._loader.importMeshAsync(null,e,i,n,s,o,r).then(e=>(Array.prototype.push.apply(i.geometries,e.geometries),Array.prototype.push.apply(i.meshes,e.meshes),Array.prototype.push.apply(i.particleSystems,e.particleSystems),Array.prototype.push.apply(i.skeletons,e.skeletons),Array.prototype.push.apply(i.animationGroups,e.animationGroups),Array.prototype.push.apply(i.materials,a),Array.prototype.push.apply(i.textures,l),Array.prototype.push.apply(i.lights,e.lights),Array.prototype.push.apply(i.transformNodes,e.transformNodes),Array.prototype.push.apply(i.cameras,u),Array.prototype.push.apply(i.morphTargetManagers,c),i))})}canDirectLoad(e){return on.canDirectLoad(e)}directLoad(e,n){if(n.startsWith("base64,"+sn)||n.startsWith(";base64,"+sn)||n.startsWith("application/octet-stream;base64,"+sn)||n.startsWith("model/gltf-binary;base64,"+sn)){const s=t.DecodeBase64UrlToBinary(n);return this._validate(e,new Uint8Array(s,0,s.byteLength)),this._unpackBinaryAsync(new t.DataReader({readAsync:(e,t)=>rn(s,e,t),byteLength:s.byteLength}))}return this._validate(e,n),Promise.resolve({json:this._parseJson(n)})}createPlugin(e){return new mn(e[on.name])}get loaderState(){return this._state}whenCompleteAsync(){return new Promise((e,t)=>{this.onCompleteObservable.addOnce(()=>{e()}),this.onErrorObservable.addOnce(e=>{t(e)})})}_setState(t){this._state!==t&&(this._state=t,this.onLoaderStateChangedObservable.notifyObservers(this._state),this._log(e.GLTFLoaderState[this._state]))}_loadFile(e,t,n,s,o,r){const i=e._loadFile(t,n,e=>{this._onProgress(e,i)},!0,s,o,r);return i.onCompleteObservable.add(()=>{i._lengthComputable=!0,i._total=i._loaded}),this._requests.push(i),i}_onProgress(e,t){if(!this._progressCallback)return;t._lengthComputable=e.lengthComputable,t._loaded=e.loaded,t._total=e.total;let n=!0,s=0,o=0;for(const e of this._requests){if(void 0===e._lengthComputable||void 0===e._loaded||void 0===e._total)return;n=n&&e._lengthComputable,s+=e._loaded,o+=e._total}this._progressCallback({lengthComputable:n,loaded:s,total:n?o:0})}_validate(e,n,s="",o=""){this.validate&&(this._startPerformanceCounter("Validate JSON"),tn.ValidateAsync(n,s,o,t=>this.preprocessUrlAsync(s+t).then(t=>e._loadFileAsync(t,void 0,!0,!0).then(e=>new Uint8Array(e,0,e.byteLength)))).then(e=>{this._endPerformanceCounter("Validate JSON"),this.onValidatedObservable.notifyObservers(e),this.onValidatedObservable.clear()},e=>{this._endPerformanceCounter("Validate JSON"),t.Tools.Warn(`Failed to validate: ${e.message}`),this.onValidatedObservable.clear()}))}_getLoader(e){const t=e.json.asset||{};this._log(`Asset version: ${t.version}`),t.minVersion&&this._log(`Asset minimum version: ${t.minVersion}`),t.generator&&this._log(`Asset generator: ${t.generator}`);const n=mn._parseVersion(t.version);if(!n)throw new Error("Invalid version: "+t.version);if(void 0!==t.minVersion){const e=mn._parseVersion(t.minVersion);if(!e)throw new Error("Invalid minimum version: "+t.minVersion);if(mn._compareVersion(e,{major:2,minor:0})>0)throw new Error("Incompatible minimum version: "+t.minVersion)}const s={1:mn._CreateGLTF1Loader,2:mn._CreateGLTF2Loader}[n.major];if(!s)throw new Error("Unsupported version: "+t.version);return s(this)}_parseJson(e){this._startPerformanceCounter("Parse JSON"),this._log(`JSON length: ${e.length}`);const t=JSON.parse(e);return this._endPerformanceCounter("Parse JSON"),t}_unpackBinaryAsync(e){return this._startPerformanceCounter("Unpack Binary"),e.loadAsync(20).then(()=>{const n=e.readUint32();if(1179937895!==n)throw new t.RuntimeError("Unexpected magic: "+n,t.ErrorCodes.GLTFLoaderUnexpectedMagicError);const s=e.readUint32();this.loggingEnabled&&this._log(`Binary version: ${s}`);const o=e.readUint32();let r;switch(this.useRangeRequests||o===e.buffer.byteLength||t.Logger.Warn(`Length in header does not match actual data length: ${o} != ${e.buffer.byteLength}`),s){case 1:r=this._unpackBinaryV1Async(e,o);break;case 2:r=this._unpackBinaryV2Async(e,o);break;default:throw new Error("Unsupported version: "+s)}return this._endPerformanceCounter("Unpack Binary"),r})}_unpackBinaryV1Async(e,t){const n=e.readUint32(),s=e.readUint32();if(0!==s)throw new Error(`Unexpected content format: ${s}`);const o=t-e.byteOffset,r={json:this._parseJson(e.readString(n)),bin:null};if(0!==o){const t=e.byteOffset;r.bin={readAsync:(n,s)=>e.buffer.readAsync(t+n,s),byteLength:o}}return Promise.resolve(r)}_unpackBinaryV2Async(e,t){const n=1313821514,s=e.readUint32();if(e.readUint32()!==n)throw new Error("First chunk format is not JSON");return e.byteOffset+s===t?e.loadAsync(s).then(()=>({json:this._parseJson(e.readString(s)),bin:null})):e.loadAsync(s+8).then(()=>{const o={json:this._parseJson(e.readString(s)),bin:null},r=()=>{const s=e.readUint32();switch(e.readUint32()){case n:throw new Error("Unexpected JSON chunk");case 5130562:{const t=e.byteOffset;o.bin={readAsync:(n,s)=>e.buffer.readAsync(t+n,s),byteLength:s},e.skipBytes(s);break}default:e.skipBytes(s)}return e.byteOffset!==t?e.loadAsync(8).then(r):Promise.resolve(o)};return r()})}static _parseVersion(e){if("1.0"===e||"1.0.1"===e)return{major:1,minor:0};const t=(e+"").match(/^(\d+)\.(\d+)/);return t?{major:parseInt(t[1]),minor:parseInt(t[2])}:null}static _compareVersion(e,t){return e.major>t.major?1:e.major<t.major?-1:e.minor>t.minor?1:e.minor<t.minor?-1:0}_logOpen(e){this._log(e),this._logIndentLevel++}_logClose(){--this._logIndentLevel}_logEnabled(e){const n=mn._logSpaces.substring(0,2*this._logIndentLevel);t.Logger.Log(`${n}${e}`)}_logDisabled(e){}_startPerformanceCounterEnabled(e){t.Tools.StartPerformanceCounter(e)}_startPerformanceCounterDisabled(e){}_endPerformanceCounterEnabled(e){t.Tools.EndPerformanceCounter(e)}_endPerformanceCounterDisabled(e){}}mn.IncrementalLoading=!0,mn.HomogeneousCoordinates=!1,mn._logSpaces=" ";let fn=!1;function pn(){fn||(fn=!0,t.RegisterSceneLoaderPlugin(new mn))}pn();var _n,gn,yn,vn,bn,xn,Tn,An,Mn,wn={__proto__:null,GLTFFileLoader:mn,get GLTFLoaderAnimationStartMode(){return e.GLTFLoaderAnimationStartMode},get GLTFLoaderCoordinateSystemMode(){return e.GLTFLoaderCoordinateSystemMode},GLTFLoaderDefaultOptions:dn,get GLTFLoaderState(){return e.GLTFLoaderState},RegisterGLTFFileLoader:pn};!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"}(_n||(_n={})),function(e){e[e.FRAGMENT=35632]="FRAGMENT",e[e.VERTEX=35633]="VERTEX"}(gn||(gn={})),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"}(yn||(yn={})),function(e){e[e.CLAMP_TO_EDGE=33071]="CLAMP_TO_EDGE",e[e.MIRRORED_REPEAT=33648]="MIRRORED_REPEAT",e[e.REPEAT=10497]="REPEAT"}(vn||(vn={})),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"}(bn||(bn={})),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"}(xn||(xn={})),function(e){e[e.FRONT=1028]="FRONT",e[e.BACK=1029]="BACK",e[e.FRONT_AND_BACK=1032]="FRONT_AND_BACK"}(Tn||(Tn={})),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"}(An||(An={}));class Cn{static SetMatrix(e,n,s,o,r){let i=null;if("MODEL"===s.semantic?i=n.getWorldMatrix():"PROJECTION"===s.semantic?i=e.getProjectionMatrix():"VIEW"===s.semantic?i=e.getViewMatrix():"MODELVIEWINVERSETRANSPOSE"===s.semantic?i=t.Matrix.Transpose(n.getWorldMatrix().multiply(e.getViewMatrix()).invert()):"MODELVIEW"===s.semantic?i=n.getWorldMatrix().multiply(e.getViewMatrix()):"MODELVIEWPROJECTION"===s.semantic?i=n.getWorldMatrix().multiply(e.getTransformMatrix()):"MODELINVERSE"===s.semantic?i=n.getWorldMatrix().invert():"VIEWINVERSE"===s.semantic?i=e.getViewMatrix().invert():"PROJECTIONINVERSE"===s.semantic?i=e.getProjectionMatrix().invert():"MODELVIEWINVERSE"===s.semantic?i=n.getWorldMatrix().multiply(e.getViewMatrix()).invert():"MODELVIEWPROJECTIONINVERSE"===s.semantic?i=n.getWorldMatrix().multiply(e.getTransformMatrix()).invert():"MODELINVERSETRANSPOSE"===s.semantic&&(i=t.Matrix.Transpose(n.getWorldMatrix().invert())),i)switch(s.type){case yn.FLOAT_MAT2:r.setMatrix2x2(o,t.Matrix.GetAsMatrix2x2(i));break;case yn.FLOAT_MAT3:r.setMatrix3x3(o,t.Matrix.GetAsMatrix3x3(i));break;case yn.FLOAT_MAT4:r.setMatrix(o,i)}}static SetUniform(e,n,s,o){switch(o){case yn.FLOAT:return e.setFloat(n,s),!0;case yn.FLOAT_VEC2:return e.setVector2(n,t.Vector2.FromArray(s)),!0;case yn.FLOAT_VEC3:return e.setVector3(n,t.Vector3.FromArray(s)),!0;case yn.FLOAT_VEC4:return e.setVector4(n,t.Vector4.FromArray(s)),!0;default:return!1}}static GetWrapMode(e){switch(e){case vn.CLAMP_TO_EDGE:return t.Texture.CLAMP_ADDRESSMODE;case vn.MIRRORED_REPEAT:return t.Texture.MIRROR_ADDRESSMODE;case vn.REPEAT:default:return t.Texture.WRAP_ADDRESSMODE}}static GetByteStrideFromType(e){switch(e.type){case"VEC2":return 2;case"VEC3":return 3;case"VEC4":case"MAT2":return 4;case"MAT3":return 9;case"MAT4":return 16;default:return 1}}static GetTextureFilterMode(e){switch(e){case bn.LINEAR:case bn.LINEAR_MIPMAP_NEAREST:case bn.LINEAR_MIPMAP_LINEAR:return t.Texture.TRILINEAR_SAMPLINGMODE;case bn.NEAREST:case bn.NEAREST_MIPMAP_NEAREST:return t.Texture.NEAREST_SAMPLINGMODE;default:return t.Texture.BILINEAR_SAMPLINGMODE}}static GetBufferFromBufferView(e,t,n,s,o){n=t.byteOffset+n;const r=e.loadedBufferViews[t.buffer];if(n+s>r.byteLength)throw new Error("Buffer access is out of range");const i=r.buffer;switch(n+=r.byteOffset,o){case _n.BYTE:return new Int8Array(i,n,s);case _n.UNSIGNED_BYTE:return new Uint8Array(i,n,s);case _n.SHORT:return new Int16Array(i,n,s);case _n.UNSIGNED_SHORT:return new Uint16Array(i,n,s);default:return new Float32Array(i,n,s)}}static GetBufferFromAccessor(e,t){const n=e.bufferViews[t.bufferView],s=t.count*Cn.GetByteStrideFromType(t);return Cn.GetBufferFromBufferView(e,n,t.byteOffset,s,t.componentType)}static DecodeBufferToText(e){let t="";const n=e.byteLength;for(let s=0;s<n;++s)t+=String.fromCharCode(e[s]);return t}static GetDefaultMaterial(e){if(!Cn._DefaultMaterial){t.Effect.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("\n"),t.Effect.ShadersStore.GLTFDefaultMaterialPixelShader=["precision highp float;","","uniform vec4 u_emission;","","void main(void)","{"," gl_FragColor = u_emission;","}"].join("\n");const n={vertex:"GLTFDefaultMaterial",fragment:"GLTFDefaultMaterial"},s={attributes:["position"],uniforms:["worldView","projection","u_emission"],samplers:new Array,needAlphaBlending:!1};Cn._DefaultMaterial=new t.ShaderMaterial("GLTFDefaultMaterial",e,n,s),Cn._DefaultMaterial.setColor4("u_emission",new t.Color4(.5,.5,.5,1))}return Cn._DefaultMaterial}}Cn._DefaultMaterial=null,function(e){e[e.IDENTIFIER=1]="IDENTIFIER",e[e.UNKNOWN=2]="UNKNOWN",e[e.END_OF_INPUT=3]="END_OF_INPUT"}(Mn||(Mn={}));class Rn{constructor(e){this._pos=0,this.currentToken=Mn.UNKNOWN,this.currentIdentifier="",this.currentString="",this.isLetterOrDigitPattern=/^[a-zA-Z0-9]+$/,this._toParse=e,this._maxPos=e.length}getNextToken(){if(this.isEnd())return Mn.END_OF_INPUT;if(this.currentString=this.read(),this.currentToken=Mn.UNKNOWN,"_"===this.currentString||this.isLetterOrDigitPattern.test(this.currentString))for(this.currentToken=Mn.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}}const Sn=["MODEL","VIEW","PROJECTION","MODELVIEW","MODELVIEWPROJECTION","JOINTMATRIX"],On=["world","view","projection","worldView","worldViewProjection","mBones"],Fn=["translation","rotation","scale"],En=["position","rotationQuaternion","scaling"],In=(e,t,n)=>{for(const s in e){const o=e[s];n[t][s]=o}},Ln=e=>{if(e)for(let t=0;t<e.length/2;t++)e[2*t+1]=1-e[2*t+1]},Pn=e=>{if("NORMAL"===e.semantic)return"normal";if("POSITION"===e.semantic)return"position";if("JOINT"===e.semantic)return"matricesIndices";if("WEIGHT"===e.semantic)return"matricesWeights";if("COLOR"===e.semantic)return"color";if(e.semantic&&-1!==e.semantic.indexOf("TEXCOORD_")){const t=Number(e.semantic.split("_")[1]);return"uv"+(0===t?"":t+1)}return null},Bn=e=>{let n;if(e.translation||e.rotation||e.scale){const s=t.Vector3.FromArray(e.scale||[1,1,1]),o=t.Quaternion.FromArray(e.rotation||[0,0,0,1]),r=t.Vector3.FromArray(e.translation||[0,0,0]);n=t.Matrix.Compose(s,o,r)}else n=t.Matrix.FromArray(e.matrix);return n},Nn=(e,n,s,o)=>{for(let e=0;e<o.bones.length;e++)if(o.bones[e].name===s)return o.bones[e];const r=e.nodes;for(const i in r){const a=r[i];if(!a.jointName)continue;const l=a.children;for(let r=0;r<l.length;r++){const u=e.nodes[l[r]];if(u.jointName&&u.jointName===s){const s=Bn(a),r=new t.Bone(a.name||"",o,Nn(e,n,a.jointName,o),s);return r.id=i,r}}}return null},kn=(e,t)=>{for(let n=0;n<e.length;n++){const s=e[n];for(let e=0;e<s.node.children.length;e++)if(s.node.children[e]===t)return s.bone}return null},Dn=(e,t)=>{const n=e.nodes;let s=n[t];if(s)return{node:s,id:t};for(const e in n)if(s=n[e],s.jointName===t)return{node:s,id:e};return null},Gn=(e,t)=>{for(let n=0;n<e.jointNames.length;n++)if(e.jointNames[n]===t)return!0;return!1},Vn=(e,n,s,o,r)=>{if(r||(e.scene._blockEntityCollection=!!e.assetContainer,(r=new t.Mesh(n.name||"",e.scene))._parentContainer=e.assetContainer,e.scene._blockEntityCollection=!1,r.id=o),!n.babylonNode)return r;const i=[];let a=null;const l=[],u=[],c=[],d=[];for(let n=0;n<s.length;n++){const o=s[n],r=e.meshes[o];if(r)for(let n=0;n<r.primitives.length;n++){const s=new t.VertexData,o=r.primitives[n];o.mode;const h=o.attributes;let m,f;for(const n in h)if(m=e.accessors[h[n]],f=Cn.GetBufferFromAccessor(e,m),"NORMAL"===n)s.normals=new Float32Array(f.length),s.normals.set(f);else if("POSITION"===n){if(mn.HomogeneousCoordinates){s.positions=new Float32Array(f.length-f.length/4);for(let e=0;e<f.length;e+=4)s.positions[e]=f[e],s.positions[e+1]=f[e+1],s.positions[e+2]=f[e+2]}else s.positions=new Float32Array(f.length),s.positions.set(f);u.push(s.positions.length)}else if(-1!==n.indexOf("TEXCOORD_")){const e=Number(n.split("_")[1]),o=t.VertexBuffer.UVKind+(0===e?"":e+1),r=new Float32Array(f.length);r.set(f),Ln(r),s.set(r,o)}else"JOINT"===n?(s.matricesIndices=new Float32Array(f.length),s.matricesIndices.set(f)):"WEIGHT"===n?(s.matricesWeights=new Float32Array(f.length),s.matricesWeights.set(f)):"COLOR"===n&&(s.colors=new Float32Array(f.length),s.colors.set(f));if(m=e.accessors[o.indices],m)f=Cn.GetBufferFromAccessor(e,m),s.indices=new Int32Array(f.length),s.indices.set(f),d.push(s.indices.length);else{const e=[];for(let t=0;t<s.positions.length/3;t++)e.push(t);s.indices=new Int32Array(e),d.push(s.indices.length)}a?a.merge(s):a=s;const p=e.scene.getMaterialById(o.material);i.push(null===p?Cn.GetDefaultMaterial(e.scene):p),l.push(0===l.length?0:l[l.length-1]+u[u.length-2]),c.push(0===c.length?0:c[c.length-1]+d[d.length-2])}}let h;e.scene._blockEntityCollection=!!e.assetContainer,i.length>1?(h=new t.MultiMaterial("multimat"+o,e.scene),h.subMaterials=i):h=new t.StandardMaterial("multimat"+o,e.scene),1===i.length&&(h=i[0]),h._parentContainer=e.assetContainer,r.material||(r.material=h),new t.Geometry(o,e.scene,a,!1,r),r.computeWorldMatrix(!0),e.scene._blockEntityCollection=!1,r.subMeshes=[];let m=0;for(let n=0;n<s.length;n++){const o=s[n],i=e.meshes[o];if(i)for(let e=0;e<i.primitives.length;e++)i.primitives[e].mode,t.SubMesh.AddToMesh(m,l[m],u[m],c[m],d[m],r,r,!0),m++}return r},Hn=(e,t,n,s)=>{e.position&&(e.position=t),(e.rotationQuaternion||e.rotation)&&(e.rotationQuaternion=n),e.scaling&&(e.scaling=s)},Kn=(e,n,s)=>{let o=null;if(e.importOnlyMeshes&&(n.skin||n.meshes)&&e.importMeshesNames&&e.importMeshesNames.length>0&&-1===e.importMeshesNames.indexOf(n.name||""))return null;if(n.skin){if(n.meshes){const r=e.skins[n.skin],i=Vn(e,n,n.meshes,s,n.babylonNode);i.skeleton=e.scene.getLastSkeletonById(n.skin),null===i.skeleton&&(i.skeleton=((e,n,s,o)=>{if(o||(o=new t.Skeleton(n.name||"","",e.scene)),!n.babylonSkeleton)return o;const r=[],i=[];((e,n,s,o)=>{for(const r in e.nodes){const i=e.nodes[r],a=r;if(!i.jointName||Gn(s,i.jointName))continue;const l=Bn(i),u=new t.Bone(i.name||"",n,null,l);u.id=a,o.push({bone:u,node:i,id:a})}for(let e=0;e<o.length;e++){const t=o[e],n=t.node.children;for(let e=0;e<n.length;e++){let s=null;for(let t=0;t<o.length;t++)if(o[t].id===n[e]){s=o[t];break}s&&(s.bone._parent=t.bone,t.bone.children.push(s.bone))}}})(e,o,n,r),o.bones=[];for(let s=0;s<n.jointNames.length;s++){const a=Dn(e,n.jointNames[s]);if(!a)continue;const l=a.node;if(!l){t.Tools.Warn("Joint named "+n.jointNames[s]+" does not exist");continue}const u=a.id,c=e.scene.getBoneById(u);if(c){o.bones.push(c);continue}let d,h=null;for(let r=0;r<s;r++){const s=Dn(e,n.jointNames[r]);if(!s)continue;const i=s.node;if(!i){t.Tools.Warn("Joint named "+n.jointNames[r]+" does not exist when looking for parent");continue}const a=i.children;if(a){d=!1;for(let t=0;t<a.length;t++)if(a[t]===u){h=Nn(e,n,n.jointNames[r],o),d=!0;break}if(d)break}}const m=Bn(l);!h&&r.length>0&&(h=kn(r,u),h&&-1===i.indexOf(h)&&i.push(h)),new t.Bone(l.jointName||"",o,h,m).id=u}const a=o.bones;o.bones=[];for(let t=0;t<n.jointNames.length;t++){const s=Dn(e,n.jointNames[t]);if(s)for(let e=0;e<a.length;e++)if(a[e].id===s.id){o.bones.push(a[e]);break}}o.prepare();for(let e=0;e<i.length;e++)o.bones.push(i[e]);return o})(e,r,0,r.babylonSkeleton),r.babylonSkeleton||(r.babylonSkeleton=i.skeleton)),o=i}}else if(n.meshes)o=Vn(e,n,n.mesh?[n.mesh]:n.meshes,s,n.babylonNode);else if(!n.light||n.babylonNode||e.importOnlyMeshes){if(n.camera&&!n.babylonNode&&!e.importOnlyMeshes){const s=e.cameras[n.camera];if(s){if(e.scene._blockEntityCollection=!!e.assetContainer,"orthographic"===s.type){const s=new t.FreeCamera(n.camera,t.Vector3.Zero(),e.scene,!1);s.name=n.name||"",s.mode=t.Camera.ORTHOGRAPHIC_CAMERA,s.attachControl(),o=s,s._parentContainer=e.assetContainer}else if("perspective"===s.type){const r=s[s.type],i=new t.FreeCamera(n.camera,t.Vector3.Zero(),e.scene,!1);i.name=n.name||"",i.attachControl(),r.aspectRatio||(r.aspectRatio=e.scene.getEngine().getRenderWidth()/e.scene.getEngine().getRenderHeight()),r.znear&&r.zfar&&(i.maxZ=r.zfar,i.minZ=r.znear),o=i,i._parentContainer=e.assetContainer}e.scene._blockEntityCollection=!1}}}else{const s=e.lights[n.light];if(s)if("ambient"===s.type){const r=s[s.type],i=new t.HemisphericLight(n.light,t.Vector3.Zero(),e.scene);i.name=n.name||"",r.color&&(i.diffuse=t.Color3.FromArray(r.color)),o=i}else if("directional"===s.type){const r=s[s.type],i=new t.DirectionalLight(n.light,t.Vector3.Zero(),e.scene);i.name=n.name||"",r.color&&(i.diffuse=t.Color3.FromArray(r.color)),o=i}else if("point"===s.type){const r=s[s.type],i=new t.PointLight(n.light,t.Vector3.Zero(),e.scene);i.name=n.name||"",r.color&&(i.diffuse=t.Color3.FromArray(r.color)),o=i}else if("spot"===s.type){const r=s[s.type],i=new t.SpotLight(n.light,t.Vector3.Zero(),t.Vector3.Zero(),0,0,e.scene);i.name=n.name||"",r.color&&(i.diffuse=t.Color3.FromArray(r.color)),r.fallOfAngle&&(i.angle=r.fallOfAngle),r.fallOffExponent&&(i.exponent=r.fallOffExponent),o=i}}if(!n.jointName){if(n.babylonNode)return n.babylonNode;if(null===o){e.scene._blockEntityCollection=!!e.assetContainer;const s=new t.Mesh(n.name||"",e.scene);s._parentContainer=e.assetContainer,e.scene._blockEntityCollection=!1,n.babylonNode=s,o=s}}if(null!==o){if(n.matrix&&o instanceof t.Mesh)((e,n)=>{if(n.matrix){const s=new t.Vector3(0,0,0),o=new t.Quaternion,r=new t.Vector3(0,0,0);t.Matrix.FromArray(n.matrix).decompose(r,o,s),Hn(e,s,o,r)}else n.translation&&n.rotation&&n.scale&&Hn(e,t.Vector3.FromArray(n.translation),t.Quaternion.FromArray(n.rotation),t.Vector3.FromArray(n.scale));e.computeWorldMatrix(!0)})(o,n);else{const e=n.translation||[0,0,0],s=n.rotation||[0,0,0,1],r=n.scale||[1,1,1];Hn(o,t.Vector3.FromArray(e),t.Quaternion.FromArray(s),t.Vector3.FromArray(r))}o.updateCache(!0),n.babylonNode=o}return o},$n=(e,t,n,s=!1)=>{const o=e.nodes[t];let r=null;if(s=!(e.importOnlyMeshes&&!s&&e.importMeshesNames)||-1!==e.importMeshesNames.indexOf(o.name||"")||0===e.importMeshesNames.length,!o.jointName&&s&&(r=Kn(e,o,t),null!==r&&(r.id=t,r.parent=n)),o.children)for(let t=0;t<o.children.length;t++)$n(e,o.children[t],r,s)},Un=e=>{let n=e.currentScene;if(n)for(let t=0;t<n.nodes.length;t++)$n(e,n.nodes[t],null);else for(const t in e.scenes){n=e.scenes[t];for(let t=0;t<n.nodes.length;t++)$n(e,n.nodes[t],null)}(e=>{for(const n in e.animations){const s=e.animations[n];if(!s.channels||!s.samplers)continue;let o=null;for(let r=0;r<s.channels.length;r++){const i=s.channels[r],a=s.samplers[i.sampler];if(!a)continue;let l,u;s.parameters?(l=s.parameters[a.input],u=s.parameters[a.output]):(l=a.input,u=a.output);const c=Cn.GetBufferFromAccessor(e,e.accessors[l]),d=Cn.GetBufferFromAccessor(e,e.accessors[u]),h=i.target.id;let m=e.scene.getNodeById(h);if(null===m&&(m=e.scene.getNodeByName(h)),null===m){t.Tools.Warn("Creating animation named "+n+". But cannot find node named "+h+" to attach to");continue}const f=m instanceof t.Bone;let p=i.target.path;const _=Fn.indexOf(p);-1!==_&&(p=En[_]);let g=t.Animation.ANIMATIONTYPE_MATRIX;f||("rotationQuaternion"===p?(g=t.Animation.ANIMATIONTYPE_QUATERNION,m.rotationQuaternion=new t.Quaternion):g=t.Animation.ANIMATIONTYPE_VECTOR3);let y=null;const v=[];let b=0,x=!1;f&&o&&o.getKeys().length===c.length&&(y=o,x=!0),x||(e.scene._blockEntityCollection=!!e.assetContainer,y=new t.Animation(n,f?"_matrix":p,1,g,t.Animation.ANIMATIONLOOPMODE_CYCLE),e.scene._blockEntityCollection=!1);for(let e=0;e<c.length;e++){let n;if("rotationQuaternion"===p?(n=t.Quaternion.FromArray([d[b],d[b+1],d[b+2],d[b+3]]),b+=4):(n=t.Vector3.FromArray([d[b],d[b+1],d[b+2]]),b+=3),f){const s=m;let r=t.Vector3.Zero(),i=new t.Quaternion,a=t.Vector3.Zero(),l=s.getBaseMatrix();x&&o&&(l=o.getKeys()[e].value),l.decompose(a,i,r),"position"===p?r=n:"rotationQuaternion"===p?i=n:a=n,n=t.Matrix.Compose(a,i,r)}x?o&&(o.getKeys()[e].value=n):v.push({frame:c[e],value:n})}!x&&y&&(y.setKeys(v),m.animations.push(y)),o=y,e.scene.stopAnimation(m),e.scene.beginAnimation(m,0,c[c.length-1],!0,1)}}})(e);for(let t=0;t<e.scene.skeletons.length;t++){const n=e.scene.skeletons[t];e.scene.beginAnimation(n,0,Number.MAX_VALUE,!0,1)}},qn=(e,t,n)=>{for(const s in t.uniforms){const o=t.uniforms[s],r=t.parameters[o];if(e.currentIdentifier===s&&r.semantic&&!r.source&&!r.node){const e=Sn.indexOf(r.semantic);if(-1!==e)return delete n[s],On[e]}}return e.currentIdentifier},Wn=e=>{for(const t in e.materials)Xn.LoadMaterialAsync(e,t,()=>{},()=>{})};class zn{static CreateRuntime(e,t,n){const s={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&&In(e.extensions,"extensions",s),e.extensionsUsed&&In(e.extensionsUsed,"extensionsUsed",s),e.buffers&&((e,t)=>{for(const n in e){const s=e[n];t.buffers[n]=s,t.buffersCount++}})(e.buffers,s),e.bufferViews&&In(e.bufferViews,"bufferViews",s),e.accessors&&In(e.accessors,"accessors",s),e.meshes&&In(e.meshes,"meshes",s),e.lights&&In(e.lights,"lights",s),e.cameras&&In(e.cameras,"cameras",s),e.nodes&&In(e.nodes,"nodes",s),e.images&&In(e.images,"images",s),e.textures&&In(e.textures,"textures",s),e.shaders&&((e,t)=>{for(const n in e){const s=e[n];t.shaders[n]=s,t.shaderscount++}})(e.shaders,s),e.programs&&In(e.programs,"programs",s),e.samplers&&In(e.samplers,"samplers",s),e.techniques&&In(e.techniques,"techniques",s),e.materials&&In(e.materials,"materials",s),e.animations&&In(e.animations,"animations",s),e.skins&&In(e.skins,"skins",s),e.scenes&&(s.scenes=e.scenes),e.scene&&e.scenes&&(s.currentScene=e.scenes[e.scene]),s}static LoadBufferAsync(e,n,s,o,r){const i=e.buffers[n];t.Tools.IsBase64(i.uri)?setTimeout(()=>s(new Uint8Array(t.Tools.DecodeBase64(i.uri)))):t.Tools.LoadFile(e.rootUrl+i.uri,e=>s(new Uint8Array(e)),r,void 0,!0,e=>{e&&o(e.status+" "+e.statusText)})}static LoadTextureBufferAsync(e,n,s,o){const r=e.textures[n];if(!r||!r.source)return void o("");if(r.babylonTexture)return void s(null);const i=e.images[r.source];t.Tools.IsBase64(i.uri)?setTimeout(()=>s(new Uint8Array(t.Tools.DecodeBase64(i.uri)))):t.Tools.LoadFile(e.rootUrl+i.uri,e=>s(new Uint8Array(e)),void 0,void 0,!0,e=>{e&&o(e.status+" "+e.statusText)})}static CreateTextureAsync(e,n,s,o){const r=e.textures[n];if(r.babylonTexture)return void o(r.babylonTexture);const i=e.samplers[r.sampler],a=i.minFilter===bn.NEAREST_MIPMAP_NEAREST||i.minFilter===bn.NEAREST_MIPMAP_LINEAR||i.minFilter===bn.LINEAR_MIPMAP_NEAREST||i.minFilter===bn.LINEAR_MIPMAP_LINEAR,l=t.Texture.BILINEAR_SAMPLINGMODE,u=null==s?new Blob:new Blob([t.GetBlobBufferSource(s)]),c=URL.createObjectURL(u),d=()=>URL.revokeObjectURL(c),h=new t.Texture(c,e.scene,!a,!0,l,d,d);void 0!==i.wrapS&&(h.wrapU=Cn.GetWrapMode(i.wrapS)),void 0!==i.wrapT&&(h.wrapV=Cn.GetWrapMode(i.wrapT)),h.name=n,r.babylonTexture=h,o(h)}static LoadShaderStringAsync(e,n,s,o){const r=e.shaders[n];if(t.Tools.IsBase64(r.uri)){const e=atob(r.uri.split(",")[1]);s&&s(e)}else t.Tools.LoadFile(e.rootUrl+r.uri,s,void 0,void 0,!1,e=>{e&&o&&o(e.status+" "+e.statusText)})}static LoadMaterialAsync(e,n,s,o){const r=e.materials[n];if(!r.technique)return void(o&&o("No technique found."));const i=e.techniques[r.technique];if(!i){e.scene._blockEntityCollection=!!e.assetContainer;const o=new t.StandardMaterial(n,e.scene);return o._parentContainer=e.assetContainer,e.scene._blockEntityCollection=!1,o.diffuseColor=new t.Color3(.5,.5,.5),o.sideOrientation=t.Material.CounterClockWiseSideOrientation,void s(o)}const a=e.programs[i.program],l=i.states,u=t.Effect.ShadersStore[a.vertexShader+"VertexShader"],c=t.Effect.ShadersStore[a.fragmentShader+"PixelShader"];let d="",h="";const m=new Rn(u),f=new Rn(c),p={},_=[],g=[],y=[];for(const e in i.uniforms){const t=i.uniforms[e],n=i.parameters[t];if(p[e]=n,!n.semantic||n.node||n.source)n.type===yn.SAMPLER_2D?y.push(e):_.push(e);else{const t=Sn.indexOf(n.semantic);-1!==t?(_.push(On[t]),delete p[e]):_.push(e)}}for(const e in i.attributes){const t=i.attributes[e],n=i.parameters[t];if(n.semantic){const e=Pn(n);e&&g.push(e)}}for(;!m.isEnd()&&m.getNextToken();){if(m.currentToken!==Mn.IDENTIFIER){d+=m.currentString;continue}let e=!1;for(const t in i.attributes){const n=i.attributes[t],s=i.parameters[n];if(m.currentIdentifier===t&&s.semantic){d+=Pn(s),e=!0;break}}e||(d+=qn(m,i,p))}for(;!f.isEnd()&&f.getNextToken();)f.currentToken===Mn.IDENTIFIER?h+=qn(f,i,p):h+=f.currentString;const v={vertex:a.vertexShader+n,fragment:a.fragmentShader+n},b={attributes:g,uniforms:_,samplers:y,needAlphaBlending:l&&l.enable&&-1!==l.enable.indexOf(3042)};t.Effect.ShadersStore[a.vertexShader+n+"VertexShader"]=d,t.Effect.ShadersStore[a.fragmentShader+n+"PixelShader"]=h;const x=new t.ShaderMaterial(n,e.scene,v,b);if(x.onError=((e,t,n)=>(s,o)=>{t.dispose(!0),n("Cannot compile program named "+e.name+". Error: "+o+". Default material will be applied")})(a,x,o),x.onCompiled=((e,t,n,s,o,r)=>i=>{((e,t,n,s,o)=>{const r=s.values||n.parameters,i=n.uniforms;for(const n in o){const a=o[n],l=a.type;let u=r[i[n]];if(void 0===u&&(u=a.value),!u)continue;const c=e=>n=>{a.value&&e&&(t.setTexture(e,n),delete o[e])};l===yn.SAMPLER_2D?Xn.LoadTextureAsync(e,s.values?u:a.value,c(n),()=>c(null)):a.value&&Cn.SetUniform(t,n,s.values?u:a.value,l)&&delete o[n]}})(e,t,n,s,o),t.onBind=i=>{((e,t,n,s,o,r,i)=>{const a=r.values||o.parameters;for(const i in n){const l=n[i],u=l.type;if(u===yn.FLOAT_MAT2||u===yn.FLOAT_MAT3||u===yn.FLOAT_MAT4)if(!l.semantic||l.source||l.node){if(l.semantic&&(l.source||l.node)){let e=t.scene.getNodeByName(l.source||l.node||"");if(null===e&&(e=t.scene.getNodeById(l.source||l.node||"")),null===e)continue;Cn.SetMatrix(t.scene,e,l,i,s.getEffect())}}else Cn.SetMatrix(t.scene,e,l,i,s.getEffect());else{const e=a[o.uniforms[i]];if(!e)continue;if(u===yn.SAMPLER_2D){const n=t.textures[r.values?e:l.value].babylonTexture;if(null==n)continue;s.getEffect().setTexture(i,n)}else Cn.SetUniform(s.getEffect(),i,e,u)}}i(s)})(i,e,o,t,n,s,r)}})(e,x,i,r,p,s),x.sideOrientation=t.Material.CounterClockWiseSideOrientation,l&&l.functions){const e=l.functions;e.cullFace&&e.cullFace[0]!==Tn.BACK&&(x.backFaceCulling=!1);const n=e.blendFuncSeparate;n&&(n[0]===An.SRC_ALPHA&&n[1]===An.ONE_MINUS_SRC_ALPHA&&n[2]===An.ONE&&n[3]===An.ONE?x.alphaMode=t.Constants.ALPHA_COMBINE:n[0]===An.ONE&&n[1]===An.ONE&&n[2]===An.ZERO&&n[3]===An.ONE?x.alphaMode=t.Constants.ALPHA_ONEONE:n[0]===An.SRC_ALPHA&&n[1]===An.ONE&&n[2]===An.ZERO&&n[3]===An.ONE?x.alphaMode=t.Constants.ALPHA_ADD:n[0]===An.ZERO&&n[1]===An.ONE_MINUS_SRC_COLOR&&n[2]===An.ONE&&n[3]===An.ONE?x.alphaMode=t.Constants.ALPHA_SUBTRACT:n[0]===An.DST_COLOR&&n[1]===An.ZERO&&n[2]===An.ONE&&n[3]===An.ONE?x.alphaMode=t.Constants.ALPHA_MULTIPLY:n[0]===An.SRC_ALPHA&&n[1]===An.ONE_MINUS_SRC_COLOR&&n[2]===An.ONE&&n[3]===An.ONE&&(x.alphaMode=t.Constants.ALPHA_MAXIMIZED))}}}let jn=class e{static RegisterExtension(n){e.Extensions[n.name]?t.Tools.Error('Tool with the same name "'+n.name+'" already exists'):e.Extensions[n.name]=n}dispose(){}_importMeshAsync(e,n,s,o,r,i,a,l){return n.useRightHandedSystem=!0,Xn.LoadRuntimeAsync(n,s,o,n=>{n.assetContainer=r,n.importOnlyMeshes=!0,""===e?n.importMeshesNames=[]:"string"==typeof e?n.importMeshesNames=[e]:!e||e instanceof Array?(n.importMeshesNames=[],t.Tools.Warn("Argument meshesNames must be of type string or string[]")):n.importMeshesNames=[e],this._createNodes(n);const s=[],o=[];for(const e in n.nodes){const o=n.nodes[e];o.babylonNode instanceof t.AbstractMesh&&s.push(o.babylonNode)}for(const e in n.skins){const s=n.skins[e];s.babylonSkeleton instanceof t.Skeleton&&o.push(s.babylonSkeleton)}this._loadBuffersAsync(n,()=>{this._loadShadersAsync(n,()=>{Wn(n),Un(n),!mn.IncrementalLoading&&i&&i(s,o)})}),mn.IncrementalLoading&&i&&i(s,o)},l),!0}importMeshAsync(e,t,n,s,o,r){return new Promise((i,a)=>{this._importMeshAsync(e,t,s,o,n,(e,t)=>{i({meshes:e,particleSystems:[],skeletons:t,animationGroups:[],lights:[],transformNodes:[],geometries:[],spriteManagers:[]})},r,e=>{a(new Error(e))})})}_loadAsync(e,t,n,s,o,r){e.useRightHandedSystem=!0,Xn.LoadRuntimeAsync(e,t,n,e=>{Xn.LoadRuntimeExtensionsAsync(e,()=>{this._createNodes(e),this._loadBuffersAsync(e,()=>{this._loadShadersAsync(e,()=>{Wn(e),Un(e),mn.IncrementalLoading||s()})}),mn.IncrementalLoading&&s()},r)},r)}loadAsync(e,t,n,s){return b(this,void 0,void 0,function*(){return yield new Promise((o,r)=>{this._loadAsync(e,t,n,()=>{o()},s,e=>{r(new Error(e))})})})}_loadShadersAsync(e,n){let s=!1;const o=(s,o)=>{Xn.LoadShaderStringAsync(e,s,r=>{r instanceof ArrayBuffer||(e.loadedShaderCount++,r&&(t.Effect.ShadersStore[s+(o.type===gn.VERTEX?"VertexShader":"PixelShader")]=r),e.loadedShaderCount===e.shaderscount&&n())},()=>{t.Tools.Error("Error when loading shader program named "+s+" located at "+o.uri)})};for(const n in e.shaders){s=!0;const r=e.shaders[n];r?o.bind(this,n,r)():t.Tools.Error("No shader named: "+n)}s||n()}_loadBuffersAsync(e,n){let s=!1;const o=(s,o)=>{Xn.LoadBufferAsync(e,s,r=>{e.loadedBufferCount++,r&&(r.byteLength!=e.buffers[s].byteLength&&t.Tools.Error("Buffer named "+s+" is length "+r.byteLength+". Expected: "+o.byteLength),e.loadedBufferViews[s]=r),e.loadedBufferCount===e.buffersCount&&n()},()=>{t.Tools.Error("Error when loading buffer named "+s+" located at "+o.uri)})};for(const n in e.buffers){s=!0;const r=e.buffers[n];r?o.bind(this,n,r)():t.Tools.Error("No buffer named: "+n)}s||n()}_createNodes(e){let t=e.currentScene;if(t)for(let n=0;n<t.nodes.length;n++)$n(e,t.nodes[n],null);else for(const n in e.scenes){t=e.scenes[n];for(let n=0;n<t.nodes.length;n++)$n(e,t.nodes[n],null)}}};jn.Extensions={};class Xn{constructor(e){this._name=e}get name(){return this._name}loadRuntimeAsync(e,t,n,s,o){return!1}loadRuntimeExtensionsAsync(e,t,n){return!1}loadBufferAsync(e,t,n,s,o){return!1}loadTextureBufferAsync(e,t,n,s){return!1}createTextureAsync(e,t,n,s,o){return!1}loadShaderStringAsync(e,t,n,s){return!1}loadMaterialAsync(e,t,n,s){return!1}static LoadRuntimeAsync(e,t,n,s,o){Xn._ApplyExtensions(r=>r.loadRuntimeAsync(e,t,n,s,o),()=>{setTimeout(()=>{s&&s(zn.CreateRuntime(t.json,e,n))})})}static LoadRuntimeExtensionsAsync(e,t,n){Xn._ApplyExtensions(s=>s.loadRuntimeExtensionsAsync(e,t,n),()=>{setTimeout(()=>{t()})})}static LoadBufferAsync(e,t,n,s,o){Xn._ApplyExtensions(r=>r.loadBufferAsync(e,t,n,s,o),()=>{zn.LoadBufferAsync(e,t,n,s,o)})}static LoadTextureAsync(e,t,n,s){Xn._LoadTextureBufferAsync(e,t,o=>{o&&Xn._CreateTextureAsync(e,t,o,n,s)},s)}static LoadShaderStringAsync(e,t,n,s){Xn._ApplyExtensions(o=>o.loadShaderStringAsync(e,t,n,s),()=>{zn.LoadShaderStringAsync(e,t,n,s)})}static LoadMaterialAsync(e,t,n,s){Xn._ApplyExtensions(o=>o.loadMaterialAsync(e,t,n,s),()=>{zn.LoadMaterialAsync(e,t,n,s)})}static _LoadTextureBufferAsync(e,t,n,s){Xn._ApplyExtensions(o=>o.loadTextureBufferAsync(e,t,n,s),()=>{zn.LoadTextureBufferAsync(e,t,n,s)})}static _CreateTextureAsync(e,t,n,s,o){Xn._ApplyExtensions(r=>r.createTextureAsync(e,t,n,s,o),()=>{zn.CreateTextureAsync(e,t,n,s)})}static _ApplyExtensions(e,t){for(const t in jn.Extensions)if(e(jn.Extensions[t]))return;t()}}mn._CreateGLTF1Loader=()=>new jn;class Yn extends Xn{constructor(){super("KHR_binary_glTF")}loadRuntimeAsync(e,t,n,s){const o=t.json.extensionsUsed;return!(!o||-1===o.indexOf(this.name)||!t.bin||(this._bin=t.bin,s(zn.CreateRuntime(t.json,e,n)),0))}loadBufferAsync(e,t,n,s){return-1!==e.extensionsUsed.indexOf(this.name)&&"binary_glTF"===t&&(this._bin.readAsync(0,this._bin.byteLength).then(n,e=>s(e.message)),!0)}loadTextureBufferAsync(e,t,n){const s=e.textures[t],o=e.images[s.source];if(!o.extensions||!(this.name in o.extensions))return!1;const r=o.extensions[this.name],i=e.bufferViews[r.bufferView];return n(Cn.GetBufferFromBufferView(e,i,0,i.byteLength,_n.UNSIGNED_BYTE)),!0}loadShaderStringAsync(e,t,n){const s=e.shaders[t];if(!s.extensions||!(this.name in s.extensions))return!1;const o=s.extensions[this.name],r=e.bufferViews[o.bufferView],i=Cn.GetBufferFromBufferView(e,r,0,r.byteLength,_n.UNSIGNED_BYTE);return setTimeout(()=>{const e=Cn.DecodeBufferToText(i);n(e)}),!0}}jn.RegisterExtension(new Yn);class Qn extends Xn{constructor(){super("KHR_materials_common")}loadRuntimeExtensionsAsync(e){if(!e.extensions)return!1;const n=e.extensions[this.name];if(!n)return!1;const s=n.lights;if(s)for(const n in s){const o=s[n];switch(o.type){case"ambient":{const n=new t.HemisphericLight(o.name,new t.Vector3(0,1,0),e.scene),s=o.ambient;s&&(n.diffuse=t.Color3.FromArray(s.color||[1,1,1]));break}case"point":{const n=new t.PointLight(o.name,new t.Vector3(10,10,10),e.scene),s=o.point;s&&(n.diffuse=t.Color3.FromArray(s.color||[1,1,1]));break}case"directional":{const n=new t.DirectionalLight(o.name,new t.Vector3(0,-1,0),e.scene),s=o.directional;s&&(n.diffuse=t.Color3.FromArray(s.color||[1,1,1]));break}case"spot":{const n=o.spot;n&&(new t.SpotLight(o.name,new t.Vector3(0,10,0),new t.Vector3(0,-1,0),n.fallOffAngle||Math.PI,n.fallOffExponent||0,e.scene).diffuse=t.Color3.FromArray(n.color||[1,1,1]));break}default:t.Tools.Warn('GLTF Material Common extension: light type "'+o.type+"” not supported")}}return!1}loadMaterialAsync(e,n,s,o){const r=e.materials[n];if(!r||!r.extensions)return!1;const i=r.extensions[this.name];if(!i)return!1;const a=new t.StandardMaterial(n,e.scene);return a.sideOrientation=t.Material.CounterClockWiseSideOrientation,"CONSTANT"===i.technique&&(a.disableLighting=!0),a.backFaceCulling=void 0!==i.doubleSided&&!i.doubleSided,a.alpha=void 0===i.values.transparency?1:i.values.transparency,a.specularPower=void 0===i.values.shininess?0:i.values.shininess,"string"==typeof i.values.ambient?this._loadTexture(e,i.values.ambient,a,"ambientTexture",o):a.ambientColor=t.Color3.FromArray(i.values.ambient||[0,0,0]),"string"==typeof i.values.diffuse?this._loadTexture(e,i.values.diffuse,a,"diffuseTexture",o):a.diffuseColor=t.Color3.FromArray(i.values.diffuse||[0,0,0]),"string"==typeof i.values.emission?this._loadTexture(e,i.values.emission,a,"emissiveTexture",o):a.emissiveColor=t.Color3.FromArray(i.values.emission||[0,0,0]),"string"==typeof i.values.specular?this._loadTexture(e,i.values.specular,a,"specularTexture",o):a.specularColor=t.Color3.FromArray(i.values.specular||[0,0,0]),!0}_loadTexture(e,t,n,s,o){zn.LoadTextureBufferAsync(e,t,o=>{zn.CreateTextureAsync(e,t,o,e=>n[s]=e)},o)}}jn.RegisterExtension(new Qn);var Zn={__proto__:null,get EBlendingFunction(){return An},get EComponentType(){return _n},get ECullingType(){return Tn},get EParameterType(){return yn},get EShaderType(){return gn},get ETextureFilterType(){return bn},get ETextureFormat(){return xn},get ETextureWrapMode(){return vn},GLTFBinaryExtension:Yn,GLTFLoader:jn,GLTFLoaderBase:zn,GLTFLoaderExtension:Xn,GLTFMaterialsCommonExtension:Qn,GLTFUtils:Cn};const Jn=new Map,es=Jn;function ts(e,n,s){ns(e)&&t.Logger.Warn(`Extension with the name '${e}' already exists`),Jn.set(e,{isGLTFExtension:n,factory:s})}function ns(e){return Jn.delete(e)}const ss=[{regex:new RegExp("^/nodes/\\d+/extensions/")},{regex:new RegExp("^/animations/\\d+/extensions/")},{regex:new RegExp("^/nodes/\\d+/weights")},{regex:new RegExp("^/meshes/\\d+/weights")},{regex:new RegExp("/extensions/KHR_texture_transform/")}];class os{constructor(e,t){this._gltf=e,this._infoTree=t}convert(e){let t,n=this._gltf,s=this._infoTree;if(!e.startsWith("/"))throw new Error("Path must start with a /");const o=e.split("/");if(o.shift(),o[o.length-1].includes(".length")){const e=o[o.length-1].split(".");o.pop(),o.push(...e)}let r=!1;for(const i of o)if("length"===i){if(!s.length)throw s.__array__?new Error(`Path ${e} is invalid - no length accessor`):new Error(`Path ${e} is invalid`);s=s.length,void 0!==n&&(t=n)}else{if(s.__ignoreObjectTree__&&(r=!0),s.__array__)s=s.__array__;else if(s=s[i],!s)throw new Error(`Path ${e} is invalid`);if(s.__passThroughTarget__)r=!0;else if(r){const e=/^\d+$/.test(i)?parseInt(i,10):NaN;if(!isNaN(e)&&"function"==typeof s.get){const t=s;s=Object.assign({},t),s.get=(n,s,...o)=>t.get(n,e,...o),"function"==typeof t.set&&(s.set=(n,s,o,...r)=>t.set(n,s,e,...r)),"function"==typeof t.getTarget&&(s.getTarget=(n,s,...o)=>t.getTarget(n,e,...o))}}else if(void 0===n){if(!ss.find(t=>t.regex.test(e)))throw new Error(`Path ${e} is invalid`)}else n=null==n?void 0:n[i];s.__target__&&void 0!==n&&(t=n)}return{object:t,info:s}}}function rs(e,n){return{type:"FlowGraphInteger",get:n=>{const s=e(n);return void 0===s?void 0:t.FlowGraphInteger.FromValue(s)},getTarget:n,getPropertyName:[()=>"length"]}}const is={length:rs(e=>e.length,e=>e.map(e=>e._babylonTransformNode)),__array__:{__target__:!0,translation:{type:"Vector3",get:e=>{var t;return null===(t=e._babylonTransformNode)||void 0===t?void 0:t.position},set:(e,t)=>{var n;return null===(n=t._babylonTransformNode)||void 0===n?void 0:n.position.copyFrom(e)},getTarget:e=>e._babylonTransformNode,getPropertyName:[()=>"position"]},rotation:{type:"Quaternion",get:e=>{var t;return null===(t=e._babylonTransformNode)||void 0===t?void 0:t.rotationQuaternion},set:(e,t)=>{var n,s;return null===(s=null===(n=t._babylonTransformNode)||void 0===n?void 0:n.rotationQuaternion)||void 0===s?void 0:s.copyFrom(e)},getTarget:e=>e._babylonTransformNode,getPropertyName:[()=>"rotationQuaternion"]},scale:{type:"Vector3",get:e=>{var t;return null===(t=e._babylonTransformNode)||void 0===t?void 0:t.scaling},set:(e,t)=>{var n;return null===(n=t._babylonTransformNode)||void 0===n?void 0:n.scaling.copyFrom(e)},getTarget:e=>e._babylonTransformNode,getPropertyName:[()=>"scaling"]},weights:{__passThroughTarget__:!0,length:rs(e=>{const t=ds(e);return t?t.mtm.numTargets:void 0!==(null==e?void 0:e.mesh)?0:void 0},e=>null==e?void 0:e._babylonTransformNode),__array__:{__target__:!0,type:"number",get:(e,t)=>{const n=ds(e);if(n&&void 0!==t&&t>=0&&t<n.mtm.numTargets)return hs(n.mtm.getTarget(t).influence)},set:(e,t,n)=>{var s;const o="number"==typeof e?e:"number"==typeof(null==e?void 0:e.value)?e.value:e,r=ds(t);if(!(!r||void 0===n||n<0||n>=r.mtm.numTargets))for(const e of r.meshes){const t=null===(s=e.morphTargetManager)||void 0===s?void 0:s.getTarget(n);t&&(t.influence=o)}},getTarget:(e,t)=>{const n=ds(e);return n&&void 0!==t&&t>=0&&t<n.mtm.numTargets?n.mtm.getTarget(t):null==e?void 0:e._babylonTransformNode},getPropertyName:[()=>"influence"]},type:"number[]",get:e=>{const t=ds(e);if(!t)return[];const n=[];for(let e=0;e<t.mtm.numTargets;e++)n.push(hs(t.mtm.getTarget(e).influence));return n},getTarget:e=>null==e?void 0:e._babylonTransformNode,getPropertyName:[()=>"influence"]},matrix:{type:"Matrix",get:e=>{var n,s,o;return t.Matrix.Compose(null===(n=e._babylonTransformNode)||void 0===n?void 0:n.scaling,null===(s=e._babylonTransformNode)||void 0===s?void 0:s.rotationQuaternion,null===(o=e._babylonTransformNode)||void 0===o?void 0:o.position)},getTarget:e=>e._babylonTransformNode,isReadOnly:!0},globalMatrix:{type:"Matrix",get:e=>{var n,s,o,r,i,a,l;const u=t.Matrix.Identity();let c=e.parent;for(;c&&c.parent;)c=c.parent;const d=(null===(n=e._babylonTransformNode)||void 0===n?void 0:n.position._isDirty)||(null===(o=null===(s=e._babylonTransformNode)||void 0===s?void 0:s.rotationQuaternion)||void 0===o?void 0:o._isDirty)||(null===(r=e._babylonTransformNode)||void 0===r?void 0:r.scaling._isDirty);if(c){const t=null===(i=c._babylonTransformNode)||void 0===i?void 0:i.computeWorldMatrix(!0).invert();t&&(null===(l=null===(a=e._babylonTransformNode)||void 0===a?void 0:a.computeWorldMatrix(d))||void 0===l||l.multiplyToRef(t,u))}else e._babylonTransformNode&&u.copyFrom(e._babylonTransformNode.computeWorldMatrix(d));return u},getTarget:e=>e._babylonTransformNode,isReadOnly:!0},camera:{type:"string",get:e=>void 0!==e.camera?`/cameras/${e.camera}`:"",getTarget:e=>e,isReadOnly:!0},mesh:{type:"string",get:e=>void 0!==e.mesh?`/meshes/${e.mesh}`:"",getTarget:e=>e,isReadOnly:!0},skin:{type:"string",get:e=>void 0!==e.skin?`/skins/${e.skin}`:"",getTarget:e=>e,isReadOnly:!0},parent:{type:"string",get:e=>e.parent&&void 0!==e.parent.index?`/nodes/${e.parent.index}`:"",getTarget:e=>e,isReadOnly:!0},children:{length:rs(e=>{var t;return null!==(t=null==e?void 0:e.length)&&void 0!==t?t:0},e=>null!=e?e:[]),__array__:{__target__:!0,type:"string",get:e=>"number"==typeof e?`/nodes/${e}`:"",getTarget:()=>({__nodeIndex:!0}),isReadOnly:!0}},extensions:{EXT_lights_ies:{multiplier:{type:"number",get:e=>{var n,s;return null===(s=null===(n=e._babylonTransformNode)||void 0===n?void 0:n.getChildren(e=>e instanceof t.SpotLight,!0)[0])||void 0===s?void 0:s.intensity},getTarget:e=>{var n;return null===(n=e._babylonTransformNode)||void 0===n?void 0:n.getChildren(e=>e instanceof t.SpotLight,!0)[0]},set:(e,n)=>{if(n._babylonTransformNode){const s=n._babylonTransformNode.getChildren(e=>e instanceof t.SpotLight,!0)[0];s&&(s.intensity=e)}}},color:{type:"Color3",get:e=>{var n,s;return null===(s=null===(n=e._babylonTransformNode)||void 0===n?void 0:n.getChildren(e=>e instanceof t.SpotLight,!0)[0])||void 0===s?void 0:s.diffuse},getTarget:e=>{var n;return null===(n=e._babylonTransformNode)||void 0===n?void 0:n.getChildren(e=>e instanceof t.SpotLight,!0)[0]},set:(e,n)=>{if(n._babylonTransformNode){const s=n._babylonTransformNode.getChildren(e=>e instanceof t.SpotLight,!0)[0];s&&(s.diffuse=e)}}}},KHR_node_visibility:{visible:{type:"boolean",get:e=>!!e._primitiveBabylonMeshes&&e._primitiveBabylonMeshes[0].isVisible,getTarget:()=>{},set:(e,t)=>{t._primitiveBabylonMeshes&&t._primitiveBabylonMeshes.forEach(t=>t.isVisible=e)}}}}}},as={length:rs(e=>e.length,e=>e.map(e=>e._babylonAnimationGroup)),__array__:{__target__:!0,type:"string",get:e=>e&&"number"==typeof e.index?`/animations/${e.index}`:"",getTarget:e=>e._babylonAnimationGroup,isReadOnly:!0}},ls={length:rs(e=>e.length,e=>e.map(e=>{var t;return null===(t=e.primitives[0]._instanceData)||void 0===t?void 0:t.babylonSourceMesh})),__array__:{__target__:!0,primitives:{length:rs(e=>{var t;return null!==(t=null==e?void 0:e.length)&&void 0!==t?t:0},e=>null!=e?e:[]),__array__:{__target__:!0,material:{type:"string",get:e=>void 0!==e.material?`/materials/${e.material}`:"",getTarget:e=>e,isReadOnly:!0}}},weights:{length:rs(e=>{var t;return null!==(t=null==e?void 0:e.length)&&void 0!==t?t:0},e=>null!=e?e:[]),__array__:{__target__:!0,type:"number",get:e=>e,getTarget:()=>({__weightValue:!0}),isReadOnly:!0}}}};function us(e,t,n,s){const o=cs(e);return s?o[n][s]:o[n]}function cs(e,n,s){var o,r,i;return null===(i=null===(o=e._data)||void 0===o?void 0:o[null!==(r=null==s?void 0:s.fillMode)&&void 0!==r?r:t.Constants.MATERIAL_TriangleFillMode])||void 0===i?void 0:i.babylonMaterial}function ds(e){var t,n,s,o;const r=null==e?void 0:e._babylonTransformNode;if(!r)return;const i=function(e){var t;const n=null==e?void 0:e._babylonTransformNode;if(!n)return;if(n.morphTargetManager)return n.morphTargetManager;const s=e._primitiveBabylonMeshes;if(s)for(const e of s){if(null==e?void 0:e.morphTargetManager)return e.morphTargetManager;if(null===(t=null==e?void 0:e.sourceMesh)||void 0===t?void 0:t.morphTargetManager)return e.sourceMesh.morphTargetManager}}(e);if(i&&e._primitiveBabylonMeshes&&e._primitiveBabylonMeshes.length>0)return{mtm:i,meshes:e._primitiveBabylonMeshes};const a=r.getDescendants(!1);for(const e of a){const r=e,i=null!==(t=r.morphTargetManager)&&void 0!==t?t:null===(n=r.sourceMesh)||void 0===n?void 0:n.morphTargetManager;if(!i)continue;const a=[],l=r.parent;if(l)for(const e of l.getChildMeshes(!0))(null!==(s=e.morphTargetManager)&&void 0!==s?s:null===(o=e.sourceMesh)||void 0===o?void 0:o.morphTargetManager)===i&&a.push(e);return 0===a.length&&a.push(r),{mtm:i,meshes:a}}}function hs(e){return Number.isFinite(e)?parseFloat(e.toPrecision(7)):e}function ms(e,t,n){if(!e)return;let s=e.extensions;if(!s){if(!n)return;s={},e.extensions=s}let o=s[t.extensionKey];if(!o){if(!n)return;o={},s[t.extensionKey]=o}for(const e of t.texturePath){let t=o[e];if(!t){if(!n)return;t={},o[e]=t}o=t}if(!o.extensions){if(!n)return;o.extensions={}}let r=o.extensions.KHR_texture_transform;if(!r){if(!n)return;r={},o.extensions.KHR_texture_transform=r}return r}function fs(e,n,s){return{offset:{componentsCount:2,type:"Vector2",get:(o,r,i)=>{var a,l;const u=us(o,0,e,n);if(u)return new t.Vector2(u.uOffset,u.vOffset);if(s){const e=ms(o,s,!1),n=null==e?void 0:e.offset;return new t.Vector2(null!==(a=null==n?void 0:n[0])&&void 0!==a?a:0,null!==(l=null==n?void 0:n[1])&&void 0!==l?l:0)}return new t.Vector2(0,0)},getTarget:cs,set:(t,o,r,i)=>{const a=us(o,0,e,n);if(a&&(a.uOffset=t.x,a.vOffset=t.y),s){const e=ms(o,s,!0);e&&(e.offset=[t.x,t.y])}},getPropertyName:[()=>`${e}${n?"."+n:""}.uOffset`,()=>`${e}${n?"."+n:""}.vOffset`]},rotation:{type:"number",get:(t,o,r)=>{var i;const a=us(t,0,e,n);if(a)return a.wAng;if(s){const e=ms(t,s,!1);return null!==(i=null==e?void 0:e.rotation)&&void 0!==i?i:0}return 0},getTarget:cs,set:(t,o,r,i)=>{const a=us(o,0,e,n);if(a&&(a.wAng=t),s){const e=ms(o,s,!0);e&&(e.rotation=t)}},getPropertyName:[()=>`${e}${n?"."+n:""}.wAng`]},scale:{componentsCount:2,type:"Vector2",get:(o,r,i)=>{var a,l;const u=us(o,0,e,n);if(u)return new t.Vector2(u.uScale,u.vScale);if(s){const e=ms(o,s,!1),n=null==e?void 0:e.scale;return new t.Vector2(null!==(a=null==n?void 0:n[0])&&void 0!==a?a:1,null!==(l=null==n?void 0:n[1])&&void 0!==l?l:1)}return new t.Vector2(1,1)},getTarget:cs,set:(t,o,r,i)=>{const a=us(o,0,e,n);if(a&&(a.uScale=t.x,a.vScale=t.y),s){const e=ms(o,s,!0);e&&(e.scale=[t.x,t.y])}},getPropertyName:[()=>`${e}${n?"."+n:""}.uScale`,()=>`${e}${n?"."+n:""}.vScale`]}}}const ps={scene:{__target__:!0,type:"number",get:e=>null!=e?e:0,getTarget:()=>({__gltfRoot:!0}),isReadOnly:!0,getPropertyName:[()=>"scene"]},cameras:{length:rs(e=>e.length,e=>e.map(e=>e._babylonCamera)),__array__:{__target__:!0,orthographic:{xmag:{componentsCount:2,type:"Vector2",get:e=>{var n,s,o,r;return new t.Vector2(null!==(s=null===(n=e._babylonCamera)||void 0===n?void 0:n.orthoLeft)&&void 0!==s?s:0,null!==(r=null===(o=e._babylonCamera)||void 0===o?void 0:o.orthoRight)&&void 0!==r?r: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=>{var n,s,o,r;return new t.Vector2(null!==(s=null===(n=e._babylonCamera)||void 0===n?void 0:n.orthoBottom)&&void 0!==s?s:0,null!==(r=null===(o=e._babylonCamera)||void 0===o?void 0:o.orthoTop)&&void 0!==r?r: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=>{var t;return null===(t=e._babylonCamera)||void 0===t?void 0:t.maxZ},set:(e,t)=>{t._babylonCamera&&(t._babylonCamera.maxZ=e)},getTarget:e=>e,getPropertyName:[()=>"maxZ"]},znear:{type:"number",get:e=>{var t;return null===(t=e._babylonCamera)||void 0===t?void 0:t.minZ},set:(e,t)=>{t._babylonCamera&&(t._babylonCamera.minZ=e)},getTarget:e=>e,getPropertyName:[()=>"minZ"]}},perspective:{aspectRatio:{type:"number",get:e=>{var t;return null===(t=e._babylonCamera)||void 0===t?void 0:t.getEngine().getAspectRatio(e._babylonCamera)},getTarget:e=>e,getPropertyName:[()=>"aspectRatio"],isReadOnly:!0},yfov:{type:"number",get:e=>{var t;return null===(t=e._babylonCamera)||void 0===t?void 0:t.fov},set:(e,t)=>{t._babylonCamera&&(t._babylonCamera.fov=e)},getTarget:e=>e,getPropertyName:[()=>"fov"]},zfar:{type:"number",get:e=>{var t;return null===(t=e._babylonCamera)||void 0===t?void 0:t.maxZ},set:(e,t)=>{t._babylonCamera&&(t._babylonCamera.maxZ=e)},getTarget:e=>e,getPropertyName:[()=>"maxZ"]},znear:{type:"number",get:e=>{var t;return null===(t=e._babylonCamera)||void 0===t?void 0:t.minZ},set:(e,t)=>{t._babylonCamera&&(t._babylonCamera.minZ=e)},getTarget:e=>e,getPropertyName:[()=>"minZ"]}}}},nodes:is,materials:{length:rs(e=>e.length,e=>e.map(e=>{var n,s;return null===(s=null===(n=e._data)||void 0===n?void 0:n[t.Constants.MATERIAL_TriangleFillMode])||void 0===s?void 0:s.babylonMaterial})),__array__:{__target__:!0,doubleSided:{type:"boolean",get:(e,t,n)=>{var s;return!(null===(s=cs(e,0,n))||void 0===s?void 0:s.backFaceCulling)},set:(e,t,n,s)=>{const o=cs(t,0,s);o&&(o.backFaceCulling=!e)},getTarget:(e,t,n)=>cs(e,0,n),getPropertyName:[()=>"backFaceCulling"]},alphaCutoff:{type:"number",get:(e,t,n)=>{var s;return null===(s=cs(e,0,n))||void 0===s?void 0:s.alphaCutOff},set:(e,t,n,s)=>{const o=cs(t,0,s);o&&(o.alphaCutOff=e)},getTarget:(e,t,n)=>cs(e,0,n),getPropertyName:[()=>"alphaCutOff"]},emissiveFactor:{type:"Color3",get:(e,t,n)=>cs(e,0,n).emissiveColor,set:(e,t,n,s)=>cs(t,0,s).emissiveColor.copyFrom(e),getTarget:(e,t,n)=>cs(e,0,n),getPropertyName:[()=>"emissiveColor"]},emissiveTexture:{extensions:{KHR_texture_transform:fs("emissiveTexture")}},normalTexture:{scale:{type:"number",get:(e,t,n)=>{var s;return null===(s=us(e,0,"bumpTexture"))||void 0===s?void 0:s.level},set:(e,t,n,s)=>{const o=us(t,0,"bumpTexture");o&&(o.level=e)},getTarget:(e,t,n)=>cs(e,0,n),getPropertyName:[()=>"level"]},extensions:{KHR_texture_transform:fs("bumpTexture")}},occlusionTexture:{strength:{type:"number",get:(e,t,n)=>cs(e,0,n).ambientTextureStrength,set:(e,t,n,s)=>{const o=cs(t,0,s);o&&(o.ambientTextureStrength=e)},getTarget:(e,t,n)=>cs(e,0,n),getPropertyName:[()=>"ambientTextureStrength"]},extensions:{KHR_texture_transform:fs("ambientTexture")}},pbrMetallicRoughness:{baseColorFactor:{type:"Color4",get:(e,n,s)=>{const o=cs(e,0,s);return t.Color4.FromColor3(o.albedoColor,o.alpha)},set:(e,t,n,s)=>{const o=cs(t,0,s);o.albedoColor.set(e.r,e.g,e.b),o.alpha=e.a},getTarget:(e,t,n)=>cs(e,0,n),getPropertyName:[()=>"albedoColor",()=>"alpha"]},baseColorTexture:{extensions:{KHR_texture_transform:fs("albedoTexture")}},metallicFactor:{type:"number",get:(e,t,n)=>cs(e,0,n).metallic,set:(e,t,n,s)=>{const o=cs(t,0,s);o&&(o.metallic=e)},getTarget:(e,t,n)=>cs(e,0,n),getPropertyName:[()=>"metallic"]},roughnessFactor:{type:"number",get:(e,t,n)=>cs(e,0,n).roughness,set:(e,t,n,s)=>{const o=cs(t,0,s);o&&(o.roughness=e)},getTarget:(e,t,n)=>cs(e,0,n),getPropertyName:[()=>"roughness"]},metallicRoughnessTexture:{extensions:{KHR_texture_transform:fs("metallicTexture")}}},extensions:{KHR_materials_anisotropy:{anisotropyStrength:{type:"number",get:(e,t,n)=>{var s,o;return null===(o=null===(s=cs(e,0,n))||void 0===s?void 0:s.anisotropy)||void 0===o?void 0:o.intensity},set:(e,t,n,s)=>{const o=cs(t,0,s);o&&(o.anisotropy.intensity=e)},getTarget:(e,t,n)=>cs(e,0,n),getPropertyName:[()=>"anisotropy.intensity"]},anisotropyRotation:{type:"number",get:(e,t,n)=>{var s,o;return null===(o=null===(s=cs(e,0,n))||void 0===s?void 0:s.anisotropy)||void 0===o?void 0:o.angle},set:(e,t,n,s)=>{const o=cs(t,0,s);o&&(o.anisotropy.angle=e)},getTarget:(e,t,n)=>cs(e,0,n),getPropertyName:[()=>"anisotropy.angle"]},anisotropyTexture:{extensions:{KHR_texture_transform:fs("anisotropy","texture")}}},KHR_materials_clearcoat:{clearcoatFactor:{type:"number",get:(e,t,n)=>cs(e,0,n).clearCoat.intensity,set:(e,t,n,s)=>{cs(t,0,s).clearCoat.intensity=e},getTarget:(e,t,n)=>cs(e,0,n),getPropertyName:[()=>"clearCoat.intensity"]},clearcoatRoughnessFactor:{type:"number",get:(e,t,n)=>cs(e,0,n).clearCoat.roughness,set:(e,t,n,s)=>{cs(t,0,s).clearCoat.roughness=e},getTarget:(e,t,n)=>cs(e,0,n),getPropertyName:[()=>"clearCoat.roughness"]},clearcoatTexture:{extensions:{KHR_texture_transform:fs("clearCoat","texture")}},clearcoatNormalTexture:{scale:{type:"number",get:(e,t,n)=>{var s;return null===(s=cs(e,0,n).clearCoat.bumpTexture)||void 0===s?void 0:s.level},getTarget:cs,set:(e,t,n,s)=>cs(t,0,s).clearCoat.bumpTexture.level=e},extensions:{KHR_texture_transform:fs("clearCoat","bumpTexture")}},clearcoatRoughnessTexture:{extensions:{KHR_texture_transform:fs("clearCoat","textureRoughness")}}},KHR_materials_dispersion:{dispersion:{type:"number",get:(e,t,n)=>cs(e,0,n).subSurface.dispersion,getTarget:cs,set:(e,t,n,s)=>cs(t,0,s).subSurface.dispersion=e}},KHR_materials_emissive_strength:{emissiveStrength:{type:"number",get:(e,t,n)=>cs(e,0,n).emissiveIntensity,getTarget:cs,set:(e,t,n,s)=>cs(t,0,s).emissiveIntensity=e}},KHR_materials_ior:{ior:{type:"number",get:(e,t,n)=>cs(e,0,n).indexOfRefraction,getTarget:cs,set:(e,t,n,s)=>cs(t,0,s).indexOfRefraction=e}},KHR_materials_iridescence:{iridescenceFactor:{type:"number",get:(e,t,n)=>cs(e,0,n).iridescence.intensity,getTarget:cs,set:(e,t,n,s)=>cs(t,0,s).iridescence.intensity=e},iridescenceIor:{type:"number",get:(e,t,n)=>cs(e,0,n).iridescence.indexOfRefraction,getTarget:cs,set:(e,t,n,s)=>cs(t,0,s).iridescence.indexOfRefraction=e},iridescenceTexture:{extensions:{KHR_texture_transform:fs("iridescence","texture")}},iridescenceThicknessMaximum:{type:"number",get:(e,t,n)=>cs(e,0,n).iridescence.maximumThickness,getTarget:cs,set:(e,t,n,s)=>cs(t,0,s).iridescence.maximumThickness=e},iridescenceThicknessMinimum:{type:"number",get:(e,t,n)=>cs(e,0,n).iridescence.minimumThickness,getTarget:cs,set:(e,t,n,s)=>cs(t,0,s).iridescence.minimumThickness=e},iridescenceThicknessTexture:{extensions:{KHR_texture_transform:fs("iridescence","thicknessTexture")}}},KHR_materials_sheen:{sheenColorFactor:{type:"Color3",get:(e,t,n)=>cs(e,0,n).sheen.color,getTarget:cs,set:(e,t,n,s)=>cs(t,0,s).sheen.color.copyFrom(e)},sheenColorTexture:{extensions:{KHR_texture_transform:fs("sheen","texture")}},sheenRoughnessFactor:{type:"number",get:(e,t,n)=>cs(e,0,n).sheen.intensity,getTarget:cs,set:(e,t,n,s)=>cs(t,0,s).sheen.intensity=e},sheenRoughnessTexture:{extensions:{KHR_texture_transform:fs("sheen","textureRoughness")}}},KHR_materials_specular:{specularFactor:{type:"number",get:(e,t,n)=>cs(e,0,n).metallicF0Factor,getTarget:cs,set:(e,t,n,s)=>cs(t,0,s).metallicF0Factor=e,getPropertyName:[()=>"metallicF0Factor"]},specularColorFactor:{type:"Color3",get:(e,t,n)=>cs(e,0,n).metallicReflectanceColor,getTarget:cs,set:(e,t,n,s)=>cs(t,0,s).metallicReflectanceColor.copyFrom(e),getPropertyName:[()=>"metallicReflectanceColor"]},specularTexture:{extensions:{KHR_texture_transform:fs("metallicReflectanceTexture")}},specularColorTexture:{extensions:{KHR_texture_transform:fs("reflectanceTexture")}}},KHR_materials_transmission:{transmissionFactor:{type:"number",get:(e,t,n)=>cs(e,0,n).subSurface.refractionIntensity,getTarget:cs,set:(e,t,n,s)=>cs(t,0,s).subSurface.refractionIntensity=e,getPropertyName:[()=>"subSurface.refractionIntensity"]},transmissionTexture:{extensions:{KHR_texture_transform:fs("subSurface","refractionIntensityTexture",{extensionKey:"KHR_materials_transmission",texturePath:["transmissionTexture"]})}}},KHR_materials_diffuse_transmission:{diffuseTransmissionFactor:{type:"number",get:(e,t,n)=>cs(e,0,n).subSurface.translucencyIntensity,getTarget:cs,set:(e,t,n,s)=>cs(t,0,s).subSurface.translucencyIntensity=e},diffuseTransmissionTexture:{extensions:{KHR_texture_transform:fs("subSurface","translucencyIntensityTexture",{extensionKey:"KHR_materials_diffuse_transmission",texturePath:["diffuseTransmissionTexture"]})}},diffuseTransmissionColorFactor:{type:"Color3",get:(e,t,n)=>cs(e,0,n).subSurface.translucencyColor,getTarget:cs,set:(e,t,n,s)=>{var o;return e&&(null===(o=cs(t,0,s).subSurface.translucencyColor)||void 0===o?void 0:o.copyFrom(e))}},diffuseTransmissionColorTexture:{extensions:{KHR_texture_transform:fs("subSurface","translucencyColorTexture",{extensionKey:"KHR_materials_diffuse_transmission",texturePath:["diffuseTransmissionColorTexture"]})}}},KHR_materials_volume:{attenuationColor:{type:"Color3",get:(e,t,n)=>cs(e,0,n).subSurface.tintColor,getTarget:cs,set:(e,t,n,s)=>cs(t,0,s).subSurface.tintColor.copyFrom(e)},attenuationDistance:{type:"number",get:(e,t,n)=>cs(e,0,n).subSurface.tintColorAtDistance,getTarget:cs,set:(e,t,n,s)=>cs(t,0,s).subSurface.tintColorAtDistance=e},thicknessFactor:{type:"number",get:(e,t,n)=>cs(e,0,n).subSurface.maximumThickness,getTarget:cs,set:(e,t,n,s)=>cs(t,0,s).subSurface.maximumThickness=e},thicknessTexture:{extensions:{KHR_texture_transform:fs("subSurface","thicknessTexture",{extensionKey:"KHR_materials_volume",texturePath:["thicknessTexture"]})}}}}}},extensions:{KHR_lights_punctual:{lights:{length:rs(e=>e.length,e=>e.map(e=>e._babylonLight)),__array__:{__target__:!0,color:{type:"Color3",get:e=>{var t;return null===(t=e._babylonLight)||void 0===t?void 0:t.diffuse},set:(e,t)=>{var n;return null===(n=t._babylonLight)||void 0===n?void 0:n.diffuse.copyFrom(e)},getTarget:e=>e._babylonLight,getPropertyName:[e=>"diffuse"]},intensity:{type:"number",get:e=>{var t;return null===(t=e._babylonLight)||void 0===t?void 0:t.intensity},set:(e,t)=>t._babylonLight?t._babylonLight.intensity=e:void 0,getTarget:e=>e._babylonLight,getPropertyName:[e=>"intensity"]},range:{type:"number",get:e=>{var t;return null===(t=e._babylonLight)||void 0===t?void 0:t.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=>{var t;return null===(t=e._babylonLight)||void 0===t?void 0:t.innerAngle},set:(e,t)=>t._babylonLight?t._babylonLight.innerAngle=e:void 0,getTarget:e=>e._babylonLight,getPropertyName:[e=>"innerConeAngle"]},outerConeAngle:{type:"number",get:e=>{var t;return null===(t=e._babylonLight)||void 0===t?void 0:t.angle},set:(e,t)=>t._babylonLight?t._babylonLight.angle=e:void 0,getTarget:e=>e._babylonLight,getPropertyName:[e=>"outerConeAngle"]}}}}},EXT_lights_area:{lights:{length:rs(e=>e.length,e=>e.map(e=>e._babylonLight)),__array__:{__target__:!0,color:{type:"Color3",get:e=>{var t;return null===(t=e._babylonLight)||void 0===t?void 0:t.diffuse},set:(e,t)=>{var n;return null===(n=t._babylonLight)||void 0===n?void 0:n.diffuse.copyFrom(e)},getTarget:e=>e._babylonLight,getPropertyName:[e=>"diffuse"]},intensity:{type:"number",get:e=>{var t;return null===(t=e._babylonLight)||void 0===t?void 0:t.intensity},set:(e,t)=>t._babylonLight?t._babylonLight.intensity=e:void 0,getTarget:e=>e._babylonLight,getPropertyName:[e=>"intensity"]},size:{type:"number",get:e=>{var t;return null===(t=e._babylonLight)||void 0===t?void 0:t.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=>{var t,n;return(null===(t=e._babylonLight)||void 0===t?void 0:t.width)/(null===(n=e._babylonLight)||void 0===n?void 0:n.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:rs(e=>e.length,e=>e.map(e=>e._babylonLight))}},EXT_lights_image_based:{lights:{length:rs(e=>e.length,e=>e.map(e=>e._babylonTexture)),__array__:{__target__:!0,intensity:{type:"number",get:e=>{var t;return null===(t=e._babylonTexture)||void 0===t?void 0:t.level},set:(e,t)=>{t._babylonTexture&&(t._babylonTexture.level=e)},getTarget:e=>e._babylonTexture},rotation:{type:"Quaternion",get:e=>{var n;return e._babylonTexture&&t.Quaternion.FromRotationMatrix(null===(n=e._babylonTexture)||void 0===n?void 0:n.getReflectionTextureMatrix())},set:(e,n)=>{var s;n._babylonTexture&&((null===(s=n._babylonTexture.getScene())||void 0===s?void 0:s.useRightHandedSystem)||(e=t.Quaternion.Inverse(e)),t.Matrix.FromQuaternionToRef(e,n._babylonTexture.getReflectionTextureMatrix()))},getTarget:e=>e._babylonTexture}}}}},animations:as,meshes:ls,scenes:{length:rs(e=>e.length,e=>e),__array__:{__target__:!0,nodes:{length:rs(e=>{var t;return null!==(t=null==e?void 0:e.length)&&void 0!==t?t:0},e=>null!=e?e:[]),__array__:{__target__:!0,type:"string",get:e=>"number"==typeof e?`/nodes/${e}`:"",getTarget:()=>({__nodeIndex:!0}),isReadOnly:!0}}}},skins:{length:rs(e=>e.length,e=>e.map(e=>{var t;return null===(t=e._data)||void 0===t?void 0:t.babylonSkeleton})),__array__:{__target__:!0,joints:{length:rs(e=>{var t;return null!==(t=null==e?void 0:e.length)&&void 0!==t?t:0},e=>null!=e?e:[]),__array__:{__target__:!0,type:"string",get:e=>"number"==typeof e?`/nodes/${e}`:"",getTarget:()=>({__nodeIndex:!0}),isReadOnly:!0}},skeleton:{type:"string",get:e=>{const t=e.skeleton;return"number"==typeof t?`/nodes/${t}`:""},getTarget:e=>e,isReadOnly:!0}}}};function _s(e){return new os(e,ps)}function gs(e){const t=e.split("/").map(e=>e.replace(/{}/g,"__array__"));let n=ps;for(const e of t)e&&(n=n[e]);if(n&&n.type&&n.get)return n}function ys(e,t){const n=e.split("/").map(e=>e.replace(/{}/g,"__array__"));let s=ps;for(const e of n)e&&(s=s[e]);s&&s.type&&s.get&&(s.interpolation=t)}function vs(e,t){const n=e.split("/").map(e=>e.replace(/{}/g,"__array__"));let s=ps;for(const e of n)if(e){if(!s[e]){if("?"===e){s.__ignoreObjectTree__=!0;continue}s[e]={},"__array__"===e&&(s[e].__target__=!0)}s=s[e]}Object.assign(s,t)}const bs=new t.Lazy(()=>Promise.resolve(BABYLON)),xs=new t.Lazy(()=>Promise.resolve().then(function(){return Ps}));class Ts{static Get(e,t,n){if(!t||null==n||!t[n])throw new Error(`${e}: Failed to find index (${n})`);return t[n]}static TryGet(e,t){return e&&null!=t&&e[t]?e[t]:null}static Assign(e){if(e)for(let t=0;t<e.length;t++)e[t].index=t}}function As(e){if(e.min&&e.max){const n=e.min,s=e.max,o=t.TmpVectors.Vector3[0].copyFromFloats(n[0],n[1],n[2]),r=t.TmpVectors.Vector3[1].copyFromFloats(s[0],s[1],s[2]);if(e.normalized&&5126!==e.componentType){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}const n=1/t;o.scaleInPlace(n),r.scaleInPlace(n)}return new t.BoundingInfo(o,r)}return null}class Ms{isMatchingMaterialType(e){if(!e)return!1;const t=Array.from(this._pbrMaterialImpls.values());for(const n of t)if(e instanceof n.materialClass)return!0;return!1}static RegisterExtension(e,t){ts(e,!1,t)}static UnregisterExtension(e){return ns(e)}get gltf(){if(!this._gltf)throw new 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 new Error("Scene is not available");return this._babylonScene}get rootBabylonMesh(){return this._rootBabylonMesh}get rootUrl(){return this._rootUrl}constructor(e){this._completePromises=new Array,this._assetContainer=null,this._babylonLights=[],this._disableInstancedMesh=0,this._allMaterialsDirtyRequired=!1,this._skipStartAnimationStep=!1,this._extensions=new Array,this._disposed=!1,this._rootUrl=null,this._fileName=null,this._uniqueRootUrl=null,this._bin=null,this._rootBabylonMesh=null,this._defaultBabylonMaterialData={},this._postSceneLoadActions=new Array,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){const n=Array.from(this._pbrMaterialImpls.values());for(const s of n)if(e instanceof s.materialClass){t=new s.adapterClass(e);break}if(!t)throw new Error("Appropriate material adapter class not found");const s=t;this._materialAdapterCache.set(e,s),this._materialAdapters.add(s)}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())}importMeshAsync(e,t,n,s,o,r){return b(this,arguments,void 0,function*(e,t,n,s,o,r,i=""){return yield Promise.resolve().then(()=>b(this,void 0,void 0,function*(){this._babylonScene=t,this._assetContainer=n,this._loadData(s);let r=null;if(e){const t={};if(this._gltf.nodes)for(const e of this._gltf.nodes)e.name&&(t[e.name]=e.index);r=(e instanceof Array?e:[e]).map(e=>{const n=t[e];if(void 0===n)throw new Error(`Failed to find node '${e}'`);return n})}return yield this._loadAsync(o,i,r,()=>({meshes:this._getMeshes(),particleSystems:[],skeletons:this._getSkeletons(),animationGroups:this._getAnimationGroups(),lights:this._babylonLights,transformNodes:this._getTransformNodes(),geometries:this._getGeometries(),spriteManagers:[]}))}))})}loadAsync(e,t,n,s){return b(this,arguments,void 0,function*(e,t,n,s,o=""){return this._babylonScene=e,this._loadData(t),yield this._loadAsync(n,o,null,()=>{})})}_loadAsync(n,s,o,r){return b(this,void 0,void 0,function*(){return yield Promise.resolve().then(()=>b(this,void 0,void 0,function*(){var i;if(this._rootUrl=n,this._uniqueRootUrl=!n.startsWith("file:")&&s?n:`${n}${t.RandomGUID()}/`,this._fileName=s,this._allMaterialsDirtyRequired=!1,yield this._loadExtensionsAsync(),!this.parent.skipMaterials){const e=this.parent.useOpenPBR||this.isExtensionUsed("KHR_materials_openpbr");let t=!1;this.parent.useOpenPBR?(null===(i=this._gltf.materials)||void 0===i?void 0:i.length)&&this._gltf.materials.some(e=>{var t;return!(null===(t=e.extensions)||void 0===t?void 0:t.KHR_materials_openpbr)})&&(t=!0):t=!0;const n=[];e&&!this._pbrMaterialImpls.has("openpbr")&&n.push(Promise.all([Promise.resolve(BABYLON),Promise.resolve().then(function(){return Ns})]).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([Promise.resolve(BABYLON),Promise.resolve().then(function(){return Ds})]).then(([{PBRMaterial:e,RegisterPbrMaterial:t},{PBRMaterialLoadingAdapter:n}])=>{t(),this._pbrMaterialImpls.set("pbr",{materialClass:e,adapterClass:n})})),yield Promise.all(n)}const a=`${e.GLTFLoaderState[e.GLTFLoaderState.LOADING]} => ${e.GLTFLoaderState[e.GLTFLoaderState.READY]}`,l=`${e.GLTFLoaderState[e.GLTFLoaderState.LOADING]} => ${e.GLTFLoaderState[e.GLTFLoaderState.COMPLETE]}`;this._parent._startPerformanceCounter(a),this._parent._startPerformanceCounter(l),this._parent._setState(e.GLTFLoaderState.LOADING),this._extensionsOnLoading();const u=new Array,c=this._babylonScene.blockMaterialDirtyMechanism;if(this._babylonScene.blockMaterialDirtyMechanism=!0,!this.parent.loadOnlyMaterials)if(o)u.push(this.loadSceneAsync("/nodes",{nodes:o,index:-1}));else if(null!=this._gltf.scene||this._gltf.scenes&&this._gltf.scenes[0]){const e=Ts.Get("/scene",this._gltf.scenes,this._gltf.scene||0);u.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){const n=this._gltf.materials[e],s="/materials/"+e,o=t.Material.TriangleFillMode;u.push(this._loadMaterialAsync(s,n,null,o,()=>{}))}this._allMaterialsDirtyRequired?this._babylonScene.blockMaterialDirtyMechanism=c:this._babylonScene._forceBlockMaterialDirtyMechanism(c),this._parent.compileMaterials&&u.push(this._compileMaterialsAsync()),this._parent.compileShadowGenerators&&u.push(this._compileShadowGeneratorsAsync());const d=Promise.all(u).then(()=>{this._rootBabylonMesh&&this._rootBabylonMesh!==this._parent.customRootNode&&this._rootBabylonMesh.setEnabled(!0);for(const e of this._babylonScene.materials){const t=e;void 0!==t.maxSimultaneousLights&&(t.maxSimultaneousLights=Math.max(t.maxSimultaneousLights,this._babylonScene.lights.length))}for(const e of Array.from(this._materialAdapters))this._completePromises.push(e.finalizeAsync(this));return this._extensionsOnReady(),this._parent._setState(e.GLTFLoaderState.READY),this._skipStartAnimationStep||this._startAnimations(),r()});return yield d.then(n=>(this._parent._endPerformanceCounter(a),t.Tools.SetImmediate(()=>{this._disposed||Promise.all(this._completePromises).then(()=>{this._parent._endPerformanceCounter(l),this._parent._setState(e.GLTFLoaderState.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()})}),n))})).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){const n=this._gltf.buffers;if(n&&n[0]&&!n[0].uri){const s=n[0];(s.byteLength<e.bin.byteLength-3||s.byteLength>e.bin.byteLength)&&t.Logger.Warn(`Binary buffer length (${s.byteLength}) from JSON does not match chunk length (${e.bin.byteLength})`),this._bin=e.bin}else t.Logger.Warn("Unexpected BIN chunk")}}_setupData(){if(Ts.Assign(this._gltf.accessors),Ts.Assign(this._gltf.animations),Ts.Assign(this._gltf.buffers),Ts.Assign(this._gltf.bufferViews),Ts.Assign(this._gltf.cameras),Ts.Assign(this._gltf.images),Ts.Assign(this._gltf.materials),Ts.Assign(this._gltf.meshes),Ts.Assign(this._gltf.nodes),Ts.Assign(this._gltf.samplers),Ts.Assign(this._gltf.scenes),Ts.Assign(this._gltf.skins),Ts.Assign(this._gltf.textures),this._gltf.nodes){const e={};for(const t of this._gltf.nodes)if(t.children)for(const n of t.children)e[n]=t.index;const t=this._createRootNode();for(const n of this._gltf.nodes){const s=e[n.index];n.parent=void 0===s?t:this._gltf.nodes[s]}}}_loadExtensionsAsync(){return b(this,void 0,void 0,function*(){var e;const n=[];if(es.forEach((e,s)=>{var o;!1===(null===(o=this.parent.extensionOptions[s])||void 0===o?void 0:o.enabled)?e.isGLTFExtension&&this.isExtensionUsed(s)&&t.Logger.Warn(`Extension ${s} is used but has been explicitly disabled.`):e.isGLTFExtension&&!this.isExtensionUsed(s)||n.push((()=>b(this,void 0,void 0,function*(){const n=yield e.factory(this);return n.name!==s&&t.Logger.Warn(`The name of the glTF loader extension instance does not match the registered name: ${n.name} !== ${s}`),this._parent.onExtensionLoadedObservable.notifyObservers(n),n}))())}),this._extensions.push(...yield Promise.all(n)),this._extensions.sort((e,t)=>(e.order||Number.MAX_VALUE)-(t.order||Number.MAX_VALUE)),this._parent.onExtensionLoadedObservable.clear(),this._gltf.extensionsRequired)for(const t of this._gltf.extensionsRequired)if(!this._extensions.some(e=>e.name===t&&e.enabled)){if(!1===(null===(e=this.parent.extensionOptions[t])||void 0===e?void 0:e.enabled))throw new Error(`Required extension ${t} is disabled`);throw new Error(`Required extension ${t} is not available`)}})}_createRootNode(){if(void 0!==this._parent.customRootNode)return this._rootBabylonMesh=this._parent.customRootNode,{_babylonTransformNode:null===this._rootBabylonMesh?void 0:this._rootBabylonMesh,index:-1};this._babylonScene._blockEntityCollection=!!this._assetContainer;const n=new t.Mesh("__root__",this._babylonScene);this._rootBabylonMesh=n,this._rootBabylonMesh._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,this._rootBabylonMesh.setEnabled(!1);const s={_babylonTransformNode:this._rootBabylonMesh,index:-1};switch(this._parent.coordinateSystemMode){case e.GLTFLoaderCoordinateSystemMode.AUTO:this._babylonScene.useRightHandedSystem||(s.rotation=[0,1,0,0],s.scale=[1,1,-1],Ms._LoadTransform(s,this._rootBabylonMesh));break;case e.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED:this._babylonScene.useRightHandedSystem=!0;break;default:throw new Error(`Invalid coordinate system mode (${this._parent.coordinateSystemMode})`)}return this._parent.onMeshLoadedObservable.notifyObservers(n),s}loadSceneAsync(e,t){const n=this._extensionsLoadSceneAsync(e,t);if(n)return n;const s=new Array;if(this.logOpen(`${e} ${t.name||""}`),t.nodes)for(const n of t.nodes){const t=Ts.Get(`${e}/nodes/${n}`,this._gltf.nodes,n);s.push(this.loadNodeAsync(`/nodes/${t.index}`,t,e=>{e.parent=this._rootBabylonMesh}))}for(const e of this._postSceneLoadActions)e();return s.push(this._loadAnimationsAsync()),this.logClose(),Promise.all(s).then(()=>{})}_forEachPrimitive(e,t){if(e._primitiveBabylonMeshes)for(const n of e._primitiveBabylonMeshes)t(n)}_getGeometries(){const e=[],t=this._gltf.nodes;if(t)for(const n of t)this._forEachPrimitive(n,t=>{const n=t.geometry;n&&-1===e.indexOf(n)&&e.push(n)});return e}_getMeshes(){const e=[];this._rootBabylonMesh instanceof t.AbstractMesh&&e.push(this._rootBabylonMesh);const n=this._gltf.nodes;if(n)for(const t of n)this._forEachPrimitive(t,t=>{e.push(t)});return e}_getTransformNodes(){const e=[],t=this._gltf.nodes;if(t)for(const n of t)n._babylonTransformNode&&"TransformNode"===n._babylonTransformNode.getClassName()&&e.push(n._babylonTransformNode),n._babylonTransformNodeForSkin&&e.push(n._babylonTransformNodeForSkin);return e}_getSkeletons(){const e=[],t=this._gltf.skins;if(t)for(const n of t)n._data&&e.push(n._data.babylonSkeleton);return e}_getAnimationGroups(){const e=[],t=this._gltf.animations;if(t)for(const n of t)n._babylonAnimationGroup&&e.push(n._babylonAnimationGroup);return e}_startAnimations(){switch(this._parent.animationStartMode){case e.GLTFLoaderAnimationStartMode.NONE:break;case e.GLTFLoaderAnimationStartMode.FIRST:{const e=this._getAnimationGroups();0!==e.length&&e[0].start(!0);break}case e.GLTFLoaderAnimationStartMode.ALL:{const e=this._getAnimationGroups();for(const t of e)t.start(!0);break}default:return void t.Logger.Error(`Invalid animation start mode (${this._parent.animationStartMode})`)}}loadNodeAsync(e,n,s=()=>{}){const o=this._extensionsLoadNodeAsync(e,n,s);if(o)return o;if(n._babylonTransformNode)throw new Error(`${e}: Invalid recursive node hierarchy`);const r=new Array;this.logOpen(`${e} ${n.name||""}`);const i=t=>{if(Ms.AddPointerMetadata(t,e),Ms._LoadTransform(n,t),null!=n.camera){const s=Ts.Get(`${e}/camera`,this._gltf.cameras,n.camera);r.push(this.loadCameraAsync(`/cameras/${s.index}`,s,e=>{e.parent=t,this._babylonScene.useRightHandedSystem||(t.scaling.x=-1)}))}if(n.children)for(const s of n.children){const n=Ts.Get(`${e}/children/${s}`,this._gltf.nodes,s);r.push(this.loadNodeAsync(`/nodes/${n.index}`,n,e=>{e.parent=t}))}s(t)},a=null!=n.mesh,l=this._parent.loadSkins&&null!=n.skin;if(!a||l){const e=n.name||`node${n.index}`;this._babylonScene._blockEntityCollection=!!this._assetContainer;const s=new t.TransformNode(e,this._babylonScene);s._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,null==n.mesh?n._babylonTransformNode=s:n._babylonTransformNodeForSkin=s,i(s)}if(a)if(l){const s=Ts.Get(`${e}/mesh`,this._gltf.meshes,n.mesh);r.push(this._loadMeshAsync(`/meshes/${s.index}`,n,s,s=>{const o=n._babylonTransformNodeForSkin;s.metadata=t.deepMerge(o.metadata,s.metadata||{});const i=Ts.Get(`${e}/skin`,this._gltf.skins,n.skin);r.push(this._loadSkinAsync(`/skins/${i.index}`,n,i,e=>{this._forEachPrimitive(n,t=>{t.skeleton=e}),this._postSceneLoadActions.push(()=>{if(null!=i.skeleton){const e=Ts.Get(`/skins/${i.index}/skeleton`,this._gltf.nodes,i.skeleton).parent;n.index===e.index?s.parent=o.parent:s.parent=e._babylonTransformNode}else s.parent=this._rootBabylonMesh;this._parent.onSkinLoadedObservable.notifyObservers({node:o,skinnedNode:s})})}))}))}else{const t=Ts.Get(`${e}/mesh`,this._gltf.meshes,n.mesh);r.push(this._loadMeshAsync(`/meshes/${t.index}`,n,t,i))}return this.logClose(),Promise.all(r).then(()=>(this._forEachPrimitive(n,e=>{const t=e;!t.isAnInstance&&t.geometry&&t.geometry.useBoundingInfoFromGeometry?e._updateBoundingInfo():e.refreshBoundingInfo(!0,!0)}),n._babylonTransformNode))}_loadMeshAsync(e,n,s,o){const r=s.primitives;if(!r||!r.length)throw new Error(`${e}: Primitives are missing`);null==r[0].index&&Ts.Assign(r);const i=new Array;this.logOpen(`${e} ${s.name||""}`);const a=n.name||`node${n.index}`;if(1===r.length){const t=s.primitives[0];i.push(this._loadMeshPrimitiveAsync(`${e}/primitives/${t.index}`,a,n,s,t,e=>{n._babylonTransformNode=e,n._primitiveBabylonMeshes=[e]}))}else{this._babylonScene._blockEntityCollection=!!this._assetContainer,n._babylonTransformNode=new t.TransformNode(a,this._babylonScene),n._babylonTransformNode._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,n._primitiveBabylonMeshes=[];for(const t of r)i.push(this._loadMeshPrimitiveAsync(`${e}/primitives/${t.index}`,`${a}_primitive${t.index}`,n,s,t,e=>{e.parent=n._babylonTransformNode,n._primitiveBabylonMeshes.push(e)}))}return o(n._babylonTransformNode),this.logClose(),Promise.all(i).then(()=>n._babylonTransformNode)}_loadMeshPrimitiveAsync(e,n,s,o,r,i){const a=this._extensionsLoadMeshPrimitiveAsync(e,n,s,o,r,i);if(a)return a;this.logOpen(`${e}`);const l=0===this._disableInstancedMesh&&this._parent.createInstances&&null==s.skin&&!o.primitives[0].targets;let u,c;if(l&&r._instanceData)this._babylonScene._blockEntityCollection=!!this._assetContainer,u=r._instanceData.babylonSourceMesh.createInstance(n),u._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,c=r._instanceData.promise;else{const i=new Array;this._babylonScene._blockEntityCollection=!!this._assetContainer;const a=new t.Mesh(n,this._babylonScene);if(a._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,a.sideOrientation=this._babylonScene.useRightHandedSystem?t.Material.CounterClockWiseSideOrientation:t.Material.ClockWiseSideOrientation,this._createMorphTargets(e,s,o,r,a),i.push(this._loadVertexDataAsync(e,r,a).then(t=>b(this,void 0,void 0,function*(){return yield this._loadMorphTargetsAsync(e,r,a,t).then(()=>{this._disposed||(this._babylonScene._blockEntityCollection=!!this._assetContainer,t.applyToMesh(a),t._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1)})}))),!this.parent.skipMaterials){const t=Ms._GetDrawMode(e,r.mode);if(null==r.material){let e=this._defaultBabylonMaterialData[t];e||(e=this._createDefaultMaterial("__GLTFLoader._default",t,this._getDefaultImpl()),this._parent.onMaterialLoadedObservable.notifyObservers(e),this._defaultBabylonMaterialData[t]=e),a.material=e}else{const n=Ts.Get(`${e}/material`,this._gltf.materials,r.material);i.push(this._loadMaterialAsync(`/materials/${n.index}`,n,a,t,e=>{a.material=e}))}}c=Promise.all(i),l&&(r._instanceData={babylonSourceMesh:a,promise:c}),u=a}return Ms.AddPointerMetadata(u,e),this._parent.onMeshLoadedObservable.notifyObservers(u),i(u),this.logClose(),c.then(()=>u)}_loadVertexDataAsync(e,n,s){const o=this._extensionsLoadVertexDataAsync(e,n,s);if(o)return o;const r=n.attributes;if(!r)throw new Error(`${e}: Attributes are missing`);const i=new Array,a=new t.Geometry(s.name,this._babylonScene);if(null==n.indices)s.isUnIndexed=!0;else{const t=Ts.Get(`${e}/indices`,this._gltf.accessors,n.indices);i.push(this._loadIndicesAccessorAsync(`/accessors/${t.index}`,t).then(e=>{a.setIndices(e)}))}const l=(n,o,l)=>{if(null==r[n])return;s._delayInfo=s._delayInfo||[],-1===s._delayInfo.indexOf(o)&&s._delayInfo.push(o);const u=Ts.Get(`${e}/attributes/${n}`,this._gltf.accessors,r[n]);i.push(this._loadVertexAccessorAsync(`/accessors/${u.index}`,u,o).then(e=>{if(e.getKind()===t.VertexBuffer.PositionKind&&!this.parent.alwaysComputeBoundingBox&&!s.skeleton){const e=As(u);e&&(a._boundingInfo=e,a.useBoundingInfoFromGeometry=!0)}a.setVerticesBuffer(e,u.count)})),o==t.VertexBuffer.MatricesIndicesExtraKind&&(s.numBoneInfluencers=8),l&&l(u)};return l("POSITION",t.VertexBuffer.PositionKind),l("NORMAL",t.VertexBuffer.NormalKind),l("TANGENT",t.VertexBuffer.TangentKind),l("TEXCOORD_0",t.VertexBuffer.UVKind),l("TEXCOORD_1",t.VertexBuffer.UV2Kind),l("TEXCOORD_2",t.VertexBuffer.UV3Kind),l("TEXCOORD_3",t.VertexBuffer.UV4Kind),l("TEXCOORD_4",t.VertexBuffer.UV5Kind),l("TEXCOORD_5",t.VertexBuffer.UV6Kind),l("JOINTS_0",t.VertexBuffer.MatricesIndicesKind),l("WEIGHTS_0",t.VertexBuffer.MatricesWeightsKind),l("JOINTS_1",t.VertexBuffer.MatricesIndicesExtraKind),l("WEIGHTS_1",t.VertexBuffer.MatricesWeightsExtraKind),l("COLOR_0",t.VertexBuffer.ColorKind,e=>{"VEC4"===e.type&&(s.hasVertexAlpha=!0)}),Promise.all(i).then(()=>a)}_createMorphTargets(e,n,s,o,r){if(!o.targets||!this._parent.loadMorphTargets)return;if(null==n._numMorphTargets)n._numMorphTargets=o.targets.length;else if(o.targets.length!==n._numMorphTargets)throw new Error(`${e}: Primitives do not have the same number of targets`);const i=s.extras?s.extras.targetNames:null;this._babylonScene._blockEntityCollection=!!this._assetContainer,r.morphTargetManager=new t.MorphTargetManager(this._babylonScene),r.morphTargetManager._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,r.morphTargetManager.areUpdatesFrozen=!0;for(let e=0;e<o.targets.length;e++){const o=n.weights?n.weights[e]:s.weights?s.weights[e]:0,a=i?i[e]:`morphTarget${e}`;r.morphTargetManager.addTarget(new t.MorphTarget(a,o,r.getScene()))}}_loadMorphTargetsAsync(e,n,s,o){if(!n.targets||!this._parent.loadMorphTargets)return Promise.resolve();const r=new Array,i=s.morphTargetManager;for(let t=0;t<i.numTargets;t++){const s=i.getTarget(t);r.push(this._loadMorphTargetVertexDataAsync(`${e}/targets/${t}`,o,n.targets[t],s))}return Promise.all(r).then(()=>{i.areUpdatesFrozen=!1,this._parent.useMaxMorphTargetInfluencers&&(i.isUsingTextureForTargets||i.numTargets<=t.MorphTargetManager.MaxActiveMorphTargetsInVertexAttributeMode)&&(i.optimizeInfluencers=!1,i.numMaxInfluencers=i.numTargets)})}_loadMorphTargetVertexDataAsync(e,n,s,o){return b(this,void 0,void 0,function*(){const r=new Array,i=(t,o,i)=>{if(null==s[t])return;const a=n.getVertexBuffer(o);if(!a)return;const l=Ts.Get(`${e}/${t}`,this._gltf.accessors,s[t]);r.push(this._loadFloatAccessorAsync(`/accessors/${l.index}`,l).then(e=>{i(a,e)}))};return i("POSITION",t.VertexBuffer.PositionKind,(e,t)=>{const n=new Float32Array(t.length);e.forEach(t.length,(e,s)=>{n[s]=t[s]+e}),o.setPositions(n)}),i("NORMAL",t.VertexBuffer.NormalKind,(e,t)=>{const n=new Float32Array(t.length);e.forEach(n.length,(e,s)=>{n[s]=t[s]+e}),o.setNormals(n)}),i("TANGENT",t.VertexBuffer.TangentKind,(e,t)=>{const n=new Float32Array(t.length/3*4);let s=0;e.forEach(t.length/3*4,(e,o)=>{(o+1)%4!=0&&(n[s]=t[s]+e,s++)}),o.setTangents(n)}),i("TEXCOORD_0",t.VertexBuffer.UVKind,(e,t)=>{const n=new Float32Array(t.length);e.forEach(t.length,(e,s)=>{n[s]=t[s]+e}),o.setUVs(n)}),i("TEXCOORD_1",t.VertexBuffer.UV2Kind,(e,t)=>{const n=new Float32Array(t.length);e.forEach(t.length,(e,s)=>{n[s]=t[s]+e}),o.setUV2s(n)}),i("COLOR_0",t.VertexBuffer.ColorKind,(t,n)=>{let s=null;const r=t.getSize();if(3===r){s=new Float32Array(n.length/3*4),t.forEach(n.length,(e,t)=>{const o=Math.floor(t/3),r=t%3;s[4*o+r]=n[3*o+r]+e});for(let e=0;e<n.length/3;++e)s[4*e+3]=1}else{if(4!==r)throw new Error(`${e}: Invalid number of components (${r}) for COLOR_0 attribute`);s=new Float32Array(n.length),t.forEach(n.length,(e,t)=>{s[t]=n[t]+e})}o.setColors(s)}),yield Promise.all(r).then(()=>{})})}static _LoadTransform(e,n){if(null!=e.skin)return;let s=t.Vector3.Zero(),o=t.Quaternion.Identity(),r=t.Vector3.One();e.matrix?t.Matrix.FromArray(e.matrix).decompose(r,o,s):(e.translation&&(s=t.Vector3.FromArray(e.translation)),e.rotation&&(o=t.Quaternion.FromArray(e.rotation)),e.scale&&(r=t.Vector3.FromArray(e.scale))),n.position=s,n.rotationQuaternion=o,n.scaling=r}_loadSkinAsync(e,n,s,o){if(!this._parent.loadSkins)return Promise.resolve();const r=this._extensionsLoadSkinAsync(e,n,s);if(r)return r;if(s._data)return o(s._data.babylonSkeleton),s._data.promise;const i=`skeleton${s.index}`;this._babylonScene._blockEntityCollection=!!this._assetContainer;const a=new t.Skeleton(s.name||i,i,this._babylonScene);a._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,this._loadBones(e,s,a);const l=this._loadSkinInverseBindMatricesDataAsync(e,s).then(e=>{this._updateBoneMatrices(a,e)});return s._data={babylonSkeleton:a,promise:l},o(a),l}_loadBones(e,n,s){if(null==n.skeleton||this._parent.alwaysComputeSkeletonRootNode){const s=this._findSkeletonRootNode(`${e}/joints`,n.joints);if(s)if(void 0===n.skeleton)n.skeleton=s.index;else{const o=(e,t)=>{for(;t.parent;t=t.parent)if(t.parent===e)return!0;return!1},r=Ts.Get(`${e}/skeleton`,this._gltf.nodes,n.skeleton);r===s||o(r,s)||(t.Logger.Warn(`${e}/skeleton: Overriding with nearest common ancestor as skeleton node is not a common root`),n.skeleton=s.index)}else t.Logger.Warn(`${e}: Failed to find common root`)}const o={};for(const t of n.joints){const r=Ts.Get(`${e}/joints/${t}`,this._gltf.nodes,t);this._loadBone(r,n,s,o)}}_findSkeletonRootNode(e,t){if(0===t.length)return null;const n={};for(const s of t){const t=[];let o=Ts.Get(`${e}/${s}`,this._gltf.nodes,s);for(;-1!==o.index;)t.unshift(o),o=o.parent;n[s]=t}let s=null;for(let e=0;;++e){let o=n[t[0]];if(e>=o.length)return s;const r=o[e];for(let i=1;i<t.length;++i)if(o=n[t[i]],e>=o.length||r!==o[e])return s;s=r}}_loadBone(e,n,s,o){e._isJoint=!0;let r=o[e.index];if(r)return r;let i=null;e.index!==n.skeleton&&(e.parent&&-1!==e.parent.index?i=this._loadBone(e.parent,n,s,o):void 0!==n.skeleton&&t.Logger.Warn(`/skins/${n.index}/skeleton: Skeleton node is not a common root`));const a=n.joints.indexOf(e.index);return r=new t.Bone(e.name||`joint${e.index}`,s,i,this._getNodeMatrix(e),null,null,a),o[e.index]=r,this._postSceneLoadActions.push(()=>{r.linkTransformNode(e._babylonTransformNode)}),r}_loadSkinInverseBindMatricesDataAsync(e,t){if(null==t.inverseBindMatrices)return Promise.resolve(null);const n=Ts.Get(`${e}/inverseBindMatrices`,this._gltf.accessors,t.inverseBindMatrices);return this._loadFloatAccessorAsync(`/accessors/${n.index}`,n)}_updateBoneMatrices(e,n){for(const s of e.bones){const e=t.Matrix.Identity(),o=s._index;n&&-1!==o&&(t.Matrix.FromArrayToRef(n,16*o,e),e.invertToRef(e));const r=s.getParent();r&&e.multiplyToRef(r.getAbsoluteInverseBindMatrix(),e),s.updateMatrix(e,!1,!1),s._updateAbsoluteBindMatrices(void 0,!1)}}_getNodeMatrix(e){return e.matrix?t.Matrix.FromArray(e.matrix):t.Matrix.Compose(e.scale?t.Vector3.FromArray(e.scale):t.Vector3.One(),e.rotation?t.Quaternion.FromArray(e.rotation):t.Quaternion.Identity(),e.translation?t.Vector3.FromArray(e.translation):t.Vector3.Zero())}loadCameraAsync(e,n,s=()=>{}){const o=this._extensionsLoadCameraAsync(e,n,s);if(o)return o;const r=new Array;this.logOpen(`${e} ${n.name||""}`),this._babylonScene._blockEntityCollection=!!this._assetContainer;const i=new t.FreeCamera(n.name||`camera${n.index}`,t.Vector3.Zero(),this._babylonScene,!1);switch(i._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,n._babylonCamera=i,i.setTarget(new t.Vector3(0,0,-1)),n.type){case"perspective":{const t=n.perspective;if(!t)throw new Error(`${e}: Camera perspective properties are missing`);i.fov=t.yfov,i.minZ=t.znear,i.maxZ=t.zfar||0;break}case"orthographic":if(!n.orthographic)throw new Error(`${e}: Camera orthographic properties are missing`);i.mode=t.Camera.ORTHOGRAPHIC_CAMERA,i.orthoLeft=-n.orthographic.xmag,i.orthoRight=n.orthographic.xmag,i.orthoBottom=-n.orthographic.ymag,i.orthoTop=n.orthographic.ymag,i.minZ=n.orthographic.znear,i.maxZ=n.orthographic.zfar;break;default:throw new Error(`${e}: Invalid camera type (${n.type})`)}return Ms.AddPointerMetadata(i,e),this._parent.onCameraLoadedObservable.notifyObservers(i),s(i),this.logClose(),Promise.all(r).then(()=>i)}_loadAnimationsAsync(){this._parent._startPerformanceCounter("Load animations");const e=this._gltf.animations;if(!e)return Promise.resolve();const t=new Array;for(let n=0;n<e.length;n++){const s=e[n];t.push(this.loadAnimationAsync(`/animations/${s.index}`,s).then(e=>{0===e.targetedAnimations.length&&e.dispose()}))}return Promise.all(t).then(()=>{this._parent._endPerformanceCounter("Load animations")})}loadAnimationAsync(e,t){this._parent._startPerformanceCounter("Load animation");return this._extensionsLoadAnimationAsync(e,t)||bs.value.then(({AnimationGroup:n})=>{this._babylonScene._blockEntityCollection=!!this._assetContainer;const s=new n(t.name||`animation${t.index}`,this._babylonScene);s._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,t._babylonAnimationGroup=s;const o=new Array;Ts.Assign(t.channels),Ts.Assign(t.samplers);for(const n of t.channels)o.push(this._loadAnimationChannelAsync(`${e}/channels/${n.index}`,e,t,n,(e,t)=>{e.animations=e.animations||[],e.animations.push(t),s.addTargetedAnimation(t,e)}));return this._parent._endPerformanceCounter("Load animation"),Promise.all(o).then(()=>(s.normalize(0),s))})}_loadAnimationChannelAsync(e,t,n,s,o){const r=this._extensionsLoadAnimationChannelAsync(e,t,n,s,o);if(r)return r;if(null==s.target.node)return Promise.resolve();const i=Ts.Get(`${e}/target/node`,this._gltf.nodes,s.target.node),a=s.target.path,l="weights"===a;return l&&!i._numMorphTargets||!l&&!i._babylonTransformNode?Promise.resolve():this._parent.loadNodeAnimations||l||i._isJoint?xs.value.then(()=>{var r,l,u,c;let d;switch(a){case"translation":d=null===(r=gs("/nodes/{}/translation"))||void 0===r?void 0:r.interpolation;break;case"rotation":d=null===(l=gs("/nodes/{}/rotation"))||void 0===l?void 0:l.interpolation;break;case"scale":d=null===(u=gs("/nodes/{}/scale"))||void 0===u?void 0:u.interpolation;break;case"weights":d=null===(c=gs("/nodes/{}/weights"))||void 0===c?void 0:c.interpolation;break;default:throw new Error(`${e}/target/path: Invalid value (${s.target.path})`)}if(!d)throw new Error(`${e}/target/path: Could not find interpolation properties for target path (${s.target.path})`);const h={object:i,info:d};return this._loadAnimationChannelFromTargetInfoAsync(e,t,n,s,h,o)}):Promise.resolve()}_loadAnimationChannelFromTargetInfoAsync(e,t,n,s,o,r){const i=this.parent.targetFps,a=1/i,l=Ts.Get(`${e}/sampler`,n.samplers,s.sampler);return this._loadAnimationSamplerAsync(`${t}/samplers/${s.sampler}`,l).then(e=>{let t=0;const l=o.object,u=o.info;for(const o of u){const u=o.getStride(l),c=e.input,d=e.output,h=new Array(c.length);let m=0;switch(e.interpolation){case"STEP":for(let e=0;e<c.length;e++){const t=o.getValue(l,d,m,1);m+=u,h[e]={frame:c[e]*i,value:t,interpolation:1}}break;case"CUBICSPLINE":for(let e=0;e<c.length;e++){const t=o.getValue(l,d,m,a);m+=u;const n=o.getValue(l,d,m,1);m+=u;const s=o.getValue(l,d,m,a);m+=u,h[e]={frame:c[e]*i,inTangent:t,value:n,outTangent:s}}break;case"LINEAR":for(let e=0;e<c.length;e++){const t=o.getValue(l,d,m,1);m+=u,h[e]={frame:c[e]*i,value:t}}}if(m>0){const e=`${n.name||`animation${n.index}`}_channel${s.index}_${t}`,a=o.buildAnimations(l,e,i,h);for(const e of a)t++,r(e.babylonAnimatable,e.babylonAnimation)}}})}_loadAnimationSamplerAsync(e,t){if(t._data)return t._data;const n=t.interpolation||"LINEAR";switch(n){case"STEP":case"LINEAR":case"CUBICSPLINE":break;default:throw new Error(`${e}/interpolation: Invalid value (${t.interpolation})`)}const s=Ts.Get(`${e}/input`,this._gltf.accessors,t.input),o=Ts.Get(`${e}/output`,this._gltf.accessors,t.output);return t._data=Promise.all([this._loadFloatAccessorAsync(`/accessors/${s.index}`,s),this._loadFloatAccessorAsync(`/accessors/${o.index}`,o)]).then(([e,t])=>({input:e,interpolation:n,output:t})),t._data}loadBufferAsync(e,t,n,s){const o=this._extensionsLoadBufferAsync(e,t,n,s);if(o)return o;if(!t._data)if(t.uri)t._data=this.loadUriAsync(`${e}/uri`,t,t.uri);else{if(!this._bin)throw new 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,s)}catch(t){throw new Error(`${e}: ${t.message}`,{cause:t})}})}loadBufferViewAsync(e,t){const n=this._extensionsLoadBufferViewAsync(e,t);if(n)return n;if(t._data)return t._data;const s=Ts.Get(`${e}/buffer`,this._gltf.buffers,t.buffer);return t._data=this.loadBufferAsync(`/buffers/${s.index}`,s,t.byteOffset||0,t.byteLength),t._data}_loadAccessorAsync(e,n,s){if(n._data)return n._data;const o=Ms._GetNumComponents(e,n.type),r=o*t.VertexBufferGetTypeByteLength(n.componentType),i=o*n.count;if(null==n.bufferView)n._data=Promise.resolve(new s(i));else{const a=Ts.Get(`${e}/bufferView`,this._gltf.bufferViews,n.bufferView);n._data=this.loadBufferViewAsync(`/bufferViews/${a.index}`,a).then(l=>{if(5126!==n.componentType||n.normalized||a.byteStride&&a.byteStride!==r){const e=new s(i);return t.VertexBufferForEach(l,n.byteOffset||0,a.byteStride||r,o,n.componentType,e.length,n.normalized||!1,(t,n)=>{e[n]=t}),e}return Ms._GetTypedArray(e,n.componentType,l,n.byteOffset,i)})}if(n.sparse){const i=n.sparse;n._data=n._data.then(a=>{const l=a,u=Ts.Get(`${e}/sparse/indices/bufferView`,this._gltf.bufferViews,i.indices.bufferView),c=Ts.Get(`${e}/sparse/values/bufferView`,this._gltf.bufferViews,i.values.bufferView);return Promise.all([this.loadBufferViewAsync(`/bufferViews/${u.index}`,u),this.loadBufferViewAsync(`/bufferViews/${c.index}`,c)]).then(([a,u])=>{const c=Ms._GetTypedArray(`${e}/sparse/indices`,i.indices.componentType,a,i.indices.byteOffset,i.count),d=o*i.count;let h;if(5126!==n.componentType||n.normalized){const a=Ms._GetTypedArray(`${e}/sparse/values`,n.componentType,u,i.values.byteOffset,d);h=new s(d),t.VertexBufferForEach(a,0,r,o,n.componentType,h.length,n.normalized||!1,(e,t)=>{h[t]=e})}else h=Ms._GetTypedArray(`${e}/sparse/values`,n.componentType,u,i.values.byteOffset,d);let m=0;for(let e=0;e<c.length;e++){let t=c[e]*o;for(let e=0;e<o;e++)l[t++]=h[m++]}return l})})}return n._data}_loadFloatAccessorAsync(e,t){return this._loadAccessorAsync(e,t,Float32Array)}_loadIndicesAccessorAsync(e,t){if("SCALAR"!==t.type)throw new Error(`${e}/type: Invalid value ${t.type}`);if(5121!==t.componentType&&5123!==t.componentType&&5125!==t.componentType)throw new Error(`${e}/componentType: Invalid value ${t.componentType}`);if(t._data)return t._data;if(t.sparse){const n=Ms._GetTypedArrayConstructor(`${e}/componentType`,t.componentType);t._data=this._loadAccessorAsync(e,t,n)}else{const n=Ts.Get(`${e}/bufferView`,this._gltf.bufferViews,t.bufferView);t._data=this.loadBufferViewAsync(`/bufferViews/${n.index}`,n).then(n=>Ms._GetTypedArray(e,t.componentType,n,t.byteOffset,t.count))}return t._data}_loadVertexBufferViewAsync(e){if(e._babylonBuffer)return e._babylonBuffer;const n=this._babylonScene.getEngine();return e._babylonBuffer=this.loadBufferViewAsync(`/bufferViews/${e.index}`,e).then(e=>new t.Buffer(n,e,!1)),e._babylonBuffer}_loadVertexAccessorAsync(e,n,s){var o;if(null===(o=n._babylonVertexBuffer)||void 0===o?void 0:o[s])return n._babylonVertexBuffer[s];n._babylonVertexBuffer||(n._babylonVertexBuffer={});const r=this._babylonScene.getEngine();if(n.sparse||null==n.bufferView)n._babylonVertexBuffer[s]=this._loadFloatAccessorAsync(e,n).then(e=>new t.VertexBuffer(r,e,s,!1));else{const o=Ts.Get(`${e}/bufferView`,this._gltf.bufferViews,n.bufferView);n._babylonVertexBuffer[s]=this._loadVertexBufferViewAsync(o).then(i=>{const a=Ms._GetNumComponents(e,n.type);return new t.VertexBuffer(r,i,s,!1,void 0,o.byteStride,void 0,n.byteOffset,a,n.componentType,n.normalized,!0,void 0,!0)})}return n._babylonVertexBuffer[s]}_loadMaterialMetallicRoughnessPropertiesAsync(e,n,s){const o=new Array,r=this._getOrCreateMaterialAdapter(s);return n&&(n.baseColorFactor?(r.baseColor=t.Color3.FromArray(n.baseColorFactor),r.geometryOpacity=n.baseColorFactor[3]):r.baseColor=t.Color3.White(),r.baseMetalness=null==n.metallicFactor?1:n.metallicFactor,r.specularRoughness=null==n.roughnessFactor?1:n.roughnessFactor,n.baseColorTexture&&o.push(this.loadTextureInfoAsync(`${e}/baseColorTexture`,n.baseColorTexture,e=>{e.name=`${s.name} (Base Color)`,r.baseColorTexture=e})),n.metallicRoughnessTexture&&(n.metallicRoughnessTexture.nonColorData=!0,o.push(this.loadTextureInfoAsync(`${e}/metallicRoughnessTexture`,n.metallicRoughnessTexture,e=>{e.name=`${s.name} (Metallic Roughness)`,r.baseMetalnessTexture=e,r.specularRoughnessTexture=e})),r.useRoughnessFromMetallicTextureGreen=!0,r.useMetallicFromMetallicTextureBlue=!0)),Promise.all(o).then(()=>{})}_loadMaterialAsync(e,t,n,s,o=()=>{}){const r=this._extensionsLoadMaterialAsync(e,t,n,s,o);if(r)return r;t._data=t._data||{};let i=t._data[s];if(!i){this.logOpen(`${e} ${t.name||""}`);const n=this.createMaterial(e,t,s);i={babylonMaterial:n,babylonMeshes:[],promise:this.loadMaterialPropertiesAsync(e,t,n)},t._data[s]=i,Ms.AddPointerMetadata(n,e),this._parent.onMaterialLoadedObservable.notifyObservers(n),this.logClose()}return n&&(i.babylonMeshes.push(n),n.onDisposeObservable.addOnce(()=>{const e=i.babylonMeshes.indexOf(n);-1!==e&&i.babylonMeshes.splice(e,1)})),o(i.babylonMaterial),i.promise.then(()=>i.babylonMaterial)}_selectImplForGltfMaterial(e){var t;if(this.parent.useOpenPBR||(null===(t=e.extensions)||void 0===t?void 0:t.KHR_materials_openpbr)){const e=this._pbrMaterialImpls.get("openpbr");if(e)return e}const n=this._pbrMaterialImpls.get("pbr");if(n)return n;throw new Error("No PBR material implementation loaded")}_getDefaultImpl(){var e;if(this.parent.useOpenPBR){const e=this._pbrMaterialImpls.get("openpbr");if(e)return e}const t=null!==(e=this._pbrMaterialImpls.get("pbr"))&&void 0!==e?e:this._pbrMaterialImpls.values().next().value;if(t)return t;throw new Error("No PBR material implementation loaded")}_createDefaultMaterial(e,t,n){this._babylonScene._blockEntityCollection=!!this._assetContainer;const s=new n.materialClass(e,this._babylonScene);s._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,s.fillMode=t,s.transparencyMode=n.materialClass.MATERIAL_OPAQUE;const o=this._getOrCreateMaterialAdapter(s);return o.transparencyAsAlphaCoverage=this._parent.transparencyAsCoverage,o.baseMetalness=1,o.specularRoughness=1,s}createMaterial(e,t,n){const s=this._extensionsCreateMaterial(e,t,n);if(s)return s;const o=t.name||`material${t.index}`;return this._createDefaultMaterial(o,n,this._selectImplForGltfMaterial(t))}loadMaterialPropertiesAsync(e,t,n){const s=this._extensionsLoadMaterialPropertiesAsync(e,t,n);if(s)return s;const o=new Array;return o.push(this.loadMaterialBasePropertiesAsync(e,t,n)),t.pbrMetallicRoughness&&o.push(this._loadMaterialMetallicRoughnessPropertiesAsync(`${e}/pbrMetallicRoughness`,t.pbrMetallicRoughness,n)),this.loadMaterialAlphaProperties(e,t,n),Promise.all(o).then(()=>{})}loadMaterialBasePropertiesAsync(e,n,s){const o=new Array,r=this._getOrCreateMaterialAdapter(s);let i;r.emissionColor=n.emissiveFactor?t.Color3.FromArray(n.emissiveFactor):new t.Color3(0,0,0),n.doubleSided&&(r.backFaceCulling=!1,r.twoSidedLighting=!0),n.normalTexture&&(n.normalTexture.nonColorData=!0,o.push(this.loadTextureInfoAsync(`${e}/normalTexture`,n.normalTexture,e=>{var t;e.name=`${s.name} (Normal)`,r.geometryNormalTexture=e,null!=(null===(t=n.normalTexture)||void 0===t?void 0:t.scale)&&(e.level=n.normalTexture.scale)})),r.setNormalMapInversions(!this._babylonScene.useRightHandedSystem,this._babylonScene.useRightHandedSystem));let a,l=1;return n.occlusionTexture&&(n.occlusionTexture.nonColorData=!0,o.push(this.loadTextureInfoAsync(`${e}/occlusionTexture`,n.occlusionTexture,e=>{e.name=`${s.name} (Occlusion)`,i=e})),null!=n.occlusionTexture.strength&&(l=n.occlusionTexture.strength)),n.emissiveTexture&&o.push(this.loadTextureInfoAsync(`${e}/emissiveTexture`,n.emissiveTexture,e=>{e.name=`${s.name} (Emissive)`,a=e})),Promise.all(o).then(()=>{i&&(r.ambientOcclusionTexture=i,r.ambientOcclusionTextureStrength=l),a&&(r.emissionColorTexture=a)})}loadMaterialAlphaProperties(e,n,s){if(0===this._pbrMaterialImpls.size)throw new Error(`${e}: Material type not supported`);const o=this._getOrCreateMaterialAdapter(s),r=o.baseColorTexture;switch(n.alphaMode||"OPAQUE"){case"OPAQUE":s.transparencyMode=t.Material.MATERIAL_OPAQUE,s.alpha=1;break;case"MASK":s.transparencyMode=t.Material.MATERIAL_ALPHATEST,o.alphaCutOff=null==n.alphaCutoff?.5:n.alphaCutoff,r&&(r.hasAlpha=!0,o.useAlphaFromBaseColorTexture=!0);break;case"BLEND":s.transparencyMode=t.Material.MATERIAL_ALPHABLEND,r&&(r.hasAlpha=!0,o.useAlphaFromBaseColorTexture=!0);break;default:throw new Error(`${e}/alphaMode: Invalid value (${n.alphaMode})`)}}loadTextureInfoAsync(e,t,n=()=>{}){const s=this._extensionsLoadTextureInfoAsync(e,t,n);if(s)return s;if(this.logOpen(`${e}`),t.texCoord>=6)throw new Error(`${e}/texCoord: Invalid value (${t.texCoord})`);const o=Ts.Get(`${e}/index`,this._gltf.textures,t.index);o._textureInfo=t;const r=this._loadTextureAsync(`/textures/${t.index}`,o,s=>{s.coordinatesIndex=t.texCoord||0,Ms.AddPointerMetadata(s,e),this._parent.onTextureLoadedObservable.notifyObservers(s),n(s)});return this.logClose(),r}_loadTextureAsync(e,t,n=()=>{}){const s=this._extensionsLoadTextureAsync(e,t,n);if(s)return s;this.logOpen(`${e} ${t.name||""}`);const o=null==t.sampler?Ms.DefaultSampler:Ts.Get(`${e}/sampler`,this._gltf.samplers,t.sampler),r=Ts.Get(`${e}/source`,this._gltf.images,t.source),i=this._createTextureAsync(e,o,r,n,void 0,!t._textureInfo.nonColorData);return this.logClose(),i}_createTextureAsync(e,n,s,o=()=>{},r,i){var a,l;const u=this._loadSampler(`/samplers/${n.index}`,n),c=new Array,d=new t.Deferred;this._babylonScene._blockEntityCollection=!!this._assetContainer;const h={noMipmap:u.noMipMaps,invertY:!1,samplingMode:u.samplingMode,onLoad:()=>{this._disposed||d.resolve()},onError:(t,n)=>{this._disposed||d.reject(new Error(`${e}: ${n&&n.message?n.message:t||"Failed to load texture"}`))},mimeType:null!==(a=s.mimeType)&&void 0!==a?a:t.GetMimeType(null!==(l=s.uri)&&void 0!==l?l:""),loaderOptions:r,useSRGBBuffer:!!i&&this._parent.useSRGBBuffers},m=new t.Texture(null,this._babylonScene,h);m._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,c.push(d.promise);const f=s.uri&&!t.IsBase64DataUrl(s.uri)?s.uri:void 0,p=null!=f?f:`${this._fileName}#image${s.index}`;if(c.push(this.loadImageAsync(`/images/${s.index}`,s).then(e=>{const t=`data:${this._uniqueRootUrl}${p}`;m.updateURL(t,e);const n=m.getInternalTexture();n&&(n.label=s.name)})),m.wrapU=u.wrapU,m.wrapV=u.wrapV,o(m),this._parent.useGltfTextureNames){const e=s.name||f||`image${s.index}`;m.name=e}return Promise.all(c).then(()=>m)}_loadSampler(e,t){return t._data||(t._data={noMipMaps:9728===t.minFilter||9729===t.minFilter,samplingMode:Ms._GetTextureSamplingMode(e,t),wrapU:Ms._GetTextureWrapMode(`${e}/wrapS`,t.wrapS),wrapV:Ms._GetTextureWrapMode(`${e}/wrapT`,t.wrapT)}),t._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{const n=Ts.Get(`${e}/bufferView`,this._gltf.bufferViews,t.bufferView);t._data=this.loadBufferViewAsync(`/bufferViews/${n.index}`,n)}this.logClose()}return t._data}loadUriAsync(e,n,s){const o=this._extensionsLoadUriAsync(e,n,s);if(o)return o;if(!Ms._ValidateUri(s))throw new Error(`${e}: '${s}' is invalid`);if(t.IsBase64DataUrl(s)){const n=new Uint8Array(t.DecodeBase64UrlToBinary(s));return this.log(`${e}: Decoded ${s.substring(0,64)}... (${n.length} bytes)`),Promise.resolve(n)}return this.log(`${e}: Loading ${s}`),this._parent.preprocessUrlAsync(this._rootUrl+s).then(n=>new Promise((o,r)=>{this._parent._loadFile(this._babylonScene,n,t=>{this._disposed||(this.log(`${e}: Loaded ${s} (${t.byteLength} bytes)`),o(new Uint8Array(t)))},!0,n=>{r(new t.LoadFileError(`${e}: Failed to load '${s}'${n?": "+n.status+" "+n.statusText:""}`,n))})}))}static AddPointerMetadata(e,t){e.metadata=e.metadata||{};const n=e._internalMetadata=e._internalMetadata||{},s=n.gltf=n.gltf||{};(s.pointers=s.pointers||[]).push(t)}static _GetTextureWrapMode(e,n){switch(n=null==n?10497:n){case 33071:return t.Texture.CLAMP_ADDRESSMODE;case 33648:return t.Texture.MIRROR_ADDRESSMODE;case 10497:return t.Texture.WRAP_ADDRESSMODE;default:return t.Logger.Warn(`${e}: Invalid value (${n})`),t.Texture.WRAP_ADDRESSMODE}}static _GetTextureSamplingMode(e,n){const s=null==n.magFilter?9729:n.magFilter,o=null==n.minFilter?9987:n.minFilter;if(9729===s)switch(o){case 9728:return t.Texture.LINEAR_NEAREST;case 9729:return t.Texture.LINEAR_LINEAR;case 9984:return t.Texture.LINEAR_NEAREST_MIPNEAREST;case 9985:return t.Texture.LINEAR_LINEAR_MIPNEAREST;case 9986:return t.Texture.LINEAR_NEAREST_MIPLINEAR;case 9987:return t.Texture.LINEAR_LINEAR_MIPLINEAR;default:return t.Logger.Warn(`${e}/minFilter: Invalid value (${o})`),t.Texture.LINEAR_LINEAR_MIPLINEAR}else switch(9728!==s&&t.Logger.Warn(`${e}/magFilter: Invalid value (${s})`),o){case 9728:return t.Texture.NEAREST_NEAREST;case 9729:return t.Texture.NEAREST_LINEAR;case 9984:return t.Texture.NEAREST_NEAREST_MIPNEAREST;case 9985:return t.Texture.NEAREST_LINEAR_MIPNEAREST;case 9986:return t.Texture.NEAREST_NEAREST_MIPLINEAR;case 9987:return t.Texture.NEAREST_LINEAR_MIPLINEAR;default:return t.Logger.Warn(`${e}/minFilter: Invalid value (${o})`),t.Texture.NEAREST_NEAREST_MIPNEAREST}}static _GetTypedArrayConstructor(e,n){try{return t.GetTypedArrayConstructor(n)}catch(t){throw new Error(`${e}: ${t.message}`,{cause:t})}}static _GetTypedArray(e,n,s,o,r){const i=s.buffer;o=s.byteOffset+(o||0);const a=Ms._GetTypedArrayConstructor(`${e}/componentType`,n),l=t.VertexBufferGetTypeByteLength(n);return o%l!==0?(t.Logger.Warn(`${e}: Copying buffer as byte offset (${o}) is not a multiple of component type byte length (${l})`),new a(i.slice(o,o+r*l),0)):new a(i,o,r)}static _GetNumComponents(e,t){switch(t){case"SCALAR":return 1;case"VEC2":return 2;case"VEC3":return 3;case"VEC4":case"MAT2":return 4;case"MAT3":return 9;case"MAT4":return 16}throw new Error(`${e}: Invalid type (${t})`)}static _ValidateUri(e){return t.Tools.IsBase64(e)||-1===e.indexOf("..")}static _GetDrawMode(e,n){switch(null==n&&(n=4),n){case 0:return t.Material.PointListDrawMode;case 1:return t.Material.LineListDrawMode;case 2:return t.Material.LineLoopDrawMode;case 3:return t.Material.LineStripDrawMode;case 4:return t.Material.TriangleFillMode;case 5:return t.Material.TriangleStripDrawMode;case 6:return t.Material.TriangleFanDrawMode}throw new Error(`${e}: Invalid mesh primitive mode (${n})`)}_compileMaterialsAsync(){this._parent._startPerformanceCounter("Compile materials");const e=new Array;if(this._gltf.materials)for(const t of this._gltf.materials)if(t._data)for(const n in t._data){const s=t._data[n];for(const t of s.babylonMeshes){t.computeWorldMatrix(!0);const n=s.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");const e=new Array,t=this._babylonScene.lights;for(const n of t){const t=n.getShadowGenerator();t&&e.push(t.forceCompilationAsync())}return Promise.all(e).then(()=>{this._parent._endPerformanceCounter("Compile shadow generators")})}_forEachExtensions(e){for(const t of this._extensions)t.enabled&&e(t)}_applyExtensions(e,t,n){for(const s of this._extensions)if(s.enabled){const o=`${s.name}.${t}`,r=e;r._activeLoaderExtensionFunctions=r._activeLoaderExtensionFunctions||{};const i=r._activeLoaderExtensionFunctions;if(!i[o]){i[o]=!0;try{const e=n(s);if(e)return e}finally{delete i[o]}}}return null}_extensionsOnLoading(){this._forEachExtensions(e=>e.onLoading&&e.onLoading())}_extensionsOnReady(){this._forEachExtensions(e=>e.onReady&&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",s=>s.loadNodeAsync&&s.loadNodeAsync(e,t,n))}_extensionsLoadCameraAsync(e,t,n){return this._applyExtensions(t,"loadCamera",s=>s.loadCameraAsync&&s.loadCameraAsync(e,t,n))}_extensionsLoadVertexDataAsync(e,t,n){return this._applyExtensions(t,"loadVertexData",s=>s._loadVertexDataAsync&&s._loadVertexDataAsync(e,t,n))}_extensionsLoadMeshPrimitiveAsync(e,t,n,s,o,r){return this._applyExtensions(o,"loadMeshPrimitive",i=>i._loadMeshPrimitiveAsync&&i._loadMeshPrimitiveAsync(e,t,n,s,o,r))}_extensionsLoadMaterialAsync(e,t,n,s,o){return this._applyExtensions(t,"loadMaterial",r=>r._loadMaterialAsync&&r._loadMaterialAsync(e,t,n,s,o))}_extensionsCreateMaterial(e,t,n){return this._applyExtensions(t,"createMaterial",s=>s.createMaterial&&s.createMaterial(e,t,n))}_extensionsLoadMaterialPropertiesAsync(e,t,n){return this._applyExtensions(t,"loadMaterialProperties",s=>s.loadMaterialPropertiesAsync&&s.loadMaterialPropertiesAsync(e,t,n))}_extensionsLoadTextureInfoAsync(e,t,n){return this._applyExtensions(t,"loadTextureInfo",s=>s.loadTextureInfoAsync&&s.loadTextureInfoAsync(e,t,n))}_extensionsLoadTextureAsync(e,t,n){return this._applyExtensions(t,"loadTexture",s=>s._loadTextureAsync&&s._loadTextureAsync(e,t,n))}_extensionsLoadAnimationAsync(e,t){return this._applyExtensions(t,"loadAnimation",n=>n.loadAnimationAsync&&n.loadAnimationAsync(e,t))}_extensionsLoadAnimationChannelAsync(e,t,n,s,o){return this._applyExtensions(n,"loadAnimationChannel",r=>r._loadAnimationChannelAsync&&r._loadAnimationChannelAsync(e,t,n,s,o))}_extensionsLoadSkinAsync(e,t,n){return this._applyExtensions(n,"loadSkin",s=>s._loadSkinAsync&&s._loadSkinAsync(e,t,n))}_extensionsLoadUriAsync(e,t,n){return this._applyExtensions(t,"loadUri",s=>s._loadUriAsync&&s._loadUriAsync(e,t,n))}_extensionsLoadBufferViewAsync(e,t){return this._applyExtensions(t,"loadBufferView",n=>n.loadBufferViewAsync&&n.loadBufferViewAsync(e,t))}_extensionsLoadBufferAsync(e,t,n,s){return this._applyExtensions(t,"loadBuffer",o=>o.loadBufferAsync&&o.loadBufferAsync(e,t,n,s))}static LoadExtensionAsync(e,t,n,s){if(!t.extensions)return null;const o=t.extensions[n];return o?s(`${e}/extensions/${n}`,o):null}static LoadExtraAsync(e,t,n,s){if(!t.extras)return null;const o=t.extras[n];return o?s(`${e}/extras/${n}`,o):null}isExtensionUsed(e){return!!this._gltf.extensionsUsed&&-1!==this._gltf.extensionsUsed.indexOf(e)}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)}}Ms.DefaultSampler={index:-1};let ws=!1;function Cs(){ws||(ws=!0,mn._CreateGLTF2Loader=e=>new Ms(e))}Cs(),pn();var Rs={__proto__:null,ArrayItem:Ts,GLTFFileLoader:mn,GLTFLoader:Ms,LoadBoundingInfoFromPositionAccessor:As,RegisterGLTF2Loader:Cs};function Ss(e,n,s,o){return t.Vector3.FromArray(n,s).scaleInPlace(o)}function Os(e,n,s,o){return t.Quaternion.FromArray(n,s).scaleInPlace(o)}function Fs(e,t,n,s){const o=new Array(e._numMorphTargets);for(let e=0;e<o.length;e++)o[e]=t[n++]*s;return o}class Es{constructor(e,t,n,s){this.type=e,this.name=t,this.getValue=n,this.getStride=s}_buildAnimation(e,n,s){const o=new t.Animation(e,this.name,n,this.type);return o.setKeys(s,!0),o}}class Is extends Es{buildAnimations(e,t,n,s){const o=[];return o.push({babylonAnimatable:e._babylonTransformNode,babylonAnimation:this._buildAnimation(t,n,s)}),o}}class Ls extends Es{buildAnimations(e,n,s,o){const r=[];if(e._numMorphTargets)for(let i=0;i<e._numMorphTargets;i++){const a=new t.Animation(`${n}_${i}`,this.name,s,this.type);if(a.setKeys(o.map(e=>({frame:e.frame,inTangent:e.inTangent?e.inTangent[i]:void 0,value:e.value[i],outTangent:e.outTangent?e.outTangent[i]:void 0,interpolation:e.interpolation})),!0),e._primitiveBabylonMeshes)for(const t of e._primitiveBabylonMeshes)if(t.morphTargetManager){const e=t.morphTargetManager.getTarget(i),n=a.clone();e.animations.push(n),r.push({babylonAnimatable:e,babylonAnimation:n})}}return r}}ys("/nodes/{}/translation",[new Is(t.Animation.ANIMATIONTYPE_VECTOR3,"position",Ss,()=>3)]),ys("/nodes/{}/rotation",[new Is(t.Animation.ANIMATIONTYPE_QUATERNION,"rotationQuaternion",Os,()=>4)]),ys("/nodes/{}/scale",[new Is(t.Animation.ANIMATIONTYPE_VECTOR3,"scaling",Ss,()=>3)]),ys("/nodes/{}/weights",[new Ls(t.Animation.ANIMATIONTYPE_FLOAT,"influence",Fs,e=>e._numMorphTargets)]);var Ps={__proto__:null,AnimationPropertyInfo:Es,TransformNodeAnimationPropertyInfo:Is,WeightAnimationPropertyInfo:Ls,getQuaternion:Os,getVector3:Ss,getWeights:Fs};class Bs{constructor(e){this._specWorkflow=!1,this._diffuseTransmissionTint=t.Color3.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){const t=this._material.ambientOcclusionTexture;t&&(t.level=e)}get ambientOcclusionTextureStrength(){var e;const t=this._material.ambientOcclusionTexture;return null!==(e=null==t?void 0:t.level)&&void 0!==e?e: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||0!==this._material.transmissionDepth?this._material.transmissionDepth=e:this._material.transmissionDepth=0}get transmissionDepth(){return this._material.transmissionDepth}set transmissionColor(e){e.equals(t.Color3.White())||(this._material.transmissionColor=e)}get transmissionColor(){return this._material.transmissionColor}get refractionBackgroundTexture(){return this._material.backgroundRefractionTexture}set refractionBackgroundTexture(e){this._material.backgroundRefractionTexture=e}configureVolume(){this._material.geometryThinWalled=0}set geometryThinWalled(e){this._material.geometryThinWalled=e?1:0}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)}finalizeAsync(e){return b(this,void 0,void 0,function*(){var n,s,o;if(this._diffuseTransmissionTint&&!this._diffuseTransmissionTint.equals(t.Color3.White())||this._diffuseTransmissionTintTexture)if(this._material.geometryThinWalled)this.subsurfaceColor=this._diffuseTransmissionTint,this.subsurfaceColorTexture=this._diffuseTransmissionTintTexture;else if(yield this.copySurfaceToCoatAsync(e,this.subsurfaceWeight,this.subsurfaceWeightTexture,t.TextureChannel.A,this._diffuseTransmissionTint,this._diffuseTransmissionTintTexture,!0),e._disposed)return;if(this.transmissionWeight>0)if(this._material.geometryThinWalled||0===this._material.transmissionDepth)this._material.transmissionColor=this._material.baseColor,this._material.transmissionColorTexture=this._material.baseColorTexture;else if((!this.baseColor.equals(t.Color3.White())||null!==this.baseColorTexture)&&(yield this.copySurfaceToCoatAsync(e,this.transmissionWeight,this.transmissionWeightTexture,t.TextureChannel.R,this.baseColor,this.baseColorTexture,!1),e._disposed))return;if(this._specWorkflow){const r=yield t.InvertTextureAsync("newRoughnessTexture ("+this._material.name+")",yield t.ExtractChannelAsync("glossiness ("+this._material.name+")",t.CreateTextureWithFactorOperand(this.specularColorTexture,new t.Color4(this.specularColor.r,this.specularColor.g,this.specularColor.b,this.glossiness),t.TextureChannel.A,t.TextureColorSpace.Linear),t.TextureChannel.A,this._material.getScene(),t.TextureColorSpace.Linear,t.ChannelMask.R),this._material.getScene(),t.ChannelMask.R,t.TextureColorSpace.Linear,t.ChannelMask.R);if(e._disposed)return void(null===(n=r.texture)||void 0===n||n.dispose());this.specularRoughnessTexture=r.texture,this.specularRoughness=r.factor?r.factor.r:1;const i=yield t.ExtractMaxChannelAsync("metallicTexture ("+this._material.name+")",t.CreateTextureWithFactorOperand(this.specularColorTexture,this.specularColor.toColor4(),t.TextureChannel.RGBA,t.TextureColorSpace.Linear),this._material.getScene(),!1,t.TextureColorSpace.SRGB,t.ChannelMask.RGB);if(e._disposed)return void(null===(s=i.texture)||void 0===s||s.dispose());this.baseMetalnessTexture=i.texture,this.baseMetalness=i.factor?i.factor.r:1;const a=yield t.LerpTexturesAsync("newBaseColor ("+this._material.name+")",t.CreateTextureWithFactorOperand(this.baseColorTexture,this.baseColor.toColor4(),t.TextureChannel.RGBA,t.TextureColorSpace.Linear),t.CreateTextureWithFactorOperand(this.specularColorTexture,this.specularColor.toColor4(),t.TextureChannel.RGBA,t.TextureColorSpace.Linear),Object.assign(Object.assign({},i),{dispose:void 0,colorSpace:t.TextureColorSpace.Linear}),this._material.getScene(),t.TextureColorSpace.SRGB,t.ChannelMask.RGB);if(e._disposed)return void(null===(o=a.texture)||void 0===o||o.dispose());const l=this.baseColorTexture;null==l||l.dispose(),this.baseColorTexture=a.texture,this.baseColor=a.factor?new t.Color3(a.factor.r,a.factor.g,a.factor.b):t.Color3.White();const u=this.specularColorTexture;null==u||u.dispose(),this.specularColorTexture=null}})}copySurfaceToCoatAsync(e,n,s,o,r,i){return b(this,arguments,void 0,function*(e,n,s,o,r,i,a=!1){var l,u,c,d,h,m,f,p,_;const g=this._material.coatWeight,y=this._material.coatWeightTexture,v=this._material.coatColor.clone(),b=this._material.coatColorTexture,x=this._material.geometryCoatNormalTexture,T=new t.Color4(g,g,g,g),A=new t.Color4(n,n,n,n);this.coatWeightTexture=null,this.coatWeight=1;const M=yield Promise.allSettled([t.LerpTexturesAsync("lerpExistingCoat",t.CreateTextureWithFactorOperand(null,new t.Color4(1,1,1,1)),t.CreateTextureWithFactorOperand(b,v.toColor4(),t.TextureChannel.RGBA,t.TextureColorSpace.SRGB),t.CreateTextureWithFactorOperand(y,T,t.TextureChannel.R),this._material.getScene(),t.TextureColorSpace.SRGB),t.LerpTexturesAsync("lerpSurfaceColor",t.CreateTextureWithFactorOperand(null,new t.Color4(1,1,1,1)),t.CreateTextureWithFactorOperand(i,r.toColor4(),t.TextureChannel.RGBA,t.TextureColorSpace.SRGB),t.CreateTextureWithFactorOperand(s,A,o),this._material.getScene(),t.TextureColorSpace.SRGB)]),w=M.find(e=>"rejected"===e.status);if(w){for(const e of M)"fulfilled"===e.status&&(null===(l=e.value.texture)||void 0===l||l.dispose());throw w.reason}const[C,R]=M.map(e=>e.value);if(e._disposed)return null===(u=C.texture)||void 0===u||u.dispose(),void(null===(c=R.texture)||void 0===c||c.dispose());const S=yield t.MultiplyTexturesAsync("newCoatColor ("+this._material.name+")",C,R,this._material.getScene(),t.TextureColorSpace.SRGB);if(e._disposed)return void(null===(d=S.texture)||void 0===d||d.dispose());S.texture?(this.coatColorTexture=S.texture,this.coatColor=t.Color3.White()):S.factor&&(this.coatColorTexture=null,this.coatColor.fromArray([S.factor.r,S.factor.g,S.factor.b]));const O=yield t.LerpTexturesAsync("newCoatIor ("+this._material.name+")",t.CreateTextureWithFactorOperand(null,new t.Color4(this._material.specularIor,this._material.specularIor,this._material.specularIor,1),t.TextureChannel.R),t.CreateTextureWithFactorOperand(null,new t.Color4(this.coatIor,this.coatIor,this.coatIor,1),t.TextureChannel.R),t.CreateTextureWithFactorOperand(y,T,t.TextureChannel.R),this._material.getScene());if(e._disposed)return void(null===(h=O.texture)||void 0===h||h.dispose());this.coatIor=O.factor?O.factor.r:this.coatIor;const F=yield t.LerpTexturesAsync("newCoatRoughness ("+this._material.name+")",t.CreateTextureWithFactorOperand(this.specularRoughnessTexture,new t.Color4(this.specularRoughness,this.specularRoughness,this.specularRoughness,1),t.TextureChannel.G),t.CreateTextureWithFactorOperand(this.coatRoughnessTexture,new t.Color4(this.coatRoughness,this.coatRoughness,this.coatRoughness,1),t.TextureChannel.G),t.CreateTextureWithFactorOperand(y,T,t.TextureChannel.R),this._material.getScene());if(e._disposed)return void(null===(m=F.texture)||void 0===m||m.dispose());this.coatRoughness=F.factor?F.factor.r:1,this.coatRoughnessTexture=F.texture;const E=yield t.LerpTexturesAsync("newCoatDarkening ("+this._material.name+")",t.CreateTextureWithFactorOperand(null,new t.Color4(0,0,0,1),t.TextureChannel.R),t.CreateTextureWithFactorOperand(null,new t.Color4(this.coatDarkening,this.coatDarkening,this.coatDarkening,1),t.TextureChannel.R),t.CreateTextureWithFactorOperand(y,T,t.TextureChannel.R),this._material.getScene());if(e._disposed)null===(f=E.texture)||void 0===f||f.dispose();else{if(this.coatDarkening=E.factor?E.factor.r:this.coatDarkening,a){const n=yield t.LerpTexturesAsync("newSpecularRoughness ("+this._material.name+")",t.CreateTextureWithFactorOperand(this.specularRoughnessTexture,new t.Color4(this._material.specularRoughness,this._material.specularRoughness,this._material.specularRoughness,1),t.TextureChannel.G),t.CreateTextureWithFactorOperand(null,new t.Color4(1,1,1,1),t.TextureChannel.R),t.CreateTextureWithFactorOperand(s,A,o),this._material.getScene());if(e._disposed)return void(null===(p=n.texture)||void 0===p||p.dispose());this.specularRoughness=n.factor?n.factor.r:1,this.specularRoughnessTexture=n.texture}if(x||this.geometryNormalTexture){const n=yield t.LerpTexturesAsync("newCoatNormal ("+this._material.name+")",t.CreateTextureWithFactorOperand(this.geometryNormalTexture,this.geometryNormalTexture?new t.Color4(1,1,1,1):new t.Color4(.5,.5,1,1),t.TextureChannel.RGBA),t.CreateTextureWithFactorOperand(x,x?new t.Color4(1,1,1,1):new t.Color4(.5,.5,1,1),t.TextureChannel.RGBA),t.CreateTextureWithFactorOperand(y,T,t.TextureChannel.R),this._material.getScene());if(e._disposed)return void(null===(_=n.texture)||void 0===_||_.dispose());n.texture&&(this.geometryCoatNormalTexture=n.texture)}}})}}var Ns={__proto__:null,OpenPBRMaterialLoadingAdapter:Bs};class ks{constructor(e){this._specWorkflow=!1,this._material=e,this._material.enableSpecularAntiAliasing=!0}get material(){return this._material}finalizeAsync(e){return b(this,void 0,void 0,function*(){})}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=t.Constants.MATERIAL_DIFFUSE_MODEL_E_OREN_NAYAR)}get baseDiffuseRoughness(){var e;return null!==(e=this._material.baseDiffuseRoughness)&&void 0!==e?e:0}set baseDiffuseRoughnessTexture(e){this._material.baseDiffuseRoughnessTexture=e}get baseDiffuseRoughnessTexture(){return this._material.baseDiffuseRoughnessTexture}set baseMetalness(e){this._material.metallic=e}get baseMetalness(){var e;return null!==(e=this._material.metallic)&&void 0!==e?e: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=t.Constants.MATERIAL_DIELECTRIC_SPECULAR_MODEL_OPENPBR,this._material.brdf.conductorSpecularModel=t.Constants.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(){var e;return null!==(e=this._material.metallicF0Factor)&&void 0!==e?e: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(){var e;return null!==(e=this._material.roughness)&&void 0!==e?e: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(){var e;return null!==(e=this._material.microSurface)&&void 0!==e?e: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(){var e;return null!==(e=this._material.ambientTextureStrength)&&void 0!==e?e: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!=t.Color3.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(){var e;return null!==(e=this._material.clearCoat.roughness)&&void 0!==e?e: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 t.Color3(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 t.Color3(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)}get 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 0===this._material.subSurface.maximumThickness}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){const n=new t.Vector3(-Math.log(this.transmissionColor.r),-Math.log(this.transmissionColor.g),-Math.log(this.transmissionColor.b));n.scaleInPlace(1/Math.max(this.transmissionDepth,.001));const s=n,o=Math.max(s.x,Math.max(s.y,s.z)),r=o>0?1/o:1;this._material.subSurface.diffusionDistance=new t.Color3(Math.exp(-s.x*r),Math.exp(-s.y*r),Math.exp(-s.z*r))}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(){var e;return null!==(e=this._material.subSurface.scatteringDiffusionProfile)&&void 0!==e?e:t.Color3.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)}}var Ds={__proto__:null,PBRMaterialLoadingAdapter:ks};const Gs="EXT_lights_image_based";let Vs=class{constructor(e){this.name=Gs,this._loader=e,this.enabled=this._loader.isExtensionUsed(Gs)}dispose(){this._loader=null,delete this._lights}onLoading(){const e=this._loader.gltf.extensions;if(e&&e[this.name]){const t=e[this.name];this._lights=t.lights}}loadSceneAsync(e,t){return Ms.LoadExtensionAsync(e,t,this.name,(n,s)=>b(this,void 0,void 0,function*(){this._loader._allMaterialsDirtyRequired=!0;const o=new Array;o.push(this._loader.loadSceneAsync(e,t)),this._loader.logOpen(`${n}`);const r=Ts.Get(`${n}/light`,this._lights,s.light);return o.push(this._loadLightAsync(`/extensions/${this.name}/lights/${s.light}`,r).then(e=>{this._loader.babylonScene.environmentTexture=e})),this._loader.logClose(),yield Promise.all(o).then(()=>{})}))}_loadLightAsync(e,n){if(!n._loaded){const s=new Array;this._loader.logOpen(`${e}`);const o=new Array(n.specularImages.length);for(let t=0;t<n.specularImages.length;t++){const r=n.specularImages[t];o[t]=new Array(r.length);for(let n=0;n<r.length;n++){const i=`${e}/specularImages/${t}/${n}`;this._loader.logOpen(`${i}`);const a=r[n],l=Ts.Get(i,this._loader.gltf.images,a);s.push(this._loader.loadImageAsync(`/images/${a}`,l).then(e=>{o[t][n]=e})),this._loader.logClose()}}this._loader.logClose(),n._loaded=Promise.all(s).then(()=>b(this,void 0,void 0,function*(){const s=new t.RawCubeTexture(this._loader.babylonScene,null,n.specularImageSize);if(s.name=n.name||"environment",n._babylonTexture=s,null!=n.intensity&&(s.level=n.intensity),n.rotation){let e=t.Quaternion.FromArray(n.rotation);this._loader.babylonScene.useRightHandedSystem||(e=t.Quaternion.Inverse(e)),t.Matrix.FromQuaternionToRef(e,s.getReflectionTextureMatrix())}if(!n.irradianceCoefficients)throw new Error(`${e}: Irradiance coefficients are missing`);const r=t.SphericalHarmonics.FromArray(n.irradianceCoefficients);r.scaleInPlace(n.intensity),r.convertIrradianceToLambertianRadiance();const i=t.SphericalPolynomial.FromHarmonics(r),a=(o.length-1)/Math.log2(n.specularImageSize);return yield s.updateRGBDAsync(o,i,a)}))}return n._loaded.then(()=>n._babylonTexture)}},Hs=!1;function Ks(){Hs||(Hs=!0,ns(Gs),ts(Gs,!0,e=>new Vs(e)))}Ks();var $s={__proto__:null,EXT_lights_image_based:Vs,RegisterEXT_lights_image_based:Ks};const Us="EXT_mesh_gpu_instancing";let qs=class{constructor(e){this.name=Us,this._loader=e,this.enabled=this._loader.isExtensionUsed(Us)}dispose(){this._loader=null}loadNodeAsync(e,n,s){return Ms.LoadExtensionAsync(e,n,this.name,(e,o)=>b(this,void 0,void 0,function*(){this._loader._disableInstancedMesh++;const r=this._loader.loadNodeAsync(`/nodes/${n.index}`,n,s);if(this._loader._disableInstancedMesh--,!n._primitiveBabylonMeshes)return yield r;const i=new Array;let a=0;const l=t=>{if(null==o.attributes[t])return void i.push(Promise.resolve(null));const n=Ts.Get(`${e}/attributes/${t}`,this._loader.gltf.accessors,o.attributes[t]);if(i.push(this._loader._loadFloatAccessorAsync(`/accessors/${n.bufferView}`,n)),0===a)a=n.count;else if(a!==n.count)throw new Error(`${e}/attributes: Instance buffer accessors do not have the same count.`)};return l("TRANSLATION"),l("ROTATION"),l("SCALE"),l("_COLOR_0"),yield r.then(e=>b(this,void 0,void 0,function*(){const[s,o,r,l]=yield Promise.all(i),u=new Float32Array(16*a);t.TmpVectors.Vector3[0].copyFromFloats(0,0,0),t.TmpVectors.Quaternion[0].copyFromFloats(0,0,0,1),t.TmpVectors.Vector3[1].copyFromFloats(1,1,1);for(let e=0;e<a;++e)s&&t.Vector3.FromArrayToRef(s,3*e,t.TmpVectors.Vector3[0]),o&&t.Quaternion.FromArrayToRef(o,4*e,t.TmpVectors.Quaternion[0]),r&&t.Vector3.FromArrayToRef(r,3*e,t.TmpVectors.Vector3[1]),t.Matrix.ComposeToRef(t.TmpVectors.Vector3[1],t.TmpVectors.Quaternion[0],t.TmpVectors.Vector3[0],t.TmpVectors.Matrix[0]),t.TmpVectors.Matrix[0].copyToArray(u,16*e);for(const e of n._primitiveBabylonMeshes)e.thinInstanceSetBuffer("matrix",u,16,!0),l&&(l.length===3*a?e.thinInstanceSetBuffer("color",l,3,!0):l.length===4*a?e.thinInstanceSetBuffer("color",l,4,!0):t.Logger.Warn("Unexpected size of _COLOR_0 attribute for mesh "+e.name));return e}))}))}},Ws=!1;function zs(){Ws||(Ws=!0,ns(Us),ts(Us,!0,e=>new qs(e)))}zs();var js={__proto__:null,EXT_mesh_gpu_instancing:qs,RegisterEXT_mesh_gpu_instancing:zs};const Xs="EXT_meshopt_compression";let Ys=class{constructor(e){this.name=Xs,this.enabled=e.isExtensionUsed(Xs),this._loader=e}dispose(){this._loader=null}loadBufferViewAsync(e,n){return Ms.LoadExtensionAsync(e,n,this.name,(s,o)=>b(this,void 0,void 0,function*(){const s=n;if(s._meshOptData)return yield s._meshOptData;const r=Ts.Get(`${e}/buffer`,this._loader.gltf.buffers,o.buffer);return s._meshOptData=this._loader.loadBufferAsync(`/buffers/${r.index}`,r,o.byteOffset||0,o.byteLength).then(e=>b(this,void 0,void 0,function*(){return yield t.MeshoptCompression.Default.decodeGltfBufferAsync(e,o.count,o.byteStride,o.mode,o.filter)})),yield s._meshOptData}))}},Qs=!1;function Zs(){Qs||(Qs=!0,ns(Xs),ts(Xs,!0,e=>new Ys(e)))}Zs();var Js={__proto__:null,EXT_meshopt_compression:Ys,RegisterEXT_meshopt_compression:Zs};const eo="EXT_texture_webp";let to=class{constructor(e){this.name=eo,this._loader=e,this.enabled=e.isExtensionUsed(eo)}dispose(){this._loader=null}_loadTextureAsync(e,t,n){return Ms.LoadExtensionAsync(e,t,this.name,(s,o)=>b(this,void 0,void 0,function*(){const r=null==t.sampler?Ms.DefaultSampler:Ts.Get(`${e}/sampler`,this._loader.gltf.samplers,t.sampler),i=Ts.Get(`${s}/source`,this._loader.gltf.images,o.source);return yield this._loader._createTextureAsync(e,r,i,e=>{n(e)},void 0,!t._textureInfo.nonColorData)}))}},no=!1;function so(){no||(no=!0,ns(eo),ts(eo,!0,e=>new to(e)))}so();var oo={__proto__:null,EXT_texture_webp:to,RegisterEXT_texture_webp:so};const ro="EXT_texture_avif";let io=class{constructor(e){this.name=ro,this._loader=e,this.enabled=e.isExtensionUsed(ro)}dispose(){this._loader=null}_loadTextureAsync(e,t,n){return Ms.LoadExtensionAsync(e,t,this.name,(s,o)=>b(this,void 0,void 0,function*(){const r=null==t.sampler?Ms.DefaultSampler:Ts.Get(`${e}/sampler`,this._loader.gltf.samplers,t.sampler),i=Ts.Get(`${s}/source`,this._loader.gltf.images,o.source);return yield this._loader._createTextureAsync(e,r,i,e=>{n(e)},void 0,!t._textureInfo.nonColorData)}))}},ao=!1;function lo(){ao||(ao=!0,ns(ro),ts(ro,!0,e=>new io(e)))}lo();var uo={__proto__:null,EXT_texture_avif:io,RegisterEXT_texture_avif:lo};const co="EXT_lights_ies";let ho=class{constructor(e){this.name=co,this._loader=e,this.enabled=this._loader.isExtensionUsed(co)}dispose(){this._loader=null,delete this._lights}onLoading(){const e=this._loader.gltf.extensions;if(e&&e[this.name]){const t=e[this.name];this._lights=t.lights,Ts.Assign(this._lights)}}loadNodeAsync(e,n,s){return Ms.LoadExtensionAsync(e,n,this.name,(o,r)=>b(this,void 0,void 0,function*(){let i,a;this._loader._allMaterialsDirtyRequired=!0;const l=yield this._loader.loadNodeAsync(e,n,e=>{a=Ts.Get(o,this._lights,r.light);const n=a.name||e.name;this._loader.babylonScene._blockEntityCollection=!!this._loader._assetContainer,i=new t.SpotLight(n,t.Vector3.Zero(),t.Vector3.Backward(),0,1,this._loader.babylonScene),i.angle=Math.PI/2,i.innerAngle=0,i._parentContainer=this._loader._assetContainer,this._loader.babylonScene._blockEntityCollection=!1,a._babylonLight=i,i.falloffType=t.Light.FALLOFF_GLTF,i.diffuse=r.color?t.Color3.FromArray(r.color):t.Color3.White(),i.intensity=r.multiplier||1,i.range=Number.MAX_VALUE,i.parent=e,this._loader._babylonLights.push(i),Ms.AddPointerMetadata(i,o),s(e)});let u;if(a.uri)u=yield this._loader.loadUriAsync(e,a,a.uri);else{const t=Ts.Get(`${e}/bufferView`,this._loader.gltf.bufferViews,a.bufferView);u=yield this._loader.loadBufferViewAsync(`/bufferViews/${t.index}`,t)}return i.iesProfileTexture=new t.Texture(i.name+"_iesProfile",this._loader.babylonScene,!0,!1,void 0,null,null,u,!0,void 0,void 0,void 0,void 0,".ies"),l}))}},mo=!1;function fo(){mo||(mo=!0,ns(co),ts(co,!0,e=>new ho(e)))}fo();var po={__proto__:null,EXT_lights_ies:ho,RegisterEXT_lights_ies:fo};const _o="KHR_draco_mesh_compression";let go=class{constructor(e){this.name=_o,this.useNormalizedFlagFromAccessor=!0,this._loader=e,this.enabled=t.DracoDecoder.DefaultAvailable&&this._loader.isExtensionUsed(_o)}dispose(){delete this.dracoDecoder,this._loader=null}_loadVertexDataAsync(e,n,s){return Ms.LoadExtensionAsync(e,n,this.name,(o,r)=>b(this,void 0,void 0,function*(){if(null!=n.mode&&4!==n.mode&&5!==n.mode)throw new Error(`${e}: Unsupported mode ${n.mode}`);const i={},a={},l=(e,t)=>{const o=r.attributes[e];if(null!=o&&(s._delayInfo=s._delayInfo||[],-1===s._delayInfo.indexOf(t)&&s._delayInfo.push(t),i[t]=o,this.useNormalizedFlagFromAccessor)){const s=Ts.TryGet(this._loader.gltf.accessors,n.attributes[e]);s&&(a[t]=s.normalized||!1)}};l("POSITION",t.VertexBuffer.PositionKind),l("NORMAL",t.VertexBuffer.NormalKind),l("TANGENT",t.VertexBuffer.TangentKind),l("TEXCOORD_0",t.VertexBuffer.UVKind),l("TEXCOORD_1",t.VertexBuffer.UV2Kind),l("TEXCOORD_2",t.VertexBuffer.UV3Kind),l("TEXCOORD_3",t.VertexBuffer.UV4Kind),l("TEXCOORD_4",t.VertexBuffer.UV5Kind),l("TEXCOORD_5",t.VertexBuffer.UV6Kind),l("JOINTS_0",t.VertexBuffer.MatricesIndicesKind),l("WEIGHTS_0",t.VertexBuffer.MatricesWeightsKind),l("COLOR_0",t.VertexBuffer.ColorKind);const u=Ts.Get(o,this._loader.gltf.bufferViews,r.bufferView);return u._dracoBabylonGeometry||(u._dracoBabylonGeometry=this._loader.loadBufferViewAsync(`/bufferViews/${u.index}`,u).then(o=>b(this,void 0,void 0,function*(){const r=this.dracoDecoder||t.DracoDecoder.Default,l=Ts.TryGet(this._loader.gltf.accessors,n.attributes.POSITION),u=this._loader.parent.alwaysComputeBoundingBox||s.skeleton||!l?null:As(l);return yield r._decodeMeshToGeometryForGltfAsync(s.name,this._loader.babylonScene,o,i,a,u).catch(t=>{throw new Error(`${e}: ${t.message}`)})}))),yield u._dracoBabylonGeometry}))}},yo=!1;function vo(){yo||(yo=!0,ns(_o),ts(_o,!0,e=>new go(e)))}vo();var bo={__proto__:null,KHR_draco_mesh_compression:go,RegisterKHR_draco_mesh_compression:vo};const xo="KHR_gaussian_splatting",To=.28209479177387814,Ao=[0,3,5,7];function Mo(e){return e<=0?0:e>=255?255:e+.5|0}let wo=class{constructor(e){this.name=xo,this._loader=e,this.enabled=this._loader.isExtensionUsed(xo)}dispose(){this._loader=null}_loadMeshPrimitiveAsync(e,n,s,o,r,i){return Ms.LoadExtensionAsync(e,r,this.name,s=>b(this,void 0,void 0,function*(){if(null!=r.mode&&0!==r.mode)throw new Error(`${s}: Gaussian splatting primitives must use POINTS mode`);const o=this._loader,a=t=>{const n=r.attributes[t];if(null==n)return null;const s=Ts.Get(`${e}/attributes/${t}`,o.gltf.accessors,n);return o._loadFloatAccessorAsync(`/accessors/${s.index}`,s)},l=a("POSITION");if(!l)throw new Error(`${s}: Gaussian splatting primitive is missing the POSITION attribute`);let u=0;const c=[];for(let e=1;e<=3&&null!=r.attributes[`KHR_gaussian_splatting:SH_DEGREE_${e}_COEF_0`];e++){u=e;for(let t=0;t<Ao[e];t++)c.push(`KHR_gaussian_splatting:SH_DEGREE_${e}_COEF_${t}`)}const d=o.babylonScene;d._blockEntityCollection=!!o._assetContainer;const h=new t.GaussianSplattingMesh(n,null,d);h._parentContainer=o._assetContainer,d._blockEntityCollection=!1,Ms.AddPointerMetadata(h,e),o.parent.onMeshLoadedObservable.notifyObservers(h),i(h);const m=d.getEngine().getCaps(),[f,p,_,g,y,v,...b]=yield Promise.all([l,a("KHR_gaussian_splatting:ROTATION"),a("KHR_gaussian_splatting:SCALE"),a("KHR_gaussian_splatting:OPACITY"),a("KHR_gaussian_splatting:SH_DEGREE_0_COEF_0"),a("COLOR_0"),...c.map(e=>a(e))]),x=f.length/3,T=v?v.length/x:0,A=new ArrayBuffer(32*x),M=new Float32Array(A),w=new Uint8Array(A);let C=null;if(u>0){const e=3*((u+1)*(u+1)-1),n=Math.ceil(e/16),s=m.maxTextureSize,o=Math.ceil(x/s);C=t.AllocateShBuffers(n,o*s*4*4)}for(let e=0;e<x;e++){const t=8*e,n=32*e,s=3*e;if(M[t+0]=f[s+0],M[t+1]=f[s+1],M[t+2]=f[s+2],M[t+3]=_?_[s+0]:1,M[t+4]=_?_[s+1]:1,M[t+5]=_?_[s+2]:1,y)w[n+24]=Mo(255*(.5+To*y[s+0])),w[n+25]=Mo(255*(.5+To*y[s+1])),w[n+26]=Mo(255*(.5+To*y[s+2]));else if(v){const t=e*T;w[n+24]=Mo(255*v[t+0]),w[n+25]=Mo(255*v[t+1]),w[n+26]=Mo(255*v[t+2])}else w[n+24]=255,w[n+25]=255,w[n+26]=255;w[n+27]=g?Mo(255*g[e]):v&&T>=4?Mo(255*v[e*T+3]):255;const o=4*e,r=p?p[o+0]:0,i=p?p[o+1]:0,a=p?p[o+2]:0,l=p?p[o+3]:1;if(w[n+28]=Mo(127.5*l+127.5),w[n+29]=Mo(127.5*r+127.5),w[n+30]=Mo(127.5*i+127.5),w[n+31]=Mo(127.5*a+127.5),C){const t=16*e;for(let e=0;e<b.length;e++){const n=b[e];if(n)for(let o=0;o<3;o++){const r=3*e+o,i=15&r;C[r>>4][t+i]=Mo(128*n[s+o]+128)}}}}return yield h.updateDataAsync(A,null!=C?C:void 0,void 0,u||void 0),h}))}},Co=!1;function Ro(){Co||(Co=!0,ns(xo),ts(xo,!0,e=>new wo(e)))}Ro();var So={__proto__:null,KHR_gaussian_splatting:wo,RegisterKHR_gaussian_splatting:Ro};const Oo="KHR_lights_punctual";class Fo{constructor(e){this.name=Oo,this._loader=e,this.enabled=this._loader.isExtensionUsed(Oo)}dispose(){this._loader=null,delete this._lights}onLoading(){const e=this._loader.gltf.extensions;if(e&&e[this.name]){const t=e[this.name];this._lights=t.lights,Ts.Assign(this._lights)}}loadNodeAsync(e,n,s){return Ms.LoadExtensionAsync(e,n,this.name,(o,r)=>b(this,void 0,void 0,function*(){return this._loader._allMaterialsDirtyRequired=!0,yield this._loader.loadNodeAsync(e,n,e=>{let n;const i=Ts.Get(o,this._lights,r.light),a=i.name||e.name;switch(this._loader.babylonScene._blockEntityCollection=!!this._loader._assetContainer,i.type){case"directional":{const e=new t.DirectionalLight(a,t.Vector3.Backward(),this._loader.babylonScene);e.position.setAll(0),n=e;break}case"point":n=new t.PointLight(a,t.Vector3.Zero(),this._loader.babylonScene);break;case"spot":{const e=new t.SpotLight(a,t.Vector3.Zero(),t.Vector3.Backward(),0,1,this._loader.babylonScene);e.angle=2*(i.spot&&i.spot.outerConeAngle||Math.PI/4),e.innerAngle=2*(i.spot&&i.spot.innerConeAngle||0),n=e;break}default:throw this._loader.babylonScene._blockEntityCollection=!1,new Error(`${o}: Invalid light type (${i.type})`)}n._parentContainer=this._loader._assetContainer,this._loader.babylonScene._blockEntityCollection=!1,i._babylonLight=n,n.falloffType=t.Light.FALLOFF_GLTF,n.diffuse=i.color?t.Color3.FromArray(i.color):t.Color3.White(),n.intensity=null==i.intensity?1:i.intensity,n.range=null==i.range?Number.MAX_VALUE:i.range,n.parent=e,this._loader._babylonLights.push(n),Ms.AddPointerMetadata(n,o),s(e)})}))}}let Eo=!1;function Io(){Eo||(Eo=!0,ns(Oo),ts(Oo,!0,e=>new Fo(e)))}Io();var Lo={__proto__:null,KHR_lights:Fo,RegisterKHR_lights:Io};const Po="EXT_lights_area";let Bo=class{constructor(e){this.name=Po,this._loader=e,this.enabled=this._loader.isExtensionUsed(Po)}dispose(){this._loader=null,delete this._lights}onLoading(){const e=this._loader.gltf.extensions;if(e&&e[this.name]){const t=e[this.name];this._lights=t.lights,Ts.Assign(this._lights)}}loadNodeAsync(e,n,s){return Ms.LoadExtensionAsync(e,n,this.name,(o,r)=>b(this,void 0,void 0,function*(){return this._loader._allMaterialsDirtyRequired=!0,yield this._loader.loadNodeAsync(e,n,e=>{var n;let i;const a=Ts.Get(o,this._lights,r.light),l=a.name||e.name;this._loader.babylonScene._blockEntityCollection=!!this._loader._assetContainer;const u=void 0!==a.size?a.size:1;switch(a.type){case"rect":{const e=void 0!==(null===(n=a.rect)||void 0===n?void 0:n.aspect)?a.rect.aspect*u:u,s=u;i=new t.RectAreaLight(l,t.Vector3.Zero(),e,s,this._loader.babylonScene);break}case"disk":{const e=Math.sqrt(u*u*.25*Math.PI);i=new t.RectAreaLight(l,t.Vector3.Zero(),e,e,this._loader.babylonScene);break}default:throw this._loader.babylonScene._blockEntityCollection=!1,new Error(`${o}: Invalid area light type (${a.type})`)}i._parentContainer=this._loader._assetContainer,this._loader.babylonScene._blockEntityCollection=!1,a._babylonLight=i,i.falloffType=t.Light.FALLOFF_GLTF,i.diffuse=a.color?t.Color3.FromArray(a.color):t.Color3.White(),i.intensity=null==a.intensity?1:a.intensity;const c=new t.TransformNode(`${l}_orientation`,this._loader.babylonScene);c.rotationQuaternion=t.Quaternion.RotationAxis(t.Vector3.Up(),Math.PI),c.parent=e,i.parent=c,this._loader._babylonLights.push(i),Ms.AddPointerMetadata(i,o),s(e)})}))}},No=!1;function ko(){No||(No=!0,ns(Po),ts(Po,!0,e=>new Bo(e)))}ko();var Do={__proto__:null,EXT_lights_area:Bo,RegisterEXT_lights_area:ko};const Go="KHR_materials_pbrSpecularGlossiness";let Vo=class{constructor(e){this.name=Go,this.order=200,this._loader=e,this.enabled=this._loader.isExtensionUsed(Go)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return Ms.LoadExtensionAsync(e,t,this.name,(s,o)=>b(this,void 0,void 0,function*(){const r=new Array;return r.push(this._loader.loadMaterialBasePropertiesAsync(e,t,n)),r.push(this._loadSpecularGlossinessPropertiesAsync(s,o,n)),this._loader.loadMaterialAlphaProperties(e,t,n),yield Promise.all(r).then(()=>{})}))}_loadSpecularGlossinessPropertiesAsync(e,n,s){const o=this._loader._getOrCreateMaterialAdapter(s),r=new Array;return o.configureSpecularGlossiness(),n.diffuseFactor?(o.baseColor=t.Color3.FromArray(n.diffuseFactor),s.alpha=n.diffuseFactor[3]):o.baseColor=t.Color3.White(),o.specularColor=n.specularFactor?t.Color3.FromArray(n.specularFactor):t.Color3.White(),o.glossiness=null==n.glossinessFactor?1:n.glossinessFactor,n.diffuseTexture&&r.push(this._loader.loadTextureInfoAsync(`${e}/diffuseTexture`,n.diffuseTexture,e=>{e.name=`${s.name} (Diffuse)`,o.baseColorTexture=e})),n.specularGlossinessTexture&&r.push(this._loader.loadTextureInfoAsync(`${e}/specularGlossinessTexture`,n.specularGlossinessTexture,e=>{e.name=`${s.name} (Specular Glossiness)`,o.specularColorTexture=e})),Promise.all(r).then(()=>{})}},Ho=!1;function Ko(){Ho||(Ho=!0,ns(Go),ts(Go,!0,e=>new Vo(e)))}Ko();var $o={__proto__:null,KHR_materials_pbrSpecularGlossiness:Vo,RegisterKHR_materials_pbrSpecularGlossiness:Ko};const Uo="KHR_materials_unlit";let qo=class{constructor(e){this.name=Uo,this.order=210,this._loader=e,this.enabled=this._loader.isExtensionUsed(Uo)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return Ms.LoadExtensionAsync(e,t,this.name,()=>b(this,void 0,void 0,function*(){return yield this._loadUnlitPropertiesAsync(e,t,n)}))}_loadUnlitPropertiesAsync(e,n,s){const o=this._loader._getOrCreateMaterialAdapter(s),r=new Array,i=n.pbrMetallicRoughness;return i&&(i.baseColorFactor&&(o.baseColor=t.Color3.FromArray(i.baseColorFactor),o.geometryOpacity=i.baseColorFactor[3]),i.baseColorTexture&&r.push(this._loader.loadTextureInfoAsync(`${e}/baseColorTexture`,i.baseColorTexture,e=>{e.name=`${s.name} (Base Color)`,o.baseColorTexture=e}))),o.isUnlit=!0,n.doubleSided&&(o.backFaceCulling=!1,o.twoSidedLighting=!0),this._loader.loadMaterialAlphaProperties(e,n,s),Promise.all(r).then(()=>{})}},Wo=!1;function zo(){Wo||(Wo=!0,ns(Uo),ts(Uo,!0,e=>new qo(e)))}zo();var jo={__proto__:null,KHR_materials_unlit:qo,RegisterKHR_materials_unlit:zo};const Xo="KHR_materials_clearcoat";let Yo=class{constructor(e){this.name=Xo,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(Xo)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return Ms.LoadExtensionAsync(e,t,this.name,(s,o)=>b(this,void 0,void 0,function*(){const r=new Array;r.push(this._loader.loadMaterialPropertiesAsync(e,t,n)),r.push(this._loadClearCoatPropertiesAsync(s,o,n)),yield Promise.all(r)}))}_loadClearCoatPropertiesAsync(e,t,n){const s=this._loader._getOrCreateMaterialAdapter(n),o=new Array;return s.configureCoat(),s.coatWeight=void 0!==t.clearcoatFactor?t.clearcoatFactor:0,s.coatRoughness=void 0!==t.clearcoatRoughnessFactor?t.clearcoatRoughnessFactor:0,t.clearcoatTexture&&o.push(this._loader.loadTextureInfoAsync(`${e}/clearcoatTexture`,t.clearcoatTexture,e=>{e.name=`${n.name} (ClearCoat)`,s.coatWeightTexture=e})),t.clearcoatRoughnessTexture&&(t.clearcoatRoughnessTexture.nonColorData=!0,o.push(this._loader.loadTextureInfoAsync(`${e}/clearcoatRoughnessTexture`,t.clearcoatRoughnessTexture,e=>{e.name=`${n.name} (ClearCoat Roughness)`,s.coatRoughnessTexture=e}))),t.clearcoatNormalTexture&&(t.clearcoatNormalTexture.nonColorData=!0,o.push(this._loader.loadTextureInfoAsync(`${e}/clearcoatNormalTexture`,t.clearcoatNormalTexture,e=>{var o;e.name=`${n.name} (ClearCoat Normal)`,s.geometryCoatNormalTexture=e,null!=(null===(o=t.clearcoatNormalTexture)||void 0===o?void 0:o.scale)&&(s.geometryCoatNormalTextureScale=t.clearcoatNormalTexture.scale)})),s.setNormalMapInversions(!n.getScene().useRightHandedSystem,n.getScene().useRightHandedSystem)),Promise.all(o).then(()=>{})}},Qo=!1;function Zo(){Qo||(Qo=!0,ns(Xo),ts(Xo,!0,e=>new Yo(e)))}Zo();var Jo={__proto__:null,KHR_materials_clearcoat:Yo,RegisterKHR_materials_clearcoat:Zo};const er="KHR_materials_coat";let tr=class{constructor(e){this.name=er,this.order=191,this.useOpenPBR=!1,this._loader=e,this.enabled=this._loader.isExtensionUsed(er)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return Ms.LoadExtensionAsync(e,t,this.name,(s,o)=>b(this,void 0,void 0,function*(){const r=new Array;r.push(this._loader.loadMaterialPropertiesAsync(e,t,n)),t.extensions&&t.extensions.KHR_materials_openpbr&&(this.useOpenPBR=!0),r.push(this._loadCoatPropertiesAsync(s,o,n)),yield Promise.all(r)}))}_loadCoatPropertiesAsync(e,n,s){var o,r;const i=this._loader._getOrCreateMaterialAdapter(s),a=new Array;i.configureCoat(),i.coatWeight=void 0!==n.coatFactor?n.coatFactor:0,i.coatRoughness=void 0!==n.coatRoughnessFactor?n.coatRoughnessFactor:0,n.coatTexture&&a.push(this._loader.loadTextureInfoAsync(`${e}/coatTexture`,n.coatTexture,e=>{e.name=`${s.name} (Coat)`,i.coatWeightTexture=e})),n.coatRoughnessTexture&&(n.coatRoughnessTexture.nonColorData=!0,a.push(this._loader.loadTextureInfoAsync(`${e}/coatRoughnessTexture`,n.coatRoughnessTexture,e=>{e.name=`${s.name} (Coat Roughness)`,i.coatRoughnessTexture=e}))),n.coatNormalTexture&&(n.coatNormalTexture.nonColorData=!0,a.push(this._loader.loadTextureInfoAsync(`${e}/coatNormalTexture`,n.coatNormalTexture,e=>{var t;e.name=`${s.name} (Coat Normal)`,i.geometryCoatNormalTexture=e,null!=(null===(t=n.coatNormalTexture)||void 0===t?void 0:t.scale)&&(i.geometryCoatNormalTextureScale=n.coatNormalTexture.scale)})),i.setNormalMapInversions(!s.getScene().useRightHandedSystem,s.getScene().useRightHandedSystem)),i.coatDarkening=void 0!==n.coatDarkeningFactor?n.coatDarkeningFactor:1,i.coatIor=void 0!==n.coatIor?n.coatIor:1.5;const l=t.Color3.White();void 0!==n.coatColorFactor&&l.fromArray(n.coatColorFactor),i.coatColor=l,n.coatColorTexture&&a.push(this._loader.loadTextureInfoAsync(`${e}/coatColorTexture`,n.coatColorTexture,e=>{e.name=`${s.name} (Coat Color)`,i.coatColorTexture=e}));const u=null!==(o=n.coatAnisotropyStrength)&&void 0!==o?o:0,c=null!==(r=n.coatAnisotropyRotation)&&void 0!==r?r:0;return i.coatRoughnessAnisotropy=u,i.geometryCoatTangentAngle=c,this.useOpenPBR||i.configureGltfStyleAnisotropy(!0),n.coatAnisotropyTexture&&(n.coatAnisotropyTexture.nonColorData=!0,a.push(this._loader.loadTextureInfoAsync(`${e}/coatAnisotropyTexture`,n.coatAnisotropyTexture,e=>{e.name=`${s.name} (Coat Anisotropy)`,i.geometryCoatTangentTexture=e}))),Promise.all(a).then(()=>{})}},nr=!1;function sr(){nr||(nr=!0,ns(er),ts(er,!0,e=>new tr(e)))}sr();var or={__proto__:null,KHR_materials_coat:tr,RegisterKHR_materials_coat:sr};const rr="KHR_materials_iridescence";let ir=class{constructor(e){this.name=rr,this.order=195,this._loader=e,this.enabled=this._loader.isExtensionUsed(rr)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return Ms.LoadExtensionAsync(e,t,this.name,(s,o)=>b(this,void 0,void 0,function*(){const r=new Array;return r.push(this._loader.loadMaterialPropertiesAsync(e,t,n)),r.push(this._loadIridescencePropertiesAsync(s,o,n)),yield Promise.all(r).then(()=>{})}))}_loadIridescencePropertiesAsync(e,t,n){var s,o,r,i,a;const l=this._loader._getOrCreateMaterialAdapter(n),u=new Array;return l.thinFilmWeight=null!==(s=t.iridescenceFactor)&&void 0!==s?s:0,l.thinFilmIor=null!==(r=null!==(o=t.iridescenceIor)&&void 0!==o?o:t.iridescenceIOR)&&void 0!==r?r:1.3,l.thinFilmThicknessMinimum=null!==(i=t.iridescenceThicknessMinimum)&&void 0!==i?i:100,l.thinFilmThicknessMaximum=null!==(a=t.iridescenceThicknessMaximum)&&void 0!==a?a:400,t.iridescenceTexture&&u.push(this._loader.loadTextureInfoAsync(`${e}/iridescenceTexture`,t.iridescenceTexture,e=>{e.name=`${n.name} (Iridescence)`,l.thinFilmWeightTexture=e})),t.iridescenceThicknessTexture&&u.push(this._loader.loadTextureInfoAsync(`${e}/iridescenceThicknessTexture`,t.iridescenceThicknessTexture,e=>{e.name=`${n.name} (Iridescence Thickness)`,l.thinFilmThicknessTexture=e})),Promise.all(u).then(()=>{})}},ar=!1;function lr(){ar||(ar=!0,ns(rr),ts(rr,!0,e=>new ir(e)))}lr();var ur={__proto__:null,KHR_materials_iridescence:ir,RegisterKHR_materials_iridescence:lr};const cr="KHR_materials_anisotropy";let dr=class{constructor(e){this.name=cr,this.order=195,this._loader=e,this.enabled=this._loader.isExtensionUsed(cr)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return Ms.LoadExtensionAsync(e,t,this.name,(s,o)=>b(this,void 0,void 0,function*(){const r=new Array;r.push(this._loader.loadMaterialPropertiesAsync(e,t,n)),r.push(this._loadAnisotropyPropertiesAsync(s,o,n)),yield Promise.all(r)}))}_loadAnisotropyPropertiesAsync(e,t,n){return b(this,void 0,void 0,function*(){var s,o,r;const i=this._loader._getOrCreateMaterialAdapter(n),a=new Array,l=null!==(s=t.anisotropyStrength)&&void 0!==s?s:0,u=null!==(o=t.anisotropyRotation)&&void 0!==o?o:0;i.specularRoughnessAnisotropy=l,i.geometryTangentAngle=u;const c=null!==(r=t.extensions)&&void 0!==r?r:{};c.EXT_materials_anisotropy_openpbr&&c.EXT_materials_anisotropy_openpbr.openPbrAnisotropyEnabled||i.configureGltfStyleAnisotropy(!0),t.anisotropyTexture&&(t.anisotropyTexture.nonColorData=!0,a.push(this._loader.loadTextureInfoAsync(`${e}/anisotropyTexture`,t.anisotropyTexture,e=>{e.name=`${n.name} (Anisotropy Intensity)`,i.geometryTangentTexture=e}))),yield Promise.all(a)})}},hr=!1;function mr(){hr||(hr=!0,ns(cr),ts(cr,!0,e=>new dr(e)))}mr();var fr={__proto__:null,KHR_materials_anisotropy:dr,RegisterKHR_materials_anisotropy:mr};const pr="KHR_materials_emissive_strength";let _r=class{constructor(e){this.name=pr,this.order=170,this._loader=e,this.enabled=this._loader.isExtensionUsed(pr)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return Ms.LoadExtensionAsync(e,t,this.name,(s,o)=>b(this,void 0,void 0,function*(){return yield this._loader.loadMaterialPropertiesAsync(e,t,n),this._loadEmissiveProperties(s,o,n),yield Promise.resolve()}))}_loadEmissiveProperties(e,t,n){void 0!==t.emissiveStrength&&(this._loader._getOrCreateMaterialAdapter(n).emissionLuminance=t.emissiveStrength)}},gr=!1;function yr(){gr||(gr=!0,ns(pr),ts(pr,!0,e=>new _r(e)))}yr();var vr={__proto__:null,KHR_materials_emissive_strength:_r,RegisterKHR_materials_emissive_strength:yr};const br="KHR_materials_sheen";let xr=class{constructor(e){this.name=br,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(br)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return Ms.LoadExtensionAsync(e,t,this.name,(s,o)=>b(this,void 0,void 0,function*(){const r=new Array;return r.push(this._loader.loadMaterialPropertiesAsync(e,t,n)),r.push(this._loadSheenPropertiesAsync(s,o,n)),yield Promise.all(r).then(()=>{})}))}_loadSheenPropertiesAsync(e,n,s){const o=this._loader._getOrCreateMaterialAdapter(s),r=new Array;o.configureFuzz();const i=void 0!==n.sheenColorFactor?t.Color3.FromArray(n.sheenColorFactor):t.Color3.Black(),a=void 0!==n.sheenRoughnessFactor?n.sheenRoughnessFactor:0;return o.fuzzWeight=1,o.fuzzColor=i,o.fuzzRoughness=a,n.sheenColorTexture&&r.push(this._loader.loadTextureInfoAsync(`${e}/sheenColorTexture`,n.sheenColorTexture,e=>{e.name=`${s.name} (Sheen Color)`,o.fuzzColorTexture=e})),n.sheenRoughnessTexture&&(n.sheenRoughnessTexture.nonColorData=!0,r.push(this._loader.loadTextureInfoAsync(`${e}/sheenRoughnessTexture`,n.sheenRoughnessTexture,e=>{e.name=`${s.name} (Sheen Roughness)`,o.fuzzRoughnessTexture=e}))),Promise.all(r).then(()=>{})}},Tr=!1;function Ar(){Tr||(Tr=!0,ns(br),ts(br,!0,e=>new xr(e)))}Ar();var Mr={__proto__:null,KHR_materials_sheen:xr,RegisterKHR_materials_sheen:Ar};const wr="KHR_materials_fuzz";let Cr=class{constructor(e){this.name=wr,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(wr)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return Ms.LoadExtensionAsync(e,t,this.name,(s,o)=>b(this,void 0,void 0,function*(){const r=new Array;return r.push(this._loader.loadMaterialPropertiesAsync(e,t,n)),r.push(this._loadFuzzPropertiesAsync(s,o,n)),yield Promise.all(r).then(()=>{})}))}_loadFuzzPropertiesAsync(e,n,s){const o=this._loader._getOrCreateMaterialAdapter(s),r=new Array;return o.configureFuzz(),o.fuzzWeight=void 0!==n.fuzzFactor?n.fuzzFactor:0,o.fuzzColor=void 0!==n.fuzzColorFactor?t.Color3.FromArray(n.fuzzColorFactor):t.Color3.White(),o.fuzzRoughness=void 0!==n.fuzzRoughnessFactor?n.fuzzRoughnessFactor:.5,n.fuzzTexture&&r.push(this._loader.loadTextureInfoAsync(`${e}/fuzzTexture`,n.fuzzTexture,e=>{e.name=`${s.name} (Fuzz)`,o.fuzzWeightTexture=e})),n.fuzzColorTexture&&r.push(this._loader.loadTextureInfoAsync(`${e}/fuzzColorTexture`,n.fuzzColorTexture,e=>{e.name=`${s.name} (Fuzz Color)`,o.fuzzColorTexture=e})),n.fuzzRoughnessTexture&&(n.fuzzRoughnessTexture.nonColorData=!0,r.push(this._loader.loadTextureInfoAsync(`${e}/fuzzRoughnessTexture`,n.fuzzRoughnessTexture,e=>{e.name=`${s.name} (Fuzz Roughness)`,o.fuzzRoughnessTexture=e}))),Promise.all(r).then(()=>{})}},Rr=!1;function Sr(){Rr||(Rr=!0,ns(wr),ts(wr,!0,e=>new Cr(e)))}Sr();var Or={__proto__:null,KHR_materials_fuzz:Cr,RegisterKHR_materials_fuzz:Sr};const Fr="KHR_materials_specular";let Er=class{constructor(e){this.name=Fr,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(Fr)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return Ms.LoadExtensionAsync(e,t,this.name,(s,o)=>b(this,void 0,void 0,function*(){const r=new Array;r.push(this._loader.loadMaterialPropertiesAsync(e,t,n)),r.push(this._loadSpecularPropertiesAsync(s,o,n));const i=this._loader._getOrCreateMaterialAdapter(n);return o.extensions&&o.extensions.EXT_materials_specular_edge_color&&o.extensions.EXT_materials_specular_edge_color.specularEdgeColorEnabled&&i.enableSpecularEdgeColor(!0),yield Promise.all(r).then(()=>{})}))}_loadSpecularPropertiesAsync(e,n,s){var o;const r=this._loader._getOrCreateMaterialAdapter(s),i=new Array;return r.specularWeight=null!==(o=n.specularFactor)&&void 0!==o?o:1,r.specularColor=void 0!==n.specularColorFactor?t.Color3.FromArray(n.specularColorFactor):new t.Color3(1,1,1),n.specularTexture&&(n.specularTexture.nonColorData=!0,i.push(this._loader.loadTextureInfoAsync(`${e}/specularTexture`,n.specularTexture,e=>{e.name=`${s.name} (Specular)`,r.specularWeightTexture=e}))),n.specularColorTexture&&i.push(this._loader.loadTextureInfoAsync(`${e}/specularColorTexture`,n.specularColorTexture,e=>{e.name=`${s.name} (Specular Color)`,r.specularColorTexture=e})),Promise.all(i).then(()=>{})}},Ir=!1;function Lr(){Ir||(Ir=!0,ns(Fr),ts(Fr,!0,e=>new Er(e)))}Lr();var Pr={__proto__:null,KHR_materials_specular:Er,RegisterKHR_materials_specular:Lr};const Br="KHR_materials_ior";let Nr=class e{constructor(e){this.name=Br,this.order=180,this._loader=e,this.enabled=this._loader.isExtensionUsed(Br)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return Ms.LoadExtensionAsync(e,t,this.name,(s,o)=>b(this,void 0,void 0,function*(){const r=new Array;return r.push(this._loader.loadMaterialPropertiesAsync(e,t,n)),r.push(this._loadIorPropertiesAsync(s,o,n)),yield Promise.all(r).then(()=>{})}))}_loadIorPropertiesAsync(t,n,s){const o=this._loader._getOrCreateMaterialAdapter(s),r=void 0!==n.ior?n.ior:e._DEFAULT_IOR;return o.specularIor=r,Promise.resolve()}};Nr._DEFAULT_IOR=1.5;let kr=!1;function Dr(){kr||(kr=!0,ns(Br),ts(Br,!0,e=>new Nr(e)))}Dr();var Gr={__proto__:null,KHR_materials_ior:Nr,RegisterKHR_materials_ior:Dr};const Vr="KHR_materials_variants";let Hr=class e{constructor(e){this.name=Vr,this._loader=e,this.enabled=this._loader.isExtensionUsed(Vr)&&!this._loader.parent.skipMaterials}dispose(){this._loader=null}static GetAvailableVariants(e){const t=this._GetExtensionMetadata(e);return t?Object.keys(t.variants):[]}getAvailableVariants(t){return e.GetAvailableVariants(t)}static SelectVariant(e,t){const n=this._GetExtensionMetadata(e);if(!n)throw new Error(`Cannot select variant on a glTF mesh that does not have the ${Vr} extension`);const s=e=>{const t=n.variants[e];if(t)for(const e of t)e.mesh.material=e.material};if(t instanceof Array)for(const e of t)s(e);else s(t);n.lastSelected=t}selectVariant(t,n){e.SelectVariant(t,n)}static Reset(e){const t=this._GetExtensionMetadata(e);if(!t)throw new Error(`Cannot reset on a glTF mesh that does not have the ${Vr} extension`);for(const e of t.original)e.mesh.material=e.material;t.lastSelected=null}reset(t){e.Reset(t)}static GetLastSelectedVariant(e){const t=this._GetExtensionMetadata(e);if(!t)throw new Error(`Cannot get the last selected variant on a glTF mesh that does not have the ${Vr} extension`);return t.lastSelected}getLastSelectedVariant(t){return e.GetLastSelectedVariant(t)}static _GetExtensionMetadata(e){var t,n;return(null===(n=null===(t=null==e?void 0:e._internalMetadata)||void 0===t?void 0:t.gltf)||void 0===n?void 0:n[Vr])||null}onLoading(){const e=this._loader.gltf.extensions;if(e&&e[this.name]){const t=e[this.name];this._variants=t.variants}}onReady(){var t;const n=this._loader.rootBabylonMesh;if(n){const s=this._loader.parent.extensionOptions[Vr];(null==s?void 0:s.defaultVariant)&&e.SelectVariant(n,s.defaultVariant),null===(t=null==s?void 0:s.onLoaded)||void 0===t||t.call(s,{get variants(){return e.GetAvailableVariants(n)},get selectedVariant(){const t=e.GetLastSelectedVariant(n);return t?Array.isArray(t)?t[0]:t:e.GetAvailableVariants(n)[0]},set selectedVariant(t){e.SelectVariant(n,t)}})}}_loadMeshPrimitiveAsync(n,s,o,r,i,a){return Ms.LoadExtensionAsync(n,i,this.name,(l,u)=>b(this,void 0,void 0,function*(){const c=new Array;return c.push(this._loader._loadMeshPrimitiveAsync(n,s,o,r,i,s=>{if(a(s),s instanceof t.Mesh){const t=Ms._GetDrawMode(n,i.mode),o=this._loader.rootBabylonMesh,r=o?o._internalMetadata=o._internalMetadata||{}:{},a=r.gltf=r.gltf||{},d=a[Vr]=a[Vr]||{lastSelected:null,original:[],variants:{}};d.original.push({mesh:s,material:s.material});for(let n=0;n<u.mappings.length;++n){const r=u.mappings[n],i=Ts.Get(`${l}/mappings/${n}/material`,this._loader.gltf.materials,r.material);c.push(this._loader._loadMaterialAsync(`#/materials/${r.material}`,i,s,t,t=>{for(let n=0;n<r.variants.length;++n){const i=r.variants[n],a=Ts.Get(`/extensions/${Vr}/variants/${i}`,this._variants,i);d.variants[a.name]=d.variants[a.name]||[],d.variants[a.name].push({mesh:s,material:t}),s.onClonedObservable.add(t=>{const n=t;let r,i=n;do{if(i=i.parent,!i)return;r=e._GetExtensionMetadata(i)}while(null===r);if(o&&r===e._GetExtensionMetadata(o)){i._internalMetadata={};for(const e in o._internalMetadata)i._internalMetadata[e]=o._internalMetadata[e];i._internalMetadata.gltf=[];for(const e in o._internalMetadata.gltf)i._internalMetadata.gltf[e]=o._internalMetadata.gltf[e];i._internalMetadata.gltf[Vr]={lastSelected:null,original:[],variants:{}};for(const e of r.original)i._internalMetadata.gltf[Vr].original.push({mesh:e.mesh,material:e.material});for(const e in r.variants)if(Object.prototype.hasOwnProperty.call(r.variants,e)){i._internalMetadata.gltf[Vr].variants[e]=[];for(const t of r.variants[e])i._internalMetadata.gltf[Vr].variants[e].push({mesh:t.mesh,material:t.material})}r=i._internalMetadata.gltf[Vr]}for(const e of r.original)e.mesh===s&&(e.mesh=n);for(const e of r.variants[a.name])e.mesh===s&&(e.mesh=n)})}}))}}})),yield Promise.all(c).then(([e])=>e)}))}},Kr=!1;function $r(){Kr||(Kr=!0,ns(Vr),ts(Vr,!0,e=>new Hr(e)))}$r();var Ur={__proto__:null,KHR_materials_variants:Hr,RegisterKHR_materials_variants:$r};class qr{static _GetDefaultOptions(){return{renderSize:1024,samples:4,lodGenerationScale:1,lodGenerationOffset:-4,renderTargetTextureType:t.Constants.TEXTURETYPE_HALF_FLOAT,generateMipmaps:!0}}constructor(e,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=Object.assign(Object.assign({},qr._GetDefaultOptions()),e),this._scene=n,this._scene._transmissionHelper=this,this.onErrorObservable=new t.Observable,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;const t=Object.assign(Object.assign({},this._options),e),n=this._options;this._options=t,t.renderSize===n.renderSize&&t.renderTargetTextureType===n.renderTargetTextureType&&t.generateMipmaps===n.generateMipmaps&&this._opaqueRenderTarget?(this._opaqueRenderTarget.samples=t.samples,this._opaqueRenderTarget.lodGenerationScale=t.lodGenerationScale,this._opaqueRenderTarget.lodGenerationOffset=t.lodGenerationOffset):this._setupRenderTargets()}getOpaqueTarget(){return this._opaqueRenderTarget}_getOrCreateAdapter(e){let t=this._adapterCache.get(e);if(!t)for(const n of this._materialImpls)if(e instanceof n.materialClass){t=new n.adapterClass(e),this._adapterCache.set(e,t);break}return t}_classifyMeshMaterials(e){const n=e.material;if(!n)return"opaque";if(!(n instanceof t.MultiMaterial)){const e=this._getOrCreateAdapter(n);return e&&e.isTranslucent()?(e.refractionBackgroundTexture=this._opaqueRenderTarget,"transparent"):"opaque"}let s=!1,o=!1;const r=new Set;for(let e=0;e<n.subMaterials.length;e++){const t=n.subMaterials[e];if(!t){o=!0;continue}const i=this._getOrCreateAdapter(t);i&&i.isTranslucent()?(i.refractionBackgroundTexture=this._opaqueRenderTarget,s=!0,r.add(e)):o=!0}return s&&o?(this._translucentMaterialIndices.set(e,r),this._rebuildOpaqueOnlySubMeshes(e,r),"mixed"):(this._translucentMaterialIndices.delete(e),this._opaqueOnlySubMeshes.delete(e),s?"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)),t.Tools.SetImmediate(()=>{!this._disposed&&e.material&&("transparent"===this._classifyMeshMaterials(e)?-1===this._transparentMeshesCache.indexOf(e)&&this._transparentMeshesCache.push(e):-1===this._opaqueMeshesCache.indexOf(e)&&this._opaqueMeshesCache.push(e))})}_removeMesh(e){e.onMaterialChangedObservable.remove(this._materialObservers[e.uniqueId]),delete this._materialObservers[e.uniqueId];let t=this._transparentMeshesCache.indexOf(e);-1!==t&&this._transparentMeshesCache.splice(t,1),t=this._opaqueMeshesCache.indexOf(e),-1!==t&&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){const t=this._transparentMeshesCache.indexOf(e),n=this._opaqueMeshesCache.indexOf(e);"transparent"===this._classifyMeshMaterials(e)?-1!==n?(this._opaqueMeshesCache.splice(n,1),this._transparentMeshesCache.push(e)):-1===t&&this._transparentMeshesCache.push(e):-1!==t?(this._transparentMeshesCache.splice(t,1),this._opaqueMeshesCache.push(e)):-1===n&&this._opaqueMeshesCache.push(e)}_isRenderTargetValid(){var e;return null!==(null===(e=this._opaqueRenderTarget)||void 0===e?void 0:e.getInternalTexture())}_setupRenderTargets(){var e,n;let s;this._opaqueRenderTarget&&this._opaqueRenderTarget.dispose(),this._opaqueRenderTarget=new t.RenderTargetTexture("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=null!==(n=null===(e=this._options.clearColor)||void 0===e?void 0:e.clone())&&void 0!==n?n: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,this._opaqueRenderTarget.onBeforeBindObservable.add(e=>{s=this._scene.environmentIntensity,this._scene.environmentIntensity=1,this._options.clearColor?e.clearColor.copyFrom(this._options.clearColor):this._scene.clearColor.toLinearSpaceToRef(e.clearColor,this._scene.getEngine().useExactSrgbConversions),e.clearColor.a=0;const t=this._opaqueOnlySubMeshes.entries();for(let e=t.next();!e.done;e=t.next()){const t=e.value[0],n=e.value[1];t.subMeshes&&(this._savedSubMeshes.set(t,t.subMeshes),t.subMeshes=n)}}),this._opaqueRenderTarget.onAfterUnbindObservable.add(()=>{this._scene.environmentIntensity=s;const e=this._savedSubMeshes.entries();for(let t=e.next();!t.done;t=e.next())t.value[0].subMeshes=t.value[1];this._savedSubMeshes.clear()});for(const e of this._transparentMeshesCache)e.material&&this._classifyMeshMaterials(e);const o=this._translucentMaterialIndices.entries();for(let e=o.next();!e.done;e=o.next()){const t=e.value[0];t.material&&this._classifyMeshMaterials(t)}}dispose(){var e,t;this._disposed=!0,null===(e=this._newMeshObserver)||void 0===e||e.remove(),null===(t=this._removedMeshObserver)||void 0===t||t.remove(),this._newMeshObserver=null,this._removedMeshObserver=null;const n=[...this._transparentMeshesCache,...this._opaqueMeshesCache];for(const e of n){const t=this._materialObservers[e.uniqueId];t&&(t.remove(),delete this._materialObservers[e.uniqueId])}for(const e of this._scene.meshes){const 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(),this._opaqueRenderTarget=null),this._transparentMeshesCache=[],this._opaqueMeshesCache=[],this._translucentMaterialIndices.clear(),this._opaqueOnlySubMeshes.clear(),this._savedSubMeshes.clear()}}function Wr(e,t){if(e.parent.dontUseTransmissionHelper)return;const n=t.getScene()._transmissionHelper,s=null!=n?n:new qr({},t.getScene());for(const t of Array.from(e._pbrMaterialImpls.values()))s.addMaterialImpl(t);n&&!n._isRenderTargetValid()&&n._setupRenderTargets()}const zr="KHR_materials_transmission";let jr=class{constructor(e){this.name=zr,this.order=175,this._loader=e,this.enabled=this._loader.isExtensionUsed(zr),this.enabled&&(e.parent.transparencyAsCoverage=!0)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return Ms.LoadExtensionAsync(e,t,this.name,(s,o)=>b(this,void 0,void 0,function*(){const r=new Array;return r.push(this._loader.loadMaterialPropertiesAsync(e,t,n)),r.push(this._loadTransparentPropertiesAsync(s,t,n,o)),yield Promise.all(r).then(()=>{})}))}_loadTransparentPropertiesAsync(e,t,n,s){const o=this._loader._getOrCreateMaterialAdapter(n),r=void 0!==s.transmissionFactor?s.transmissionFactor:0;if(0===r||!o)return Promise.resolve();o.configureTransmission(),o.transmissionWeight=r,r>0&&Wr(this._loader,n);let i=Promise.resolve(null);return s.transmissionTexture&&(s.transmissionTexture.nonColorData=!0,i=this._loader.loadTextureInfoAsync(`${e}/transmissionTexture`,s.transmissionTexture,e=>{e.name=`${n.name} (Transmission)`,o.transmissionWeightTexture=e})),i.then(()=>{})}},Xr=!1;function Yr(){Xr||(Xr=!0,ns(zr),ts(zr,!0,e=>new jr(e)))}Yr();var Qr={__proto__:null,KHR_materials_transmission:jr,RegisterKHR_materials_transmission:Yr};const Zr="KHR_materials_diffuse_transmission";let Jr=class{constructor(e){this.name=Zr,this.order=174,this._loader=e,this.enabled=this._loader.isExtensionUsed(Zr),this.enabled&&(e.parent.transparencyAsCoverage=!0)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return Ms.LoadExtensionAsync(e,t,this.name,(s,o)=>b(this,void 0,void 0,function*(){const r=new Array;return r.push(this._loader.loadMaterialPropertiesAsync(e,t,n)),r.push(this._loadTranslucentPropertiesAsync(s,t,n,o)),yield Promise.all(r).then(()=>{})}))}_loadTranslucentPropertiesAsync(e,n,s,o){var r;const i=this._loader._getOrCreateMaterialAdapter(s);i.configureSubsurface(),i.subsurfaceWeight=null!==(r=o.diffuseTransmissionFactor)&&void 0!==r?r:0,i.subsurfaceWeight>0&&Wr(this._loader,s),i.diffuseTransmissionTint=void 0!==o.diffuseTransmissionColorFactor?t.Color3.FromArray(o.diffuseTransmissionColorFactor):t.Color3.White();const a=new Array;return o.diffuseTransmissionTexture&&(o.diffuseTransmissionTexture.nonColorData=!0,a.push(this._loader.loadTextureInfoAsync(`${e}/diffuseTransmissionTexture`,o.diffuseTransmissionTexture).then(e=>{e.name=`${s.name} (Diffuse Transmission)`,i.subsurfaceWeightTexture=e}))),o.diffuseTransmissionColorTexture&&a.push(this._loader.loadTextureInfoAsync(`${e}/diffuseTransmissionColorTexture`,o.diffuseTransmissionColorTexture).then(e=>{e.name=`${s.name} (Diffuse Transmission Color)`,i.diffuseTransmissionTintTexture=e})),Promise.all(a).then(()=>{})}},ei=!1;function ti(){ei||(ei=!0,ns(Zr),ts(Zr,!0,e=>new Jr(e)))}ti();var ni={__proto__:null,KHR_materials_diffuse_transmission:Jr,RegisterKHR_materials_diffuse_transmission:ti};const si="KHR_materials_volume";let oi=class{constructor(e){this.name=si,this.order=173,this._loader=e,this.enabled=this._loader.isExtensionUsed(si),this.enabled&&this._loader._disableInstancedMesh++}dispose(){this.enabled&&this._loader._disableInstancedMesh--,this._loader=null}loadMaterialPropertiesAsync(e,t,n){return Ms.LoadExtensionAsync(e,t,this.name,(s,o)=>b(this,void 0,void 0,function*(){const r=new Array;return r.push(this._loader.loadMaterialPropertiesAsync(e,t,n)),r.push(this._loadVolumePropertiesAsync(s,t,n,o)),yield Promise.all(r).then(()=>{})}))}_loadVolumePropertiesAsync(e,n,s,o){var r;const i=this._loader._getOrCreateMaterialAdapter(s);if(0===i.transmissionWeight&&0===i.subsurfaceWeight||!o.thicknessFactor)return Promise.resolve();i.geometryThinWalled=!1;const a=void 0!==o.attenuationDistance?o.attenuationDistance:Number.MAX_VALUE,l=void 0!==o.attenuationColor&&3==o.attenuationColor.length?t.Color3.FromArray(o.attenuationColor):t.Color3.White();i.configureVolume(),i.transmissionColor=l,i.transmissionDepth=a,i.volumeThickness=null!==(r=o.thicknessFactor)&&void 0!==r?r:0;const u=new Array;return o.thicknessTexture&&(o.thicknessTexture.nonColorData=!0,u.push(this._loader.loadTextureInfoAsync(`${e}/thicknessTexture`,o.thicknessTexture,e=>{e.name=`${s.name} (Thickness)`,i.volumeThicknessTexture=e}))),Promise.all(u).then(()=>{})}},ri=!1;function ii(){ri||(ri=!0,ns(si),ts(si,!0,e=>new oi(e)))}ii();var ai={__proto__:null,KHR_materials_volume:oi,RegisterKHR_materials_volume:ii};const li="KHR_materials_volume_scatter";let ui=class{constructor(e){this.name=li,this.order=172,this._loader=e,this.enabled=this._loader.isExtensionUsed(li),this.enabled&&this._loader._disableInstancedMesh++}dispose(){this.enabled&&this._loader._disableInstancedMesh--,this._loader=null}loadMaterialPropertiesAsync(e,t,n){return Ms.LoadExtensionAsync(e,t,this.name,(s,o)=>b(this,void 0,void 0,function*(){const r=new Array;return r.push(this._loader.loadMaterialPropertiesAsync(e,t,n)),r.push(this._loadVolumePropertiesAsync(s,t,n,o)),yield Promise.all(r).then(()=>{})}))}_loadVolumePropertiesAsync(e,n,s,o){const r=this._loader._getOrCreateMaterialAdapter(s);if(0===r.transmissionWeight&&0===r.subsurfaceWeight||r.geometryThinWalled)return Promise.resolve();const i=void 0!==o.multiscatterColorFactor&&3==o.multiscatterColorFactor.length?t.Color3.FromArray(o.multiscatterColorFactor):t.Color3.Black(),a=void 0!==o.scatterAnisotropy?o.scatterAnisotropy:0;let l=Promise.resolve(null);o.multiscatterColorTexture&&(o.multiscatterColorTexture.nonColorData=!0,l=this._loader.loadTextureInfoAsync(`${e}/multiscatterColorTexture`,o.multiscatterColorTexture,e=>{e.name=`${s.name} (Scatter Color)`,r.transmissionWeight>0&&(r.transmissionScatterTexture=e),r.subsurfaceWeight>0&&(r.subsurfaceColorTexture=e)}));const u=new t.Vector3(-Math.log(r.transmissionColor.r),-Math.log(r.transmissionColor.g),-Math.log(r.transmissionColor.b));if(u.scaleInPlace(1/Math.max(r.transmissionDepth,1e-6)),r.transmissionWeight>0){const e=function(e){const n=new t.Vector3(e.r,e.g,e.b),s=new t.Vector3(4.09712,4.09712,4.09712);s.addInPlace(new t.Vector3(4.20863,4.20863,4.20863).multiplyInPlace(n));const o=new t.Vector3(9.59217,9.59217,9.59217);return o.addInPlace(new t.Vector3(41.6808,41.6808,41.6808).multiplyInPlace(n)),o.addInPlace(new t.Vector3(17.7126,17.7126,17.7126).multiplyInPlace(n.multiply(n))),s.subtractInPlace(new t.Vector3(Math.sqrt(o.x),Math.sqrt(o.y),Math.sqrt(o.z))),new t.Vector3(1,1,1).subtract(s.multiply(s))}(i),n=u.multiply(e);n.scaleInPlace(r.transmissionDepth),r.transmissionScatter.set(n.x,n.y,n.z),r.transmissionScatterAnisotropy=a}if(r.subsurfaceWeight>0){r.subsurfaceScatterAnisotropy=a,r.subsurfaceColor=i;const e=new t.Vector3(0!==u.x?1/u.x:1,0!==u.y?1/u.y:1,0!==u.z?1/u.z:1);r.subsurfaceRadius=Math.max(e.x,e.y,e.z),r.subsurfaceRadiusScale=new t.Color3(e.x/r.subsurfaceRadius,e.y/r.subsurfaceRadius,e.z/r.subsurfaceRadius)}return l.then(()=>{})}},ci=!1;function di(){ci||(ci=!0,ns(li),ts(li,!0,e=>new ui(e)))}di();var hi={__proto__:null,KHR_materials_volume_scatter:ui,RegisterKHR_materials_volume_scatter:di};const mi="KHR_materials_dispersion";let fi=class{constructor(e){this.name=mi,this.order=174,this._loader=e,this.enabled=this._loader.isExtensionUsed(mi)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return Ms.LoadExtensionAsync(e,t,this.name,(s,o)=>b(this,void 0,void 0,function*(){const r=new Array;return r.push(this._loader.loadMaterialPropertiesAsync(e,t,n)),r.push(this._loadDispersionPropertiesAsync(s,t,n,o)),yield Promise.all(r).then(()=>{})}))}_loadDispersionPropertiesAsync(e,t,n,s){const o=this._loader._getOrCreateMaterialAdapter(n);return 0!=o.transmissionWeight&&s.dispersion?(o.transmissionDispersionAbbeNumber=20,o.transmissionDispersionScale=s.dispersion,Promise.resolve()):Promise.resolve()}},pi=!1;function _i(){pi||(pi=!0,ns(mi),ts(mi,!0,e=>new fi(e)))}_i();var gi={__proto__:null,KHR_materials_dispersion:fi,RegisterKHR_materials_dispersion:_i};const yi="KHR_materials_diffuse_roughness";let vi=class{constructor(e){this.name=yi,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(yi)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return Ms.LoadExtensionAsync(e,t,this.name,(s,o)=>b(this,void 0,void 0,function*(){const r=new Array;return r.push(this._loader.loadMaterialPropertiesAsync(e,t,n)),r.push(this._loadDiffuseRoughnessPropertiesAsync(s,o,n)),yield Promise.all(r).then(()=>{})}))}_loadDiffuseRoughnessPropertiesAsync(e,t,n){var s;const o=this._loader._getOrCreateMaterialAdapter(n),r=new Array;return o.baseDiffuseRoughness=null!==(s=t.diffuseRoughnessFactor)&&void 0!==s?s:0,t.diffuseRoughnessTexture&&r.push(this._loader.loadTextureInfoAsync(`${e}/diffuseRoughnessTexture`,t.diffuseRoughnessTexture,e=>{e.name=`${n.name} (Diffuse Roughness)`,o.baseDiffuseRoughnessTexture=e})),Promise.all(r).then(()=>{})}},bi=!1;function xi(){bi||(bi=!0,ns(yi),ts(yi,!0,e=>new vi(e)))}xi();var Ti={__proto__:null,KHR_materials_diffuse_roughness:vi,RegisterKHR_materials_diffuse_roughness:xi};const Ai="KHR_mesh_quantization";let Mi=class{constructor(e){this.name=Ai,this.enabled=e.isExtensionUsed(Ai)}dispose(){}},wi=!1;function Ci(){wi||(wi=!0,ns(Ai),ts(Ai,!0,e=>new Mi(e)))}Ci();var Ri={__proto__:null,KHR_mesh_quantization:Mi,RegisterKHR_mesh_quantization:Ci};const Si="KHR_texture_basisu";let Oi=class{constructor(e){this.name=Si,this._loader=e,this.enabled=e.isExtensionUsed(Si)}dispose(){this._loader=null}_loadTextureAsync(e,t,n){return Ms.LoadExtensionAsync(e,t,this.name,(s,o)=>b(this,void 0,void 0,function*(){const r=null==t.sampler?Ms.DefaultSampler:Ts.Get(`${e}/sampler`,this._loader.gltf.samplers,t.sampler),i=Ts.Get(`${s}/source`,this._loader.gltf.images,o.source);return yield this._loader._createTextureAsync(e,r,i,e=>{n(e)},t._textureInfo.nonColorData?{useRGBAIfASTCBC7NotAvailableWhenUASTC:!0}:void 0,!t._textureInfo.nonColorData)}))}},Fi=!1;function Ei(){Fi||(Fi=!0,ns(Si),ts(Si,!0,e=>new Oi(e)))}Ei();var Ii={__proto__:null,KHR_texture_basisu:Oi,RegisterKHR_texture_basisu:Ei};const Li="KHR_texture_transform";let Pi=class{constructor(e){this.name=Li,this._loader=e,this.enabled=this._loader.isExtensionUsed(Li)}dispose(){this._loader=null}loadTextureInfoAsync(e,n,s){return Ms.LoadExtensionAsync(e,n,this.name,(o,r)=>b(this,void 0,void 0,function*(){return yield this._loader.loadTextureInfoAsync(e,n,e=>{if(!(e instanceof t.Texture))throw new Error(`${o}: Texture type not supported`);r.offset&&(e.uOffset=r.offset[0],e.vOffset=r.offset[1]),e.uRotationCenter=0,e.vRotationCenter=0,r.rotation&&(e.wAng=-r.rotation),r.scale&&(e.uScale=r.scale[0],e.vScale=r.scale[1]),null!=r.texCoord&&(e.coordinatesIndex=r.texCoord),s(e)})}))}},Bi=!1;function Ni(){Bi||(Bi=!0,ns(Li),ts(Li,!0,e=>new Pi(e)))}Ni();var ki={__proto__:null,KHR_texture_transform:Pi,RegisterKHR_texture_transform:Ni};const Di="KHR_xmp_json_ld";let Gi=class{constructor(e){this.name=Di,this.order=100,this._loader=e,this.enabled=this._loader.isExtensionUsed(Di)}dispose(){this._loader=null}onLoading(){var e,t,n;if(null===this._loader.rootBabylonMesh)return;const s=null===(e=this._loader.gltf.extensions)||void 0===e?void 0:e.KHR_xmp_json_ld,o=null===(n=null===(t=this._loader.gltf.asset)||void 0===t?void 0:t.extensions)||void 0===n?void 0:n.KHR_xmp_json_ld;if(s&&o){const e=+o.packet;s.packets&&e<s.packets.length&&(this._loader.rootBabylonMesh.metadata=this._loader.rootBabylonMesh.metadata||{},this._loader.rootBabylonMesh.metadata.xmp=s.packets[e])}}},Vi=!1;function Hi(){Vi||(Vi=!0,ns(Di),ts(Di,!0,e=>new Gi(e)))}Hi();var Ki={__proto__:null,KHR_xmp_json_ld:Gi,RegisterKHR_xmp_json_ld:Hi};const $i="KHR_animation_pointer";let Ui=class{constructor(e){this.name=$i,this._loader=e,this._pathToObjectConverter=_s(this._loader.gltf)}get enabled(){return this._loader.isExtensionUsed($i)}dispose(){this._loader=null,delete this._pathToObjectConverter}_loadAnimationChannelAsync(e,n,s,o,r){var i;const a=null===(i=o.target.extensions)||void 0===i?void 0:i.KHR_animation_pointer;if(!a||!this._pathToObjectConverter)return null;"pointer"!==o.target.path&&t.Logger.Warn(`${e}/target/path: Value (${o.target.path}) must be (pointer) when using the ${this.name} extension`),null!=o.target.node&&t.Logger.Warn(`${e}/target/node: Value (${o.target.node}) must not be present when using the ${this.name} extension`);const l=`${e}/extensions/${this.name}`,u=a.pointer;if(!u)throw new Error(`${l}: Pointer is missing`);try{const t=this._pathToObjectConverter.convert(u);if(!t.info.interpolation)throw new Error(`${l}/pointer: Interpolation is missing`);return this._loader._loadAnimationChannelFromTargetInfoAsync(e,n,s,o,{object:t.object,info:t.info.interpolation},r)}catch(e){return t.Logger.Warn(`${l}/pointer: Invalid pointer (${u}) skipped`),null}}},qi=!1;function Wi(){qi||(qi=!0,ns($i),ts($i,!0,e=>new Ui(e)))}function zi(e,n,s,o){return t.Color3.FromArray(n,s).scale(o)}function ji(e,t,n,s){return t[n]*s}function Xi(e,t,n,s){return-t[n]*s}function Yi(e,t,n,s){return t[n+1]*s}function Qi(e,t,n,s){return t[n]*s*2}function Zi(e){return{scale:[new ea(t.Animation.ANIMATIONTYPE_FLOAT,`${e}.uScale`,ji,()=>2),new ea(t.Animation.ANIMATIONTYPE_FLOAT,`${e}.vScale`,Yi,()=>2)],offset:[new ea(t.Animation.ANIMATIONTYPE_FLOAT,`${e}.uOffset`,ji,()=>2),new ea(t.Animation.ANIMATIONTYPE_FLOAT,`${e}.vOffset`,Yi,()=>2)],rotation:[new ea(t.Animation.ANIMATIONTYPE_FLOAT,`${e}.wAng`,Xi,()=>1)]}}class Ji extends Es{buildAnimations(e,t,n,s){return[{babylonAnimatable:e._babylonCamera,babylonAnimation:this._buildAnimation(t,n,s)}]}}class ea extends Es{buildAnimations(e,t,n,s){const o=[];for(const r in e._data)o.push({babylonAnimatable:e._data[r].babylonMaterial,babylonAnimation:this._buildAnimation(t,n,s)});return o}}class ta extends Es{buildAnimations(e,t,n,s){return[{babylonAnimatable:e._babylonLight,babylonAnimation:this._buildAnimation(t,n,s)}]}}ys("/cameras/{}/orthographic/xmag",[new Ji(t.Animation.ANIMATIONTYPE_FLOAT,"orthoLeft",Xi,()=>1),new Ji(t.Animation.ANIMATIONTYPE_FLOAT,"orthoRight",Yi,()=>1)]),ys("/cameras/{}/orthographic/ymag",[new Ji(t.Animation.ANIMATIONTYPE_FLOAT,"orthoBottom",Xi,()=>1),new Ji(t.Animation.ANIMATIONTYPE_FLOAT,"orthoTop",Yi,()=>1)]),ys("/cameras/{}/orthographic/zfar",[new Ji(t.Animation.ANIMATIONTYPE_FLOAT,"maxZ",ji,()=>1)]),ys("/cameras/{}/orthographic/znear",[new Ji(t.Animation.ANIMATIONTYPE_FLOAT,"minZ",ji,()=>1)]),ys("/cameras/{}/perspective/yfov",[new Ji(t.Animation.ANIMATIONTYPE_FLOAT,"fov",ji,()=>1)]),ys("/cameras/{}/perspective/zfar",[new Ji(t.Animation.ANIMATIONTYPE_FLOAT,"maxZ",ji,()=>1)]),ys("/cameras/{}/perspective/znear",[new Ji(t.Animation.ANIMATIONTYPE_FLOAT,"minZ",ji,()=>1)]),ys("/materials/{}/pbrMetallicRoughness/baseColorFactor",[new ea(t.Animation.ANIMATIONTYPE_COLOR3,"albedoColor",zi,()=>4),new ea(t.Animation.ANIMATIONTYPE_FLOAT,"alpha",function(e,t,n,s){return t[n+3]*s},()=>4)]),ys("/materials/{}/pbrMetallicRoughness/metallicFactor",[new ea(t.Animation.ANIMATIONTYPE_FLOAT,"metallic",ji,()=>1)]),ys("/materials/{}/pbrMetallicRoughness/metallicFactor",[new ea(t.Animation.ANIMATIONTYPE_FLOAT,"roughness",ji,()=>1)]);const na=Zi("albedoTexture");ys("/materials/{}/pbrMetallicRoughness/baseColorTexture/extensions/KHR_texture_transform/scale",na.scale),ys("/materials/{}/pbrMetallicRoughness/baseColorTexture/extensions/KHR_texture_transform/offset",na.offset),ys("/materials/{}/pbrMetallicRoughness/baseColorTexture/extensions/KHR_texture_transform/rotation",na.rotation);const sa=Zi("metallicTexture");ys("//materials/{}/pbrMetallicRoughness/metallicRoughnessTexture/scale",sa.scale),ys("//materials/{}/pbrMetallicRoughness/metallicRoughnessTexture/offset",sa.offset),ys("//materials/{}/pbrMetallicRoughness/metallicRoughnessTexture/rotation",sa.rotation),ys("/materials/{}/emissiveFactor",[new ea(t.Animation.ANIMATIONTYPE_COLOR3,"emissiveColor",zi,()=>3)]);const oa=Zi("bumpTexture");ys("/materials/{}/normalTexture/scale",[new ea(t.Animation.ANIMATIONTYPE_FLOAT,"bumpTexture.level",ji,()=>1)]),ys("/materials/{}/normalTexture/extensions/KHR_texture_transform/scale",oa.scale),ys("/materials/{}/normalTexture/extensions/KHR_texture_transform/offset",oa.offset),ys("/materials/{}/normalTexture/extensions/KHR_texture_transform/rotation",oa.rotation),ys("/materials/{}/occlusionTexture/strength",[new ea(t.Animation.ANIMATIONTYPE_FLOAT,"ambientTextureStrength",ji,()=>1)]);const ra=Zi("ambientTexture");ys("/materials/{}/occlusionTexture/extensions/KHR_texture_transform/scale",ra.scale),ys("/materials/{}/occlusionTexture/extensions/KHR_texture_transform/offset",ra.offset),ys("/materials/{}/occlusionTexture/extensions/KHR_texture_transform/rotation",ra.rotation);const ia=Zi("emissiveTexture");ys("/materials/{}/emissiveTexture/extensions/KHR_texture_transform/scale",ia.scale),ys("/materials/{}/emissiveTexture/extensions/KHR_texture_transform/offset",ia.offset),ys("/materials/{}/emissiveTexture/extensions/KHR_texture_transform/rotation",ia.rotation),ys("/materials/{}/extensions/KHR_materials_anisotropy/anisotropyStrength",[new ea(t.Animation.ANIMATIONTYPE_FLOAT,"anisotropy.intensity",ji,()=>1)]),ys("/materials/{}/extensions/KHR_materials_anisotropy/anisotropyRotation",[new ea(t.Animation.ANIMATIONTYPE_FLOAT,"anisotropy.angle",ji,()=>1)]);const aa=Zi("anisotropy.texture");ys("/materials/{}/extensions/KHR_materials_anisotropy/anisotropyTexture/extensions/KHR_texture_transform/scale",aa.scale),ys("/materials/{}/extensions/KHR_materials_anisotropy/anisotropyTexture/extensions/KHR_texture_transform/offset",aa.offset),ys("/materials/{}/extensions/KHR_materials_anisotropy/anisotropyTexture/extensions/KHR_texture_transform/rotation",aa.rotation),ys("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatFactor",[new ea(t.Animation.ANIMATIONTYPE_FLOAT,"clearCoat.intensity",ji,()=>1)]),ys("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatRoughnessFactor",[new ea(t.Animation.ANIMATIONTYPE_FLOAT,"clearCoat.roughness",ji,()=>1)]);const la=Zi("clearCoat.texture");ys("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatTexture/extensions/KHR_texture_transform/scale",la.scale),ys("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatTexture/extensions/KHR_texture_transform/offset",la.offset),ys("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatTexture/extensions/KHR_texture_transform/rotation",la.rotation);const ua=Zi("clearCoat.bumpTexture");ys("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatNormalTexture/scale",[new ea(t.Animation.ANIMATIONTYPE_FLOAT,"clearCoat.bumpTexture.level",ji,()=>1)]),ys("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatNormalTexture/extensions/KHR_texture_transform/scale",ua.scale),ys("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatNormalTexture/extensions/KHR_texture_transform/offset",ua.offset),ys("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatNormalTexture/extensions/KHR_texture_transform/rotation",ua.rotation);const ca=Zi("clearCoat.textureRoughness");ys("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatRoughnessTexture/extensions/KHR_texture_transform/scale",ca.scale),ys("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatRoughnessTexture/extensions/KHR_texture_transform/offset",ca.offset),ys("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatRoughnessTexture/extensions/KHR_texture_transform/rotation",ca.rotation),ys("/materials/{}/extensions/KHR_materials_dispersion/dispersionFactor",[new ea(t.Animation.ANIMATIONTYPE_FLOAT,"subSurface.dispersion",ji,()=>1)]),ys("/materials/{}/extensions/KHR_materials_emissive_strength/emissiveStrength",[new ea(t.Animation.ANIMATIONTYPE_FLOAT,"emissiveIntensity",ji,()=>1)]),ys("/materials/{}/extensions/KHR_materials_ior/ior",[new ea(t.Animation.ANIMATIONTYPE_FLOAT,"indexOfRefraction",ji,()=>1)]),ys("/materials/{}/extensions/KHR_materials_iridescence/iridescenceFactor",[new ea(t.Animation.ANIMATIONTYPE_FLOAT,"iridescence.intensity",ji,()=>1)]),ys("/materials/{}/extensions/KHR_materials_iridescence/iridescenceIor",[new ea(t.Animation.ANIMATIONTYPE_FLOAT,"iridescence.indexOfRefraction",ji,()=>1)]),ys("/materials/{}/extensions/KHR_materials_iridescence/iridescenceThicknessMinimum",[new ea(t.Animation.ANIMATIONTYPE_FLOAT,"iridescence.minimumThickness",ji,()=>1)]),ys("/materials/{}/extensions/KHR_materials_iridescence/iridescenceThicknessMaximum",[new ea(t.Animation.ANIMATIONTYPE_FLOAT,"iridescence.maximumThickness",ji,()=>1)]);const da=Zi("iridescence.texture");ys("/materials/{}/extensions/KHR_materials_iridescence/iridescenceTexture/extensions/KHR_texture_transform/scale",da.scale),ys("/materials/{}/extensions/KHR_materials_iridescence/iridescenceTexture/extensions/KHR_texture_transform/offset",da.offset),ys("/materials/{}/extensions/KHR_materials_iridescence/iridescenceTexture/extensions/KHR_texture_transform/rotation",da.rotation);const ha=Zi("iridescence.thicknessTexture");ys("/materials/{}/extensions/KHR_materials_iridescence/iridescenceThicknessTexture/extensions/KHR_texture_transform/scale",ha.scale),ys("/materials/{}/extensions/KHR_materials_iridescence/iridescenceThicknessTexture/extensions/KHR_texture_transform/offset",ha.offset),ys("/materials/{}/extensions/KHR_materials_iridescence/iridescenceThicknessTexture/extensions/KHR_texture_transform/rotation",ha.rotation),ys("/materials/{}/extensions/KHR_materials_sheen/sheenColorFactor",[new ea(t.Animation.ANIMATIONTYPE_COLOR3,"sheen.color",zi,()=>3)]),ys("/materials/{}/extensions/KHR_materials_sheen/sheenRoughnessFactor",[new ea(t.Animation.ANIMATIONTYPE_FLOAT,"sheen.roughness",ji,()=>1)]);const ma=Zi("sheen.texture");ys("/materials/{}/extensions/KHR_materials_sheen/sheenColorTexture/extensions/KHR_texture_transform/scale",ma.scale),ys("/materials/{}/extensions/KHR_materials_sheen/sheenColorTexture/extensions/KHR_texture_transform/offset",ma.offset),ys("/materials/{}/extensions/KHR_materials_sheen/sheenColorTexture/extensions/KHR_texture_transform/rotation",ma.rotation);const fa=Zi("sheen.textureRoughness");ys("/materials/{}/extensions/KHR_materials_sheen/sheenRoughnessTexture/extensions/KHR_texture_transform/scale",fa.scale),ys("/materials/{}/extensions/KHR_materials_sheen/sheenRoughnessTexture/extensions/KHR_texture_transform/offset",fa.offset),ys("/materials/{}/extensions/KHR_materials_sheen/sheenRoughnessTexture/extensions/KHR_texture_transform/rotation",fa.rotation),ys("/materials/{}/extensions/KHR_materials_specular/specularFactor",[new ea(t.Animation.ANIMATIONTYPE_FLOAT,"metallicF0Factor",ji,()=>1)]),ys("/materials/{}/extensions/KHR_materials_specular/specularColorFactor",[new ea(t.Animation.ANIMATIONTYPE_COLOR3,"metallicReflectanceColor",zi,()=>3)]);const pa=Zi("metallicReflectanceTexture");ys("/materials/{}/extensions/KHR_materials_specular/specularTexture/extensions/KHR_texture_transform/scale",pa.scale),ys("/materials/{}/extensions/KHR_materials_specular/specularTexture/extensions/KHR_texture_transform/offset",pa.offset),ys("/materials/{}/extensions/KHR_materials_specular/specularTexture/extensions/KHR_texture_transform/rotation",pa.rotation);const _a=Zi("reflectanceTexture");ys("/materials/{}/extensions/KHR_materials_specular/specularColorTexture/extensions/KHR_texture_transform/scale",_a.scale),ys("/materials/{}/extensions/KHR_materials_specular/specularColorTexture/extensions/KHR_texture_transform/offset",_a.offset),ys("/materials/{}/extensions/KHR_materials_specular/specularColorTexture/extensions/KHR_texture_transform/rotation",_a.rotation),ys("/materials/{}/extensions/KHR_materials_transmission/transmissionFactor",[new ea(t.Animation.ANIMATIONTYPE_FLOAT,"subSurface.refractionIntensity",ji,()=>1)]);const ga=Zi("subSurface.refractionIntensityTexture");ys("/materials/{}/extensions/KHR_materials_transmission/transmissionTexture/extensions/KHR_texture_transform/scale",ga.scale),ys("/materials/{}/extensions/KHR_materials_transmission/transmissionTexture/extensions/KHR_texture_transform/offset",ga.offset),ys("/materials/{}/extensions/KHR_materials_transmission/transmissionTexture/extensions/KHR_texture_transform/rotation",ga.rotation),ys("/materials/{}/extensions/KHR_materials_volume/attenuationColor",[new ea(t.Animation.ANIMATIONTYPE_COLOR3,"subSurface.tintColor",zi,()=>3)]),ys("/materials/{}/extensions/KHR_materials_volume/attenuationDistance",[new ea(t.Animation.ANIMATIONTYPE_FLOAT,"subSurface.tintColorAtDistance",ji,()=>1)]),ys("/materials/{}/extensions/KHR_materials_volume/thicknessFactor",[new ea(t.Animation.ANIMATIONTYPE_FLOAT,"subSurface.maximumThickness",ji,()=>1)]);const ya=Zi("subSurface.thicknessTexture");ys("/materials/{}/extensions/KHR_materials_volume/thicknessTexture/extensions/KHR_texture_transform/scale",ya.scale),ys("/materials/{}/extensions/KHR_materials_volume/thicknessTexture/extensions/KHR_texture_transform/offset",ya.offset),ys("/materials/{}/extensions/KHR_materials_volume/thicknessTexture/extensions/KHR_texture_transform/rotation",ya.rotation),ys("/materials/{}/extensions/KHR_materials_diffuse_transmission/diffuseTransmissionFactor",[new ea(t.Animation.ANIMATIONTYPE_FLOAT,"subSurface.translucencyIntensity",ji,()=>1)]);const va=Zi("subSurface.translucencyIntensityTexture");ys("materials/{}/extensions/KHR_materials_diffuse_transmission/diffuseTransmissionTexture/extensions/KHR_texture_transform/scale",va.scale),ys("materials/{}/extensions/KHR_materials_diffuse_transmission/diffuseTransmissionTexture/extensions/KHR_texture_transform/offset",va.offset),ys("materials/{}/extensions/KHR_materials_diffuse_transmission/diffuseTransmissionTexture/extensions/KHR_texture_transform/rotation",va.rotation),ys("/materials/{}/extensions/KHR_materials_diffuse_transmission/diffuseTransmissionColorFactor",[new ea(t.Animation.ANIMATIONTYPE_COLOR3,"subSurface.translucencyColor",zi,()=>3)]);const ba=Zi("subSurface.translucencyColorTexture");ys("materials/{}/extensions/KHR_materials_diffuse_transmission/diffuseTransmissionColorTexture/extensions/KHR_texture_transform/scale",ba.scale),ys("materials/{}/extensions/KHR_materials_diffuse_transmission/diffuseTransmissionColorTexture/extensions/KHR_texture_transform/offset",ba.offset),ys("materials/{}/extensions/KHR_materials_diffuse_transmission/diffuseTransmissionColorTexture/extensions/KHR_texture_transform/rotation",ba.rotation),ys("/extensions/KHR_lights_punctual/lights/{}/color",[new ta(t.Animation.ANIMATIONTYPE_COLOR3,"diffuse",zi,()=>3)]),ys("/extensions/KHR_lights_punctual/lights/{}/intensity",[new ta(t.Animation.ANIMATIONTYPE_FLOAT,"intensity",ji,()=>1)]),ys("/extensions/KHR_lights_punctual/lights/{}/range",[new ta(t.Animation.ANIMATIONTYPE_FLOAT,"range",ji,()=>1)]),ys("/extensions/KHR_lights_punctual/lights/{}/spot/innerConeAngle",[new ta(t.Animation.ANIMATIONTYPE_FLOAT,"innerAngle",Qi,()=>1)]),ys("/extensions/KHR_lights_punctual/lights/{}/spot/outerConeAngle",[new ta(t.Animation.ANIMATIONTYPE_FLOAT,"angle",Qi,()=>1)]),ys("/extensions/EXT_lights_area/lights/{}/color",[new ta(t.Animation.ANIMATIONTYPE_COLOR3,"diffuse",zi,()=>3)]),ys("/extensions/EXT_lights_area/lights/{}/intensity",[new ta(t.Animation.ANIMATIONTYPE_FLOAT,"intensity",ji,()=>1)]),ys("/extensions/EXT_lights_area/lights/{}/size",[new ta(t.Animation.ANIMATIONTYPE_FLOAT,"radius",ji,()=>1)]),ys("/extensions/EXT_lights_area/lights/{}/rect/aspect",[new ta(t.Animation.ANIMATIONTYPE_FLOAT,"radius",ji,()=>1)]),ys("/nodes/{}/extensions/EXT_lights_ies/color",[new ta(t.Animation.ANIMATIONTYPE_COLOR3,"diffuse",zi,()=>3)]),ys("/nodes/{}/extensions/EXT_lights_ies/multiplier",[new ta(t.Animation.ANIMATIONTYPE_FLOAT,"intensity",ji,()=>1)]),ys("/nodes/{}/extensions/KHR_node_visibility/visible",[new class extends Es{buildAnimations(e,t,n,s){return e._primitiveBabylonMeshes?e._primitiveBabylonMeshes.map(e=>({babylonAnimatable:e,babylonAnimation:this._buildAnimation(t,n,s)})):[]}}(t.Animation.ANIMATIONTYPE_FLOAT,"isVisible",ji,()=>1)]),Wi();var xa={__proto__:null,KHR_animation_pointer:Ui,RegisterKHR_animation_pointer:Wi};const Ta="MSFT_audio_emitter";let Aa=class{constructor(e){this.name=Ta,this._loader=e,this.enabled=this._loader.isExtensionUsed(Ta)}dispose(){this._loader=null,this._clips=null,this._emitters=null}onLoading(){const e=this._loader.gltf.extensions;if(e&&e[this.name]){const t=e[this.name];this._clips=t.clips,this._emitters=t.emitters,Ts.Assign(this._clips),Ts.Assign(this._emitters)}}loadSceneAsync(e,t){return Ms.LoadExtensionAsync(e,t,this.name,(n,s)=>b(this,void 0,void 0,function*(){const o=new Array;o.push(this._loader.loadSceneAsync(e,t));for(const e of s.emitters){const t=Ts.Get(`${n}/emitters`,this._emitters,e);if(null!=t.refDistance||null!=t.maxDistance||null!=t.rolloffFactor||null!=t.distanceModel||null!=t.innerAngle||null!=t.outerAngle)throw new Error(`${n}: Direction or Distance properties are not allowed on emitters attached to a scene`);o.push(this._loadEmitterAsync(`${n}/emitters/${t.index}`,t))}yield Promise.all(o)}))}loadNodeAsync(e,n,s){return Ms.LoadExtensionAsync(e,n,this.name,(e,o)=>b(this,void 0,void 0,function*(){const r=new Array,i=yield this._loader.loadNodeAsync(e,n,n=>{for(const s of o.emitters){const o=Ts.Get(`${e}/emitters`,this._emitters,s);r.push(this._loadEmitterAsync(`${e}/emitters/${o.index}`,o).then(()=>{for(const e of o._babylonSounds)e.attachToMesh(n),null==o.innerAngle&&null==o.outerAngle||(e.setLocalDirectionToMesh(t.Vector3.Forward()),e.setDirectionalCone(2*t.Tools.ToDegrees(null==o.innerAngle?Math.PI:o.innerAngle),2*t.Tools.ToDegrees(null==o.outerAngle?Math.PI:o.outerAngle),0))}))}s(n)});return yield Promise.all(r),i}))}loadAnimationAsync(e,t){return Ms.LoadExtensionAsync(e,t,this.name,(n,s)=>b(this,void 0,void 0,function*(){const o=yield this._loader.loadAnimationAsync(e,t),r=new Array;Ts.Assign(s.events);for(const i of s.events)r.push(this._loadAnimationEventAsync(`${n}/events/${i.index}`,e,t,i,o));return yield Promise.all(r),o}))}_loadClipAsync(e,n){if(n._objectURL)return n._objectURL;let s;if(n.uri)s=this._loader.loadUriAsync(e,n,n.uri);else{const t=Ts.Get(`${e}/bufferView`,this._loader.gltf.bufferViews,n.bufferView);s=this._loader.loadBufferViewAsync(`/bufferViews/${t.index}`,t)}return n._objectURL=s.then(e=>{const s=t.GetBlobBufferSource(e);return URL.createObjectURL(new Blob([s],{type:n.mimeType}))}),n._objectURL}_loadEmitterAsync(e,n){if(n._babylonSounds=n._babylonSounds||[],!n._babylonData){const e=new Array,s=n.name||`emitter${n.index}`,o={loop:!1,autoplay:!1,volume:null==n.volume?1:n.volume};for(let r=0;r<n.clips.length;r++){const i=`/extensions/${this.name}/clips`,a=Ts.Get(i,this._clips,n.clips[r].clip);e.push(this._loadClipAsync(`${i}/${n.clips[r].clip}`,a).then(e=>{const i=n._babylonSounds[r]=new t.Sound(s,e,this._loader.babylonScene,null,o);i.refDistance=n.refDistance||1,i.maxDistance=n.maxDistance||256,i.rolloffFactor=n.rolloffFactor||1,i.distanceModel=n.distanceModel||"exponential"}))}const r=Promise.all(e).then(()=>{const e=n.clips.map(e=>e.weight||1),s=new t.WeightedSound(n.loop||!1,n._babylonSounds,e);n.innerAngle&&(s.directionalConeInnerAngle=2*t.Tools.ToDegrees(n.innerAngle)),n.outerAngle&&(s.directionalConeOuterAngle=2*t.Tools.ToDegrees(n.outerAngle)),n.volume&&(s.volume=n.volume),n._babylonData.sound=s});n._babylonData={loaded:r}}return n._babylonData.loaded}_getEventAction(e,t,n,s,o){switch(n){case"play":return e=>{const n=(o||0)+(e-s);t.play(n)};case"stop":return()=>{t.stop()};case"pause":return()=>{t.pause()};default:throw new Error(`${e}: Unsupported action ${n}`)}}_loadAnimationEventAsync(e,n,s,o,r){if(0==r.targetedAnimations.length)return Promise.resolve();const i=r.targetedAnimations[0],a=o.emitter,l=Ts.Get(`/extensions/${this.name}/emitters`,this._emitters,a);return this._loadEmitterAsync(e,l).then(()=>{const n=l._babylonData.sound;if(n){const s=new t.AnimationEvent(o.time,this._getEventAction(e,n,o.action,o.time,o.startOffset));i.animation.addEvent(s),r.onAnimationGroupEndObservable.add(()=>{n.stop()}),r.onAnimationGroupPauseObservable.add(()=>{n.pause()})}})}},Ma=!1;function wa(){Ma||(Ma=!0,ns(Ta),ts(Ta,!0,e=>new Aa(e)))}wa();var Ca={__proto__:null,MSFT_audio_emitter:Aa,RegisterMSFT_audio_emitter:wa};const Ra="MSFT_lod";let Sa=class{constructor(e){var n,s;this.name=Ra,this.order=100,this.maxLODsToLoad=10,this.onNodeLODsLoadedObservable=new t.Observable,this.onMaterialLODsLoadedObservable=new t.Observable,this._bufferLODs=new Array,this._nodeIndexLOD=null,this._nodeSignalLODs=new Array,this._nodePromiseLODs=new Array,this._nodeBufferLODs=new Array,this._materialIndexLOD=null,this._materialSignalLODs=new Array,this._materialPromiseLODs=new Array,this._materialBufferLODs=new Array,this._loader=e,this.maxLODsToLoad=null!==(s=null===(n=this._loader.parent.extensionOptions[Ra])||void 0===n?void 0:n.maxLODsToLoad)&&void 0!==s?s:this.maxLODsToLoad,this.enabled=this._loader.isExtensionUsed(Ra)}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++){const t=Promise.all(this._nodePromiseLODs[e]).then(()=>{0!==e&&(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++){const t=Promise.all(this._materialPromiseLODs[e]).then(()=>{0!==e&&(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){const n=this._loader.loadSceneAsync(e,t);return this._loadBufferLOD(this._bufferLODs,0),n}loadNodeAsync(e,n,s){return Ms.LoadExtensionAsync(e,n,this.name,(e,o)=>b(this,void 0,void 0,function*(){let r;const i=this._getLODs(e,n,this._loader.gltf.nodes,o.ids);this._loader.logOpen(`${e}`);for(let e=0;e<i.length;e++){const n=i[e];0!==e&&(this._nodeIndexLOD=e,this._nodeSignalLODs[e]=this._nodeSignalLODs[e]||new t.Deferred);const o=e=>{s(e),e.setEnabled(!1)},a=this._loader.loadNodeAsync(`/nodes/${n.index}`,n,o).then(t=>{if(0!==e){const t=i[e-1];t._babylonTransformNode&&(this._disposeTransformNode(t._babylonTransformNode),delete t._babylonTransformNode)}return t.setEnabled(!0),t});this._nodePromiseLODs[e]=this._nodePromiseLODs[e]||[],0===e?r=a:(this._nodeIndexLOD=null,this._nodePromiseLODs[e].push(a))}return this._loader.logClose(),yield r}))}_loadMaterialAsync(e,t,n,s,o){return this._nodeIndexLOD?null:Ms.LoadExtensionAsync(e,t,this.name,(e,r)=>b(this,void 0,void 0,function*(){let i;const a=this._getLODs(e,t,this._loader.gltf.materials,r.ids);this._loader.logOpen(`${e}`);for(let e=0;e<a.length;e++){const t=a[e];0!==e&&(this._materialIndexLOD=e);const r=this._loader._loadMaterialAsync(`/materials/${t.index}`,t,n,s,t=>{0===e&&o(t)}).then(t=>{if(0!==e){o(t);const n=a[e-1]._data;n[s]&&(this._disposeMaterials([n[s].babylonMaterial]),delete n[s])}return t});this._materialPromiseLODs[e]=this._materialPromiseLODs[e]||[],0===e?i=r:(this._materialIndexLOD=null,this._materialPromiseLODs[e].push(r))}return this._loader.logClose(),yield i}))}_loadUriAsync(e,n,s){if(null!==this._nodeIndexLOD){this._loader.log("deferred");const o=this._nodeIndexLOD-1;return this._nodeSignalLODs[o]=this._nodeSignalLODs[o]||new t.Deferred,this._nodeSignalLODs[this._nodeIndexLOD-1].promise.then(()=>b(this,void 0,void 0,function*(){return yield this._loader.loadUriAsync(e,n,s)}))}if(null!==this._materialIndexLOD){this._loader.log("deferred");const o=this._materialIndexLOD-1;return this._materialSignalLODs[o]=this._materialSignalLODs[o]||new t.Deferred,this._materialSignalLODs[o].promise.then(()=>b(this,void 0,void 0,function*(){return yield this._loader.loadUriAsync(e,n,s)}))}return null}loadBufferAsync(e,n,s,o){if(this._loader.parent.useRangeRequests&&!n.uri){if(!this._loader.bin)throw new Error(`${e}: Uri is missing or the binary glTF is missing its binary chunk`);const n=(e,n)=>b(this,void 0,void 0,function*(){const r=s,i=r+o-1;let a=e[n];return a?(a.start=Math.min(a.start,r),a.end=Math.max(a.end,i)):(a={start:r,end:i,loaded:new t.Deferred},e[n]=a),yield a.loaded.promise.then(e=>new Uint8Array(e.buffer,e.byteOffset+s-a.start,o))});return this._loader.log("deferred"),null!==this._nodeIndexLOD?n(this._nodeBufferLODs,this._nodeIndexLOD):null!==this._materialIndexLOD?n(this._materialBufferLODs,this._materialIndexLOD):n(this._bufferLODs,0)}return null}_loadBufferLOD(e,t){const 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,s){if(this.maxLODsToLoad<=0)throw new Error("maxLODsToLoad must be greater than zero");const o=[];for(let t=s.length-1;t>=0;t--)if(o.push(Ts.Get(`${e}/ids/${s[t]}`,n,s[t])),o.length===this.maxLODsToLoad)return o;return o.push(t),o}_disposeTransformNode(e){const t=[],n=e.material;n&&t.push(n);for(const n of e.getChildMeshes())n.material&&t.push(n.material);e.dispose();const s=t.filter(e=>this._loader.babylonScene.meshes.every(t=>t.material!=e));this._disposeMaterials(s)}_disposeMaterials(e){const t={};for(const n of e){for(const e of n.getActiveTextures())t[e.uniqueId]=e;n.dispose()}for(const e in t)for(const n of this._loader.babylonScene.materials)n.hasTexture(t[e])&&delete t[e];for(const e in t)t[e].dispose()}},Oa=!1;function Fa(){Oa||(Oa=!0,ns(Ra),ts(Ra,!0,e=>new Sa(e)))}Fa();var Ea={__proto__:null,MSFT_lod:Sa,RegisterMSFT_lod:Fa};const Ia="MSFT_minecraftMesh";let La=class{constructor(e){this.name=Ia,this._loader=e,this.enabled=this._loader.isExtensionUsed(Ia)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return Ms.LoadExtraAsync(e,t,this.name,(s,o)=>b(this,void 0,void 0,function*(){if(o){if(!this._loader._pbrMaterialImpls.get("pbr"))throw new Error(`${s}: Material type not supported`);const o=this._loader.loadMaterialPropertiesAsync(e,t,n);return n.needAlphaBlending()&&(n.forceDepthWrite=!0,n.separateCullingPass=!0),n.backFaceCulling=n.forceDepthWrite,n.twoSidedLighting=!0,yield o}}))}},Pa=!1;function Ba(){Pa||(Pa=!0,ns(Ia),ts(Ia,!0,e=>new La(e)))}Ba();var Na={__proto__:null,MSFT_minecraftMesh:La,RegisterMSFT_minecraftMesh:Ba};const ka="MSFT_sRGBFactors";let Da=class{constructor(e){this.name=ka,this._loader=e,this.enabled=this._loader.isExtensionUsed(ka)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return Ms.LoadExtraAsync(e,t,this.name,(s,o)=>b(this,void 0,void 0,function*(){if(o){const s=this._loader._getOrCreateMaterialAdapter(n),o=this._loader.loadMaterialPropertiesAsync(e,t,n),r=n.getScene().getEngine().useExactSrgbConversions;return s.baseColorTexture||s.baseColor.toLinearSpaceToRef(s.baseColor,r),s.specularColorTexture||s.specularColor.toLinearSpaceToRef(s.specularColor,r),yield o}}))}},Ga=!1;function Va(){Ga||(Ga=!0,ns(ka),ts(ka,!0,e=>new Da(e)))}Va();var Ha={__proto__:null,MSFT_sRGBFactors:Da,RegisterMSFT_sRGBFactors:Va};function Ka(e){const[t,n]=e.split(":");return $a({op:t,extension:n})}function $a(e,n=!0){var s;const o=e.extension?null===(s=qa[e.extension])||void 0===s?void 0:s[e.op]:Wa[e.op];if(!o&&(t.Logger.Warn(`No mapping found for operation ${e.op} and extension ${e.extension||"KHR_interactivity"}`),n)){const t={},n={flows:{}};if(e.inputValueSockets){t.values={};for(const n in e.inputValueSockets)t.values[n]={name:n}}return e.outputValueSockets&&(n.values={},Object.keys(e.outputValueSockets).forEach(e=>{n.values[e]={name:e}})),{blocks:[],inputs:t,outputs:n}}return o}function Ua(e,t,n){qa[t]||(qa[t]={}),qa[t][e]=n}const qa={BABYLON:{"flow/log":{blocks:["FlowGraphConsoleLogBlock"],inputs:{values:{message:{name:"message"}}}}}},Wa={"event/onStart":{blocks:["FlowGraphSceneReadyEventBlock"],outputs:{values:{event:{name:"event"}},flows:{out:{name:"done"}}}},"event/onTick":{blocks:["FlowGraphSceneTickEventBlock"],inputs:{},outputs:{values:{timeSinceLastTick:{name:"deltaTime",gltfType:"number"},event:{name:"event"}},flows:{out:{name:"done"}}}},"event/send":{blocks:["FlowGraphSendCustomEventBlock"],extraProcessor(e,t,n,s,o){var r;if("event/send"!==t.op||!e.configuration||1!==Object.keys(e.configuration).length)throw new Error("Receive event should have a single configuration object, the event itself");const i=null===(r=e.configuration.event.value)||void 0===r?void 0:r[0];if("number"!=typeof i)throw new Error("Event id should be a number");const a=s.arrays.events[i],l=o[0];return l.config||(l.config={}),l.config.eventId=a.eventId,l.config.eventData=a.eventData,o}},"event/receive":{blocks:["FlowGraphReceiveCustomEventBlock"],outputs:{values:{event:{name:"event"}},flows:{out:{name:"done"}}},validation(e,n){var s,o;if(!e.configuration)return t.Logger.Error("Receive event should have a configuration object"),{valid:!1,error:"Receive event should have a configuration object"};const r=e.configuration.event;if(!r)return t.Logger.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"};const i=null===(s=r.value)||void 0===s?void 0:s[0];return"number"!=typeof i?(t.Logger.Error("Event id should be a number"),{valid:!1,error:"Event id should be a number"}):(null===(o=n.events)||void 0===o?void 0:o[i])?{valid:!0}:(t.Logger.Error(`Event with id ${i} not found`),{valid:!1,error:`Event with id ${i} not found`})},extraProcessor(e,t,n,s,o){var r;if("event/receive"!==t.op||!e.configuration||1!==Object.keys(e.configuration).length)throw new Error("Receive event should have a single configuration object, the event itself");const i=null===(r=e.configuration.event.value)||void 0===r?void 0:r[0];if("number"!=typeof i)throw new Error("Event id should be a number");const a=s.arrays.events[i],l=o[0];return l.config||(l.config={}),l.config.eventId=a.eventId,l.config.eventData=a.eventData,o}},"event/stopPropagation":{blocks:["FlowGraphStopEventPropagationBlock"],inputs:{values:{event:{name:"event"},stopImmediate:{name:"stopImmediate"}},flows:{in:{name:"in"}}},outputs:{flows:{out:{name:"out"}}}},"math/E":za("FlowGraphEBlock"),"math/Pi":za("FlowGraphPIBlock"),"math/Tau":za("FlowGraphTauBlock"),"math/Inf":za("FlowGraphInfBlock"),"math/NaN":za("FlowGraphNaNBlock"),"math/abs":za("FlowGraphAbsBlock"),"math/sign":za("FlowGraphSignBlock"),"math/trunc":za("FlowGraphTruncBlock"),"math/floor":za("FlowGraphFloorBlock"),"math/ceil":za("FlowGraphCeilBlock"),"math/round":{blocks:["FlowGraphRoundBlock"],configuration:{},inputs:{values:{a:{name:"a"}}},outputs:{values:{value:{name:"value"}}},extraProcessor(e,t,n,s,o){var r;return(r=o[0]).config||(r.config={}),o[0].config.roundHalfAwayFromZero=!0,o}},"math/fract":za("FlowGraphFractBlock"),"math/neg":za("FlowGraphNegationBlock"),"math/add":za("FlowGraphAddBlock",["a","b"],!0),"math/sub":za("FlowGraphSubtractBlock",["a","b"],!0),"math/mul":{blocks:["FlowGraphMultiplyBlock"],extraProcessor(e,t,n,s,o){var r;(r=o[0]).config||(r.config={}),o[0].config.useMatrixPerComponent=!0,o[0].config.preventIntegerFloatArithmetic=!0;let i=-1;return Object.keys(e.values||{}).find(t=>{var n;return void 0!==(null===(n=e.values)||void 0===n?void 0:n[t].type)&&(i=e.values[t].type,!0)}),-1!==i&&(o[0].config.type=s.arrays.types[i].flowGraphType),o},validation:e=>e.values?ja(e):{valid:!0}},"math/div":za("FlowGraphDivideBlock",["a","b"],!0),"math/rem":za("FlowGraphModuloBlock",["a","b"]),"math/min":za("FlowGraphMinBlock",["a","b"]),"math/max":za("FlowGraphMaxBlock",["a","b"]),"math/clamp":za("FlowGraphClampBlock",["a","b","c"]),"math/saturate":za("FlowGraphSaturateBlock"),"math/mix":za("FlowGraphMathInterpolationBlock",["a","b","c"]),"math/smoothStep":za("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":za("FlowGraphMathSlerpBlock",["a","b","c"]),"math/slerp":za("FlowGraphVectorSlerpBlock",["a","b","c"]),"math/eq":za("FlowGraphEqualityBlock",["a","b"]),"ref/eq":za("FlowGraphEqualityBlock",["a","b"]),"math/lt":za("FlowGraphLessThanBlock",["a","b"]),"math/le":za("FlowGraphLessThanOrEqualBlock",["a","b"]),"math/gt":za("FlowGraphGreaterThanBlock",["a","b"]),"math/ge":za("FlowGraphGreaterThanOrEqualBlock",["a","b"]),"math/isNaN":za("FlowGraphIsNaNBlock"),"math/isInf":za("FlowGraphIsInfBlock"),"math/select":{blocks:["FlowGraphConditionalBlock"],inputs:{values:{condition:{name:"condition"},a:{name:"onTrue"},b:{name:"onFalse"}}},outputs:{values:{value:{name:"output"}}}},"math/random":{blocks:["FlowGraphRandomBlock"],outputs:{values:{value:{name:"value"}}}},"math/sin":za("FlowGraphSinBlock"),"math/cos":za("FlowGraphCosBlock"),"math/tan":za("FlowGraphTanBlock"),"math/asin":za("FlowGraphASinBlock"),"math/acos":za("FlowGraphACosBlock"),"math/atan":za("FlowGraphATanBlock"),"math/atan2":za("FlowGraphATan2Block",["a","b"]),"math/sinh":za("FlowGraphSinhBlock"),"math/cosh":za("FlowGraphCoshBlock"),"math/tanh":za("FlowGraphTanhBlock"),"math/asinh":za("FlowGraphASinhBlock"),"math/acosh":za("FlowGraphACoshBlock"),"math/atanh":za("FlowGraphATanhBlock"),"math/exp":za("FlowGraphExponentialBlock"),"math/log":za("FlowGraphLogBlock"),"math/log2":za("FlowGraphLog2Block"),"math/log10":za("FlowGraphLog10Block"),"math/sqrt":za("FlowGraphSquareRootBlock"),"math/cbrt":za("FlowGraphCubeRootBlock"),"math/pow":za("FlowGraphPowerBlock",["a","b"]),"math/length":za("FlowGraphLengthBlock"),"math/normalize":za("FlowGraphNormalizeBlock"),"math/dot":za("FlowGraphDotBlock",["a","b"]),"math/cross":za("FlowGraphCrossBlock",["a","b"]),"math/rotate2D":{blocks:["FlowGraphRotate2DBlock"],inputs:{values:{a:{name:"a"},angle:{name:"b"}}},outputs:{values:{value:{name:"value"}}}},"math/rotate3D":{blocks:["FlowGraphRotate3DBlock"],inputs:{values:{a:{name:"a"},rotation:{name:"b"}}},outputs:{values:{value:{name:"value"}}}},"math/transform":{blocks:["FlowGraphTransformVectorBlock"],inputs:{values:{a:{name:"a"},b:{name:"b"}}},outputs:{values:{value:{name:"value"}}}},"math/combine2":{blocks:["FlowGraphCombineVector2Block"],inputs:{values:{a:{name:"input_0",gltfType:"number"},b:{name:"input_1",gltfType:"number"}}},outputs:{values:{value:{name:"value"}}}},"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"}}}},"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"}}}},"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":za("FlowGraphTransposeBlock"),"math/determinant":za("FlowGraphDeterminantBlock"),"math/inverse":za("FlowGraphInvertMatrixBlock"),"math/matMul":za("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"}}},extraProcessor(e,t,n,s,o,r){const i=o[0].dataInputs.find(e=>"rotationQuaternion"===e.name);if(!i)throw new Error("Rotation quaternion input not found");return r._connectionValues[i.uniqueId]&&(r._connectionValues[i.uniqueId].type="Quaternion"),o}},"math/matDecompose":{blocks:["FlowGraphMatrixDecompose"],inputs:{values:{a:{name:"input",gltfType:"number"}}},outputs:{values:{translation:{name:"position"},rotation:{name:"rotationQuaternion"},scale:{name:"scaling"}}},extraProcessor(e,t,n,s,o){var r;return(r=o[0]).config||(r.config={}),o[0].config.keepDegenerateComponents=!0,o}},"math/quatConjugate":za("FlowGraphConjugateBlock",["a"]),"math/quatMul":{blocks:["FlowGraphMultiplyBlock"],inputs:{values:{a:{name:"a",gltfType:"vector4"},b:{name:"b",gltfType:"vector4"}}},outputs:{values:{value:{name:"value"}}},extraProcessor(e,t,n,s,o){var r;return(r=o[0]).config||(r.config={}),o[0].config.type="Quaternion",o}},"math/quatAngleBetween":za("FlowGraphAngleBetweenBlock",["a","b"]),"math/quatFromAxisAngle":{blocks:["FlowGraphQuaternionFromAxisAngleBlock"],inputs:{values:{axis:{name:"a",gltfType:"float3"},angle:{name:"b",gltfType:"number"}}},outputs:{values:{value:{name:"value"}}}},"math/quatToAxisAngle":za("FlowGraphAxisAngleFromQuaternionBlock",["a"]),"math/quatFromDirections":za("FlowGraphQuaternionFromDirectionsBlock",["a","b"]),"math/quatFromUpForward":{blocks:["FlowGraphQuaternionFromUpForwardBlock"],inputs:{values:{up:{name:"a",gltfType:"float3"},forward:{name:"b",gltfType:"float3"}}},outputs:{values:{value:{name:"value"}}}},"math/quatFromAngles":{blocks:["FlowGraphQuaternionFromAnglesBlock"],configuration:{order:{name:"order",defaultValue:["yxz"]}},inputs:{values:{x:{name:"a",gltfType:"number"},y:{name:"b",gltfType:"number"},z:{name:"c",gltfType:"number"}}},outputs:{values:{value:{name:"value"}}}},"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"}}}},"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"}}}},"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"},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"}}}},"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"}}},extraProcessor(e,t,n,s,o,r){var i,a,l;(l=o[0]).config||(l.config={});const u=o[0].dataInputs[0];return o[0].config.valueType=null!==(a=null===(i=r._connectionValues[u.uniqueId])||void 0===i?void 0:i.type)&&void 0!==a?a:"FlowGraphInteger",o}},"math/and":{blocks:["FlowGraphBitwiseAndBlock"],inputs:{values:{a:{name:"a"},b:{name:"b"}}},outputs:{values:{value:{name:"value"}}},extraProcessor(e,t,n,s,o,r){var i,a,l,u,c;(c=o[0]).config||(c.config={});const d=o[0].dataInputs[0],h=o[0].dataInputs[1];return o[0].config.valueType=null!==(u=null!==(a=null===(i=r._connectionValues[d.uniqueId])||void 0===i?void 0:i.type)&&void 0!==a?a:null===(l=r._connectionValues[h.uniqueId])||void 0===l?void 0:l.type)&&void 0!==u?u:"FlowGraphInteger",o}},"math/or":{blocks:["FlowGraphBitwiseOrBlock"],inputs:{values:{a:{name:"a"},b:{name:"b"}}},outputs:{values:{value:{name:"value"}}},extraProcessor(e,t,n,s,o,r){var i,a,l,u,c;(c=o[0]).config||(c.config={});const d=o[0].dataInputs[0],h=o[0].dataInputs[1];return o[0].config.valueType=null!==(u=null!==(a=null===(i=r._connectionValues[d.uniqueId])||void 0===i?void 0:i.type)&&void 0!==a?a:null===(l=r._connectionValues[h.uniqueId])||void 0===l?void 0:l.type)&&void 0!==u?u:"FlowGraphInteger",o}},"math/xor":{blocks:["FlowGraphBitwiseXorBlock"],inputs:{values:{a:{name:"a"},b:{name:"b"}}},outputs:{values:{value:{name:"value"}}},extraProcessor(e,t,n,s,o,r){var i,a,l,u,c;(c=o[0]).config||(c.config={});const d=o[0].dataInputs[0],h=o[0].dataInputs[1];return o[0].config.valueType=null!==(u=null!==(a=null===(i=r._connectionValues[d.uniqueId])||void 0===i?void 0:i.type)&&void 0!==a?a:null===(l=r._connectionValues[h.uniqueId])||void 0===l?void 0:l.type)&&void 0!==u?u:"FlowGraphInteger",o}},"math/asr":za("FlowGraphBitwiseRightShiftBlock",["a","b"]),"math/lsl":za("FlowGraphBitwiseLeftShiftBlock",["a","b"]),"math/clz":za("FlowGraphLeadingZerosBlock"),"math/ctz":za("FlowGraphTrailingZerosBlock"),"math/popcnt":za("FlowGraphOneBitsCounterBlock"),"math/rad":za("FlowGraphDegToRadBlock"),"math/deg":za("FlowGraphRadToDegBlock"),"type/boolToInt":za("FlowGraphBooleanToInt"),"type/boolToFloat":za("FlowGraphBooleanToFloat"),"type/intToBool":za("FlowGraphIntToBoolean"),"type/intToFloat":za("FlowGraphIntToFloat"),"type/floatToInt":za("FlowGraphFloatToInt"),"type/floatToBool":za("FlowGraphFloatToBoolean"),"flow/sequence":{blocks:["FlowGraphSequenceBlock"],extraProcessor(e,t,n,s,o){const r=o[0];return r.config||(r.config={}),r.config.outputSignalCount=Object.keys(e.flows||[]).length,r.signalOutputs.forEach((e,t)=>{e.name="out_"+t}),o}},"flow/branch":{blocks:["FlowGraphBranchBlock"],outputs:{flows:{true:{name:"onTrue"},false:{name:"onFalse"}}}},"flow/switch":{blocks:["FlowGraphSwitchBlock"],configuration:{cases:{name:"cases",isArray:!0,inOptions:!0,defaultValue:[]}},inputs:{values:{selection:{name:"case"},default:{name:"default"}}},validation(e){var n;const s=null===(n=e.configuration)||void 0===n?void 0:n.cases;if(s&&s.value){if(!s.value.every(e=>"number"==typeof e&&/^-?\d+$/.test(e.toString())))return t.Logger.Warn("Switch cases should be integers. Using empty array instead."),s.value=[],{valid:!0};const e=new Set(s.value);s.value=Array.from(e)}return{valid:!0}},extraProcessor(e,t,n,s,o){if("flow/switch"!==t.op||!e.flows||0===Object.keys(e.flows).length)throw new Error("Switch should have a single configuration object, the cases array");return o[0].signalOutputs.forEach(e=>{"default"!==e.name&&(e.name="out_"+e.name)}),o}},"flow/while":{blocks:["FlowGraphWhileLoopBlock"],outputs:{flows:{loopBody:{name:"executionFlow"}}}},"flow/for":{blocks:["FlowGraphForLoopBlock"],configuration:{initialIndex:{name:"initialIndex",gltfType:"number",inOptions:!0,defaultValue:0}},inputs:{values:{startIndex:{name:"startIndex",gltfType:"number"},endIndex:{name:"endIndex",gltfType:"number"}}},outputs:{values:{index:{name:"index"}},flows:{loopBody:{name:"executionFlow"}}},extraProcessor(e,t,n,s,o){const r=o[0];return r.config||(r.config={}),r.config.incrementIndexWhenLoopDone=!0,r.config.maxLoopIterations=2e4,o}},"flow/doN":{blocks:["FlowGraphDoNBlock"],configuration:{},inputs:{values:{n:{name:"maxExecutions",gltfType:"number"}}},outputs:{values:{currentCount:{name:"executionCount"}}}},"flow/multiGate":{blocks:["FlowGraphMultiGateBlock"],configuration:{isRandom:{name:"isRandom",gltfType:"boolean",inOptions:!0,defaultValue:!1},isLoop:{name:"isLoop",gltfType:"boolean",inOptions:!0,defaultValue:!1}},extraProcessor(e,t,n,s,o){if("flow/multiGate"!==t.op||!e.flows||0===Object.keys(e.flows).length)throw new Error("MultiGate should have a single configuration object, the number of output flows");const r=o[0];return r.config||(r.config={}),r.config.outputSignalCount=Object.keys(e.flows).length,r.signalOutputs.forEach((e,t)=>{e.name="out_"+t}),o}},"flow/waitAll":{blocks:["FlowGraphWaitAllBlock"],configuration:{inputFlows:{name:"inputSignalCount",gltfType:"number",inOptions:!0,defaultValue:0}},inputs:{flows:{reset:{name:"reset"},"[segment]":{name:"in_$1"}}},validation(e){var t,n,s;return"number"!=typeof(null===(s=null===(n=null===(t=e.configuration)||void 0===t?void 0:t.inputFlows)||void 0===n?void 0:n.value)||void 0===s?void 0:s[0])&&(e.configuration=e.configuration||{inputFlows:{value:[0]}},e.configuration.inputFlows.value=[0]),{valid:!0}}},"flow/throttle":{blocks:["FlowGraphThrottleBlock"],outputs:{flows:{err:{name:"error"}}}},"flow/setDelay":{blocks:["FlowGraphSetDelayBlock"],outputs:{flows:{err:{name:"error"}},values:{lastDelay:{name:"lastDelayIndex"}}}},"flow/cancelDelay":{blocks:["FlowGraphCancelDelayBlock"],inputs:{values:{delay:{name:"delayIndex"}}}},"variable/get":{blocks:["FlowGraphGetVariableBlock"],validation(e){var n,s;return(null===(s=null===(n=e.configuration)||void 0===n?void 0:n.variable)||void 0===s?void 0:s.value)?{valid:!0}:(t.Logger.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",flowGraphType:"string",inOptions:!0,isVariable:!0,dataTransformer:(e,t)=>t.getVariableName(e)}}},"variable/set":{blocks:["FlowGraphSetVariableBlock"],configuration:{variables:{name:"variables",gltfType:"number",flowGraphType:"string",inOptions:!0,isArray:!0,dataTransformer:(e,t)=>e.map(e=>t.getVariableName(e))}},extraProcessor:(e,t,n,s,o)=>(o[0].dataInputs.forEach(e=>{e.name=s.getVariableName(+e.name)}),o)},"variable/interpolate":{blocks:["FlowGraphInterpolationBlock","FlowGraphContextBlock","FlowGraphPlayAnimationBlock","FlowGraphBezierCurveEasing","FlowGraphGetVariableBlock"],configuration:{variable:{name:"propertyName",inOptions:!0,isVariable:!0,dataTransformer:(e,t)=>t.getVariableName(e)},useSlerp:{name:"animationType",inOptions:!0,defaultValue:!1,dataTransformer:e=>!0===e?"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,n,s,o,r){var i,a,l,u,c,d;const h=r[0],m=null===(a=null===(i=e.configuration)||void 0===i?void 0:i.variable.value)||void 0===a?void 0:a[0];if("number"!=typeof m)throw t.Logger.Error("Variable index is not defined for variable interpolation block"),new Error("Variable index is not defined for variable interpolation block");const f=o.arrays.staticVariables[m];void 0===(null===(u=null===(l=h.config)||void 0===l?void 0:l.animationType)||void 0===u?void 0:u.value)&&(h.config||(h.config={}),(c=h.config).animationType||(c.animationType={}),h.config.animationType.value=t.getAnimationTypeByFlowGraphType(f.type));const p=r[4];return p.config||(p.config={}),(d=p.config).variable||(d.variable={}),p.config.variable.value=o.getVariableName(m),r}},"pointer/get":{blocks:["FlowGraphGetPropertyBlock","FlowGraphJsonPointerParserBlock"],validation:Ya,configuration:{pointer:{name:"jsonPointer",toBlock:"FlowGraphJsonPointerParserBlock"}},inputs:{values:{"[segment]":{name:"$1",toBlock:"FlowGraphJsonPointerParserBlock"}}},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}],extraProcessor:(e,t,n,s,o)=>(o.forEach(e=>{"FlowGraphJsonPointerParserBlock"===e.className&&(e.config||(e.config={}),e.config.outputValue=!0)}),o)},"pointer/set":{blocks:["FlowGraphSetPropertyBlock","FlowGraphJsonPointerParserBlock"],validation:Ya,configuration:{pointer:{name:"jsonPointer",toBlock:"FlowGraphJsonPointerParserBlock"}},inputs:{values:{value:{name:"value"},"[segment]":{name:"$1",toBlock:"FlowGraphJsonPointerParserBlock"}}},outputs:{flows:{err:{name:"error"}}},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,s,o)=>(o.forEach(e=>{"FlowGraphJsonPointerParserBlock"===e.className&&(e.config||(e.config={}),e.config.outputValue=!0)}),o)},"pointer/interpolate":{blocks:["FlowGraphInterpolationBlock","FlowGraphJsonPointerParserBlock","FlowGraphPlayAnimationBlock","FlowGraphBezierCurveEasing"],validation:Ya,configuration:{pointer:{name:"jsonPointer",toBlock:"FlowGraphJsonPointerParserBlock"}},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,s,o)=>(o.forEach(t=>{"FlowGraphJsonPointerParserBlock"===t.className?(t.config||(t.config={}),t.config.outputValue=!0):"FlowGraphInterpolationBlock"===t.className&&(t.config||(t.config={}),Object.keys(e.values||[]).forEach(n=>{var o;const r=null===(o=e.values)||void 0===o?void 0:o[n];if("value"===n&&r){const e=r.type;void 0!==e&&(t.config.animationType=s.arrays.types[e].flowGraphType)}}))}),o)},"animation/start":{blocks:["FlowGraphPlayAnimationBlock","FlowGraphArrayIndexBlock","KHR_interactivity/FlowGraphGLTFDataProvider"],inputs:{values:{animation:{name:"index",gltfType:"number",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:{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,s,o,r,i){const a=o[o.length-1];return a.config||(a.config={}),a.config.glTF=i,o}},"animation/stop":{blocks:["FlowGraphStopAnimationBlock","FlowGraphArrayIndexBlock","KHR_interactivity/FlowGraphGLTFDataProvider"],inputs:{values:{animation:{name:"index",gltfType:"number",toBlock:"FlowGraphArrayIndexBlock"}}},outputs:{flows:{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,s,o,r,i){const a=o[o.length-1];return a.config||(a.config={}),a.config.glTF=i,o}},"animation/stopAt":{blocks:["FlowGraphStopAnimationBlock","FlowGraphArrayIndexBlock","KHR_interactivity/FlowGraphGLTFDataProvider"],configuration:{},inputs:{values:{animation:{name:"index",gltfType:"number",toBlock:"FlowGraphArrayIndexBlock"},stopTime:{name:"stopAtFrame",gltfType:"number",convertConnectedTimeToFrames:!0,dataTransformer:(e,t)=>[e[0]*t._animationTargetFps]}}},outputs:{flows:{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,s,o,r,i){const a=o[o.length-1];return a.config||(a.config={}),a.config.glTF=i,o}},"math/switch":{blocks:["FlowGraphDataSwitchBlock"],configuration:{cases:{name:"cases",isArray:!0,inOptions:!0,defaultValue:[]}},inputs:{values:{selection:{name:"case"}}},validation(e){var n;const s=null===(n=e.configuration)||void 0===n?void 0:n.cases;if(s&&s.value){if(!s.value.every(e=>"number"==typeof e&&/^-?\d+$/.test(e.toString())))return t.Logger.Warn("Switch cases should be integers. Using empty array instead."),s.value=[],{valid:!0};const e=new Set(s.value);s.value=Array.from(e)}return{valid:!0}},extraProcessor(e,t,n,s,o){const r=o[0];return r.dataInputs.forEach(e=>{"default"!==e.name&&"case"!==e.name&&(e.name="in_"+e.name)}),r.config||(r.config={}),r.config.treatCasesAsIntegers=!0,o}},"debug/log":{blocks:["FlowGraphConsoleLogBlock"],configuration:{message:{name:"messageTemplate",inOptions:!0}}}};function za(e,t=["a"],n){return{blocks:[e],inputs:{values:t.reduce((e,t)=>(e[t]={name:t},e),{})},outputs:{values:{value:{name:"value"}}},extraProcessor(e,t,s,o,r){var i;if(n){(i=r[0]).config||(i.config={}),r[0].config.preventIntegerFloatArithmetic=!0;let t=-1;Object.keys(e.values||{}).find(n=>{var s;return void 0!==(null===(s=e.values)||void 0===s?void 0:s[n].type)&&(t=e.values[n].type,!0)}),-1!==t&&(r[0].config.type=o.arrays.types[t].flowGraphType)}return r},validation:e=>n?ja(e):{valid:!0}}}function ja(e){if(e.values){const t=Object.keys(e.values).map(t=>e.values[t].type).filter(e=>void 0!==e);if(!t.every(e=>e===t[0]))return{valid:!1,error:"All inputs must be of the same type"}}return{valid:!0}}function Xa(e){for(let t=0;t<e.length;t++){const n=e[t];if(-1==="[]{}".indexOf(n))continue;let s=1;for(;e[t+s]===n;)s++;if(s%2!=0)return!0;t+=s-1}return!1}function Ya(e){var t,n,s;const o=null===(s=null===(n=null===(t=e.configuration)||void 0===t?void 0:t.pointer)||void 0===n?void 0:n.value)||void 0===s?void 0:s[0];if("string"!=typeof o)return{valid:!1,error:"A pointer operation requires a string `pointer` configuration value"};if(0!==o.length&&"/"!==o[0])return{valid:!1,error:`The JSON Pointer Template "${o}" is not a syntactically valid JSON Pointer`};const r=e=>({valid:!1,error:`The JSON Pointer Template "${o}" is invalid: ${e}`}),i=new Set;for(const e of o.split("/")){const t="["===e[0]&&"["!==e[1],n="{"===e[0]&&"{"!==e[1];if(!t&&!n){if(Xa(e))return r(`the path segment "${e}" contains an odd number of consecutive brackets`);continue}const s=t?"]":"}",o=e.substring(1,e.length-1);if(e.length<3||e[e.length-1]!==s||/[[{]/.test(o)||/[\]}]/.test(o))return r(`the template parameter path segment "${e}" is malformed`);const a=o.replace(/~1/g,"/").replace(/~0/g,"~");if(i.has(a))return r(`the template parameter "${a}" is used more than once`);i.add(a)}return{valid:!0}}function Qa(){return Object.keys(Wa)}const Za={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"}};class Ja{constructor(e,t,n=60){this._interactivityGraph=e,this._gltf=t,this._animationTargetFps=n,this._types=[],this._mappings=[],this._staticVariables=[],this._events=[],this._internalEventsCounter=0,this._nodes=[],this._insertedBlocks=[],this._parseTypes(),this._parseDeclarations(),this._parseVariables(),this._parseEvents(),this._parseNodes()}get arrays(){return{types:this._types,mappings:this._mappings,staticVariables:this._staticVariables,events:this._events,nodes:this._nodes}}_parseTypes(){if(this._interactivityGraph.types)for(const e of this._interactivityGraph.types)this._types.push(Za[e.signature])}_parseDeclarations(){if(this._interactivityGraph.declarations)for(const e of this._interactivityGraph.declarations){const n=$a(e);if(!n)throw t.Logger.Error(["No mapping found for declaration",e]),new Error("Error parsing declarations");this._mappings.push({flowGraphMapping:n,fullOperationName:e.extension?e.op+":"+e.extension:e.op})}}_parseVariables(){if(this._interactivityGraph.variables)for(const e of this._interactivityGraph.variables){const t=this._parseVariable(e);this._staticVariables.push(t)}}_parseVariable(e,n){const s=this._types[e.type];if(!s)throw t.Logger.Error(["No type found for variable",e]),new Error("Error parsing variables");if(e.value&&e.value.length!==s.length)throw t.Logger.Error(["Invalid value length for variable",e,s]),new Error("Error parsing variables");const o=e.value||[];if(!o.length)switch(s.flowGraphType){case"boolean":o.push(!1);break;case"FlowGraphInteger":o.push(0);break;case"number":o.push(NaN);break;case"string":o.push("");break;case"Vector2":o.push(NaN,NaN);break;case"Vector3":o.push(NaN,NaN,NaN);break;case"Vector4":case"Matrix2D":case"Quaternion":o.fill(NaN,0,4);break;case"Matrix":o.fill(NaN,0,16);break;case"Matrix3D":o.fill(NaN,0,9)}return"number"===s.elementType&&"string"==typeof o[0]&&(o[0]=parseFloat(o[0])),{type:s.flowGraphType,value:n?n(o,this):o}}_parseEvents(){if(this._interactivityGraph.events)for(const e of this._interactivityGraph.events){const n={eventId:e.id||"internalEvent_"+this._internalEventsCounter++};e.values&&(n.eventData=Object.keys(e.values).map(n=>{var s;const o=null===(s=e.values)||void 0===s?void 0:s[n];if(!o)throw t.Logger.Error(["No value found for event key",n]),new Error("Error parsing events");const r=this._types[o.type];if(!r)throw t.Logger.Error(["No type found for event value",o]),new Error("Error parsing events");const i=void 0!==o.value?this._parseVariable(o):void 0;return{id:n,type:r.flowGraphType,eventData:!0,value:i}})),this._events.push(n)}}_parseNodes(){var e;if(this._interactivityGraph.nodes)for(const n of this._interactivityGraph.nodes){if("number"!=typeof n.declaration)throw t.Logger.Error(["No declaration found for node",n]),new Error("Error parsing nodes");const s=this._mappings[n.declaration];if(!s)throw t.Logger.Error(["No mapping found for node",n]),new Error("Error parsing nodes");if(s.flowGraphMapping.validation){const t=s.flowGraphMapping.validation(n,this._interactivityGraph,this._gltf);if(!t.valid)throw new Error(`Error validating interactivity node ${null===(e=this._interactivityGraph.declarations)||void 0===e?void 0:e[n.declaration].op} - ${t.error}`)}const o=[];for(const e of s.flowGraphMapping.blocks){const t=this._getEmptyBlock(e,s.fullOperationName);this._parseNodeConfiguration(n,t,s.flowGraphMapping,e),o.push(t)}this._nodes.push({blocks:o,fullOperationName:s.fullOperationName})}}_getEmptyBlock(e,n){return{uniqueId:t.RandomGUID(),className:e,dataInputs:[],dataOutputs:[],signalInputs:[],signalOutputs:[],config:{},type:n,metadata:{}}}_parseNodeConfiguration(e,n,s,o){var r;const i=e.configuration;if(i)for(const e in i){const a=i[e];if(!a)throw new Error("Error parsing node configuration");const l=null===(r=s.configuration)||void 0===r?void 0:r[e];if(l&&l.toBlock?l.toBlock===o:0===s.blocks.indexOf(o)){let s=null==l?void 0:l.defaultValue;(null==a?void 0:a.value)&&(s=a.value),(null==l?void 0:l.isArray)||(1!==s.length&&t.Logger.Warn(`Invalid non-array value length: ${s.length}`),s=s[0]),(null==l?void 0:l.dataTransformer)&&(s=l.dataTransformer(s,this)),void 0!==s&&(n.config[(null==l?void 0:l.name)||e]={value:s})}}}_parseNodeConnections(e){var n,s,o,r,i,a,l,u,c,d,h,m,f,p,_,g,y,v,b;for(let x=0;x<this._nodes.length;x++){const T=null===(n=this._interactivityGraph.nodes)||void 0===n?void 0:n[x];if(!T)throw t.Logger.Error(["No node found for interactivity node",this._nodes[x]]),new Error("Error parsing node connections");const A=this._nodes[x],M=this._mappings[T.declaration];if(!M)throw t.Logger.Error(["No mapping found for node",T]),new Error("Error parsing node connections");if(0===A.blocks.length){t.Logger.Warn(`Skipping connections for no-op node #${x} (unsupported operation: ${A.fullOperationName})`);continue}const w=T.flows||{},C=Object.keys(w).sort();for(const e of C){const n=w[e],c=null===(o=null===(s=M.flowGraphMapping.outputs)||void 0===s?void 0:s.flows)||void 0===o?void 0:o[e],d=(null==c?void 0:c.name)||e,h=n.node,m=this._nodes[h];if(!m)throw t.Logger.Error(["No node found for input node id",h]),new Error("Error parsing node connections");if(0===m.blocks.length){t.Logger.Warn(`Dropping flow connection from node #${x} "${e}" to no-op node #${h} (unsupported operation: ${m.fullOperationName})`);continue}const f=this._createNewSocketConnection(d,!0);(c&&c.toBlock&&A.blocks.find(e=>e.className===c.toBlock)||A.blocks[0]).signalOutputs.push(f);const p=Ka(m.fullOperationName);if(!p)throw t.Logger.Error(["No mapping found for input node",m]),new Error("Error parsing node connections");let _=null===(i=null===(r=p.inputs)||void 0===r?void 0:r.flows)||void 0===i?void 0:i[n.socket||"in"],g=!1;if(!_)for(const e in null===(a=p.inputs)||void 0===a?void 0:a.flows)e.startsWith("[")&&e.endsWith("]")&&(g=!0,_=null===(u=null===(l=p.inputs)||void 0===l?void 0:l.flows)||void 0===u?void 0:u[e]);const y=_?g?_.name.replace("$1",n.socket||""):_.name:n.socket||"in",v=_&&_.toBlock&&m.blocks.find(e=>e.className===_.toBlock)||m.blocks[0];let b=v.signalInputs.find(e=>e.name===y);b||(b=this._createNewSocketConnection(y),v.signalInputs.push(b)),b.connectedPointIds.push(f.uniqueId),f.connectedPointIds.push(b.uniqueId)}const R=T.values||{},S=Object.keys(R);for(const n of S){const s=R[n];let o=null===(d=null===(c=M.flowGraphMapping.inputs)||void 0===c?void 0:c.values)||void 0===d?void 0:d[n],r=!1;if(!o)for(const e in null===(h=M.flowGraphMapping.inputs)||void 0===h?void 0:h.values)e.startsWith("[")&&e.endsWith("]")&&(r=!0,o=null===(f=null===(m=M.flowGraphMapping.inputs)||void 0===m?void 0:m.values)||void 0===f?void 0:f[e]);const i=o?r?o.name.replace("$1",n):o.name:n,a=this._createNewSocketConnection(i);(o&&o.toBlock&&A.blocks.find(e=>e.className===o.toBlock)||A.blocks[0]).dataInputs.push(a);const l=!!(null==o?void 0:o.convertConnectedTimeToFrames);if(void 0!==s.value){const t=this._parseVariable(s,o&&o.dataTransformer);e._connectionValues[a.uniqueId]=t}else{if(void 0===s.node)throw t.Logger.Error(["Invalid value for value connection",s]),new Error("Error parsing node connections");{const o=s.node,r=s.socket||"value",i=this._nodes[o];if(!i)throw t.Logger.Error(["No node found for output socket reference",s]),new Error("Error parsing node connections");if(0===i.blocks.length){t.Logger.Warn(`Dropping value connection from no-op node #${o} (unsupported operation: ${i.fullOperationName}) into node #${x} "${n}"; consumer will use type-default value`);continue}const u=Ka(i.fullOperationName);if(!u)throw t.Logger.Error(["No mapping found for output socket reference",s]),new Error("Error parsing node connections");let c=null===(_=null===(p=u.outputs)||void 0===p?void 0:p.values)||void 0===_?void 0:_[r],d=!1;if(!c)for(const e in null===(g=u.outputs)||void 0===g?void 0:g.values)e.startsWith("[")&&e.endsWith("]")&&(d=!0,c=null===(v=null===(y=u.outputs)||void 0===y?void 0:y.values)||void 0===v?void 0:v[e]);const h=c?d?c.name.replace("$1",r):null==c?void 0:c.name:r,m=c&&c.toBlock&&i.blocks.find(e=>e.className===c.toBlock)||i.blocks[0];let f=m.dataOutputs.find(e=>e.name===h);f||(f=this._createNewSocketConnection(h,!0),m.dataOutputs.push(f)),l?this._connectWithSecondsToFramesConversion(e,f,a):(a.connectedPointIds.push(f.uniqueId),f.connectedPointIds.push(a.uniqueId))}}}if(M.flowGraphMapping.interBlockConnectors)for(const e of M.flowGraphMapping.interBlockConnectors){const t=e.input,n=e.output,s=e.isVariable;this._connectFlowGraphNodes(t,n,A.blocks[e.inputBlockIndex],A.blocks[e.outputBlockIndex],s)}if(M.flowGraphMapping.extraProcessor){const n=null===(b=this._interactivityGraph.declarations)||void 0===b?void 0:b[T.declaration];if(!n)throw t.Logger.Error(["No declaration found for extra processor",T]),new Error("Error parsing node connections");A.blocks=M.flowGraphMapping.extraProcessor(T,n,M.flowGraphMapping,this,A.blocks,e,this._gltf)}}}_createNewSocketConnection(e,n){return{uniqueId:t.RandomGUID(),name:e,_connectionType:n?1:0,connectedPointIds:[]}}_connectWithSecondsToFramesConversion(e,t,n){const s=this._getEmptyBlock("FlowGraphMultiplyBlock","FlowGraphMultiplyBlock");s.config={type:"number"};const o=this._createNewSocketConnection("a"),r=this._createNewSocketConnection("b"),i=this._createNewSocketConnection("value",!0);s.dataInputs.push(o,r),s.dataOutputs.push(i),e._connectionValues[r.uniqueId]={type:"number",value:[this._animationTargetFps]},o.connectedPointIds.push(t.uniqueId),t.connectedPointIds.push(o.uniqueId),n.connectedPointIds.push(i.uniqueId),i.connectedPointIds.push(n.uniqueId),this._insertedBlocks.push(s)}_connectFlowGraphNodes(e,t,n,s,o){const r=o?n.dataInputs:n.signalInputs,i=o?s.dataOutputs:s.signalOutputs,a=r.find(t=>t.name===e)||this._createNewSocketConnection(e),l=i.find(e=>e.name===t)||this._createNewSocketConnection(t,!0);r.find(t=>t.name===e)||r.push(a),i.find(e=>e.name===t)||i.push(l),a.connectedPointIds.push(l.uniqueId),l.connectedPointIds.push(a.uniqueId)}getVariableName(e){return"staticVariable_"+e}serializeToFlowGraph(){const e={uniqueId:t.RandomGUID(),_userVariables:{},_connectionValues:{}};this._parseNodeConnections(e);for(let t=0;t<this._staticVariables.length;t++){const n=this._staticVariables[t];e._userVariables[this.getVariableName(t)]=n}return{rightHanded:!0,allBlocks:this._nodes.reduce((e,t)=>e.concat(t.blocks),[]).concat(this._insertedBlocks),executionContexts:[e]}}}class el{constructor(e,t){this._prefixes=e,this._fallback=t}addPrefix(e){this._prefixes.unshift(e)}convert(e){for(const{prefix:t,converter:n}of this._prefixes)if(e.startsWith(t))return n.convert(e);return this._fallback.convert(e)}}const tl="/extensions/BABYLON_scene_objects/";class nl{constructor(e,t){this._scene=e,this._tree=t}convert(e){if(!e.startsWith(tl))throw new Error(`BabylonScenePathToObjectConverter: path "${e}" does not start with the expected prefix "${tl}".`);const t=e.slice(34).split("/").filter(e=>e.length>0);if(0===t.length)throw new Error(`BabylonScenePathToObjectConverter: path "${e}" is missing a collection name.`);const n=t[0],s=this._tree[n];if(!s)throw new Error(`BabylonScenePathToObjectConverter: unknown collection "${n}" in path "${e}".`);if(2===t.length&&"length"===t[1])return{object:this._getCollectionArray(n),info:s.length};if(t.length<2)throw new Error(`BabylonScenePathToObjectConverter: path "${e}" is missing an instance id.`);if(!/^\d+$/.test(t[1]))throw new Error(`BabylonScenePathToObjectConverter: invalid uniqueId "${t[1]}" in path "${e}".`);const o=parseInt(t[1],10);if(!Number.isFinite(o)||o<0)throw new Error(`BabylonScenePathToObjectConverter: invalid uniqueId "${t[1]}" in path "${e}".`);const r=this._lookupInstanceByUniqueId(n,o);if(!r)throw new Error(`BabylonScenePathToObjectConverter: no ${n} instance found with uniqueId ${o} (path "${e}").`);if(2===t.length)return{object:r,info:this._buildIdentityAccessor(r)};if(t.length>3)throw new Error(`BabylonScenePathToObjectConverter: nested property paths are not yet supported (path "${e}").`);const i=t[2],a=s.__array__[i];if(!a||"boolean"==typeof a)throw new Error(`BabylonScenePathToObjectConverter: property "${i}" is not registered on ${n} (path "${e}").`);return{object:r,info:a}}_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}}}const sl="/extensions/KHR_interactivity/events/";const ol={isKhrInteractivityRef:!0};class rl{convert(e){const n=e.endsWith("/")?e.slice(0,-1):e;if(n.startsWith(sl)){const e=n.substring(37);return{object:ol,info:{type:"object",isReadOnly:!0,get:()=>e.length>0?n:void 0,getTarget:()=>ol}}}const s=n.substring(37),o=/^\d+$/.test(s)?parseInt(s,10):NaN;return{object:ol,info:{type:"object",isReadOnly:!0,get:(e,n,s)=>{const r=s;if(!(!r||isNaN(o)||o<0))return t.IsDelayActive(r,o)?new t.FlowGraphInteger(o):void 0},getTarget:()=>ol}}}}const il="/extensions/KHR_interactivity/limits/",al={major:2,minor:0},ll=2147483647,ul={maxActiveAnimations:ll,maxActiveDelays:ll,maxActivePropertyInterpolations:ll,maxActiveVariableInterpolations:ll},cl={isKhrInteractivityAssetCapability:!0};class dl{constructor(e,t){this._gltf=e,this._isExtensionEnabled=t}convert(e){const t=e.endsWith("/")?e.slice(0,-1):e;if(t.startsWith(il)){const n=ul[t.substring(37)];if(void 0===n)throw new Error(`Path ${e} is invalid`);return this._createAccessor("number",()=>n)}const n=t.substring(36);if("majorVersion"===n||"minorVersion"===n)return this._createAccessor("number",()=>{var e;return function(e){const[t,n]=(null!=e?e:"").split("."),s=parseInt(t,10),o=parseInt(n,10);return isNaN(s)?al:s!==al.major?s<al.major?{major:s,minor:isNaN(o)?0:o}:al:{major:s,minor:Math.min(isNaN(o)?0:o,al.minor)}}(null===(e=this._gltf.asset)||void 0===e?void 0:e.version)["majorVersion"===n?"major":"minor"]});const s=n.split("/");if(3===s.length&&"extensions"===s[0]&&"enabled"===s[2]){const e=s[1];return this._createAccessor("boolean",()=>this._isExtensionEnabled(e))}throw new Error(`Path ${e} is invalid`)}_createAccessor(e,t){return{object:cl,info:{type:e,isReadOnly:!0,get:t,getTarget:()=>cl}}}}class hl{encodeEventReference(e){return function(e){return sl+e}(e)}decodeEventReference(e){return function(e){return"string"==typeof(t=e)&&t.startsWith(sl)?e.substring(37):void 0;var t}(e)}decodeIndexReference(e){if(0===e.length||"/"!==e[0])return;const t=e.substring(e.lastIndexOf("/")+1);return/^(0|[1-9]\d*)$/.test(t)?parseInt(t,10):void 0}getObjectReference(e,t){var n,s;const o=null===(s=null===(n=e._internalMetadata)||void 0===n?void 0:n.gltf)||void 0===s?void 0:s.pointers;if(!Array.isArray(o))return;const r=o.filter(e=>"string"==typeof e);if(0!==r.length){if(t){const e=r.find(e=>e.split("/")[1]===t);if(e)return e}return r[0]}}}const ml="KHR_interactivity";let fl=class{constructor(e){var n;this._loader=e,this.name=ml,this.enabled=this._loader.isExtensionUsed(ml),this._gltfPathConverter=_s(this._loader.gltf);const s=e.babylonScene;if(this._gltfPathConverter){const e=[];s&&e.push({prefix:tl,converter:new nl(s,{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=>{var n;return null!==(n=e.rotationQuaternion)&&void 0!==n?n:t.Quaternion.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}}}})});const o=new rl;e.push({prefix:sl,converter:o}),e.push({prefix:"/extensions/KHR_interactivity/delays/",converter:o});const r=new Set((null!==(n=this._loader.gltf.extensionsUsed)&&void 0!==n?n:[]).filter(e=>{var t;return es.has(e)&&!1!==(null===(t=this._loader.parent.extensionOptions[e])||void 0===t?void 0:t.enabled)})),i=new dl(this._loader.gltf,e=>r.has(e));e.push({prefix:"/extensions/KHR_interactivity/asset/",converter:i}),e.push({prefix:il,converter:i}),this._pathConverter=new el(e,this._gltfPathConverter)}e._skipStartAnimationStep=!0,s&&pl(s)}dispose(){this._loader=null,delete this._gltfPathConverter,delete this._pathConverter}onReady(){return b(this,void 0,void 0,function*(){var e;if(!this._loader.babylonScene||!this._pathConverter)return;const n=this._loader.babylonScene,s=null===(e=this._loader.gltf.extensions)||void 0===e?void 0:e.KHR_interactivity;s&&(yield Promise.all(s.graphs.map((e,s)=>b(this,void 0,void 0,function*(){var o;const r=new t.FlowGraphCoordinator({scene:n,hostResolver:new hl});r.dispatchEventsSynchronously=!1;try{const n=new Ja(e,this._loader.gltf,this._loader.parent.targetFps);yield t.ParseFlowGraphAsync(n.serializeToFlowGraph(),{coordinator:r,pathConverter:this._pathConverter}),r.start()}catch(e){t.Logger.Error(`KHR_interactivity: rejecting behavior graph #${s}: ${null!==(o=null==e?void 0:e.message)&&void 0!==o?o:e}`),r.dispose()}}))))})}};function pl(e){vs("/extensions/KHR_interactivity/?/activeCamera/rotation",{get:()=>{if(!e.activeCamera)return new t.Quaternion(NaN,NaN,NaN,NaN);const n=t.Quaternion.FromRotationMatrix(e.activeCamera.getWorldMatrix()).normalize();return e.useRightHandedSystem||(n.w*=-1,n.x*=-1),n},type:"Quaternion",getTarget:()=>e.activeCamera}),vs("/extensions/KHR_interactivity/?/activeCamera/position",{get:()=>{if(!e.activeCamera)return new t.Vector3(NaN,NaN,NaN);const n=e.activeCamera.getWorldMatrix().getTranslation();return e.useRightHandedSystem||(n.x*=-1),n},type:"Vector3",getTarget:()=>e.activeCamera});const n=n=>{const s=e.activeCamera;return s&&s.mode!==t.Constants.ORTHOGRAPHIC_CAMERA?n(s):NaN},s=n=>{const s=e.activeCamera;return s&&s.mode===t.Constants.ORTHOGRAPHIC_CAMERA?n(s):NaN};vs("/extensions/KHR_interactivity/?/activeCamera/perspective/aspectRatio",{get:()=>n(e=>e.getEngine().getAspectRatio(e)),type:"number",getTarget:()=>e.activeCamera}),vs("/extensions/KHR_interactivity/?/activeCamera/perspective/yfov",{get:()=>n(e=>{if(e.fovMode===t.Constants.FOVMODE_VERTICAL_FIXED)return e.fov;const n=e.getEngine().getAspectRatio(e);return n?2*Math.atan(Math.tan(e.fov/2)/n):e.fov}),type:"number",getTarget:()=>e.activeCamera}),vs("/extensions/KHR_interactivity/?/activeCamera/perspective/znear",{get:()=>n(e=>e.minZ),type:"number",getTarget:()=>e.activeCamera}),vs("/extensions/KHR_interactivity/?/activeCamera/perspective/zfar",{get:()=>n(e=>0===e.maxZ?1/0:e.maxZ),type:"number",getTarget:()=>e.activeCamera}),vs("/extensions/KHR_interactivity/?/activeCamera/orthographic/xmag",{get:()=>s(e=>{var t,n;const s=e.getEngine().getRenderWidth()/2;return((null!==(t=e.orthoRight)&&void 0!==t?t:s)-(null!==(n=e.orthoLeft)&&void 0!==n?n:-s))/2}),type:"number",getTarget:()=>e.activeCamera}),vs("/extensions/KHR_interactivity/?/activeCamera/orthographic/ymag",{get:()=>s(e=>{var t,n;const s=e.getEngine().getRenderHeight()/2;return((null!==(t=e.orthoTop)&&void 0!==t?t:s)-(null!==(n=e.orthoBottom)&&void 0!==n?n:-s))/2}),type:"number",getTarget:()=>e.activeCamera}),vs("/extensions/KHR_interactivity/?/activeCamera/orthographic/znear",{get:()=>s(e=>e.minZ),type:"number",getTarget:()=>e.activeCamera}),vs("/extensions/KHR_interactivity/?/activeCamera/orthographic/zfar",{get:()=>s(e=>e.maxZ),type:"number",getTarget:()=>e.activeCamera}),vs("/animations/{}/extensions/KHR_interactivity/isPlaying",{get:e=>{var t,n;return null!==(n=null===(t=e._babylonAnimationGroup)||void 0===t?void 0:t.isPlaying)&&void 0!==n&&n},type:"boolean",getTarget:e=>e._babylonAnimationGroup}),vs("/animations/{}/extensions/KHR_interactivity/minTime",{get:e=>{var t,n;return(null!==(n=null===(t=e._babylonAnimationGroup)||void 0===t?void 0:t.from)&&void 0!==n?n:0)/60},type:"number",getTarget:e=>e._babylonAnimationGroup}),vs("/animations/{}/extensions/KHR_interactivity/maxTime",{get:e=>{var t,n;return(null!==(n=null===(t=e._babylonAnimationGroup)||void 0===t?void 0:t.to)&&void 0!==n?n:0)/60},type:"number",getTarget:e=>e._babylonAnimationGroup}),vs("/animations/{}/extensions/KHR_interactivity/playhead",{get:e=>{var t,n;return(null!==(n=null===(t=e._babylonAnimationGroup)||void 0===t?void 0:t.getCurrentFrame())&&void 0!==n?n:0)/60},type:"number",getTarget:e=>e._babylonAnimationGroup}),vs("/animations/{}/extensions/KHR_interactivity/virtualPlayhead",{get:e=>{var t,n;return(null!==(n=null===(t=e._babylonAnimationGroup)||void 0===t?void 0:t.getCurrentFrame())&&void 0!==n?n:0)/60},type:"number",getTarget:e=>e._babylonAnimationGroup})}let _l=!1;function gl(){_l||(_l=!0,t.addToBlockFactory(ml,"FlowGraphGLTFDataProvider",()=>b(this,void 0,void 0,function*(){return(yield Promise.resolve().then(function(){return Kl})).FlowGraphGLTFDataProvider})),ns(ml),ts(ml,!0,e=>new fl(e)))}gl();var yl={__proto__:null,KHR_interactivity:fl,RegisterKHR_interactivity:gl,_AddInteractivityObjectModel:pl};const vl="KHR_node_visibility";let bl=class{constructor(e){this.name=vl,this._loader=e,this.enabled=e.isExtensionUsed(vl)}onReady(){var e;if(!this._loader)return;const t=this._loader.gltf.nodes;if(t)for(const n of t){const t=n._babylonTransformNode;t&&(t.inheritVisibility=!0,n.extensions&&n.extensions.KHR_node_visibility&&!1===n.extensions.KHR_node_visibility.visible&&(t.isVisible=!1,null===(e=n._primitiveBabylonMeshes)||void 0===e||e.forEach(e=>{e.inheritVisibility=!0,e.isVisible=!1})))}}dispose(){delete this._loader}},xl=!1;function Tl(){xl||(xl=!0,vs("/nodes/{}/extensions/KHR_node_visibility/visible",{get:e=>{const t=e._babylonTransformNode;return!t||void 0===t.isVisible||t.isVisible},set:(e,t)=>{var n,s;null===(n=t._primitiveBabylonMeshes)||void 0===n||n.forEach(e=>{e.inheritVisibility=!0}),t._babylonTransformNode&&(t._babylonTransformNode.isVisible=e),null===(s=t._primitiveBabylonMeshes)||void 0===s||s.forEach(t=>{t.isVisible=e})},getTarget:e=>e._babylonTransformNode,getPropertyName:[()=>"isVisible"],type:"boolean"}),ns(vl),ts(vl,!0,e=>new bl(e)))}Tl();var Al={__proto__:null,KHR_node_visibility:bl,RegisterKHR_node_visibility:Tl};const Ml="KHR_node_selectability";let wl=class{constructor(e){this.name=Ml,this._loader=e,this.enabled=e.isExtensionUsed(Ml)}onReady(){return b(this,void 0,void 0,function*(){var e;null===(e=this._loader.gltf.nodes)||void 0===e||e.forEach(e=>{var t,n,s;(null===(t=e.extensions)||void 0===t?void 0:t.KHR_node_selectability)&&!1===(null===(n=e.extensions)||void 0===n?void 0:n.KHR_node_selectability.selectable)&&(null===(s=e._babylonTransformNode)||void 0===s||s.getChildMeshes().forEach(e=>{e.isPickable=!1}))})})}dispose(){this._loader=null}},Cl=!1;function Rl(){Cl||(Cl=!0,Ua("event/onSelect",Ml,{blocks:["FlowGraphMeshPickEventBlock","FlowGraphGetVariableBlock","FlowGraphIndexOfBlock","KHR_interactivity/FlowGraphGLTFDataProvider"],configuration:{stopPropagation:{name:"stopPropagation"},nodeIndex:{name:"variable",toBlock:"FlowGraphGetVariableBlock",dataTransformer:e=>"pickedMesh_"+e}},outputs:{values:{selectedNodeIndex:{name:"index",toBlock:"FlowGraphIndexOfBlock"},selectedNode:{name:"pickedMesh",toBlock:"FlowGraphMeshPickEventBlock"},controllerIndex:{name:"pointerId"},selectionPoint:{name:"pickedPoint"},selectionRayOrigin:{name:"pickOrigin"}},flows:{out:{name:"done"}}},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}],extraProcessor(e,t,n,s,o,r,i){var a,l,u,c,d,h,m;const f=o[o.length-1];f.config=f.config||{},f.config.glTF=i;const p=null===(u=null===(l=null===(a=e.configuration)||void 0===a?void 0:a.nodeIndex)||void 0===l?void 0:l.value)||void 0===u?void 0:u[0];if(void 0===p||"number"!=typeof p)throw new Error("nodeIndex not found in configuration");const _="pickedMesh_"+p;return o[1].config.variable=_,r._userVariables[_]={className:"Mesh",id:null===(d=null===(c=null==i?void 0:i.nodes)||void 0===c?void 0:c[p]._babylonTransformNode)||void 0===d?void 0:d.id,uniqueId:null===(m=null===(h=null==i?void 0:i.nodes)||void 0===h?void 0:h[p]._babylonTransformNode)||void 0===m?void 0:m.uniqueId},o}}),vs("/nodes/{}/extensions/KHR_node_selectability/selectable",{get:e=>{const t=e._babylonTransformNode;return!t||void 0===t.isPickable||t.isPickable},set:(e,t)=>{var n;null===(n=t._primitiveBabylonMeshes)||void 0===n||n.forEach(t=>{t.isPickable=e})},getTarget:e=>e._babylonTransformNode,getPropertyName:[()=>"isPickable"],type:"boolean"}),ns(Ml),ts(Ml,!0,e=>new wl(e)))}Rl();var Sl={__proto__:null,KHR_node_selectability:wl,RegisterKHR_node_selectability:Rl};const Ol="KHR_node_hoverability",Fl="targetMeshPointerOver_",El="targetMeshPointerOut_";let Il=class{constructor(e){this.name=Ol,this._loader=e,this.enabled=e.isExtensionUsed(Ol)}onReady(){return b(this,void 0,void 0,function*(){var e;null===(e=this._loader.gltf.nodes)||void 0===e||e.forEach(e=>{var t,n,s;(null===(t=e.extensions)||void 0===t?void 0:t.KHR_node_hoverability)&&!1===(null===(n=e.extensions)||void 0===n?void 0:n.KHR_node_hoverability.hoverable)&&(null===(s=e._babylonTransformNode)||void 0===s||s.getChildMeshes().forEach(e=>{e.pointerOverDisableMeshTesting=!0}))})})}dispose(){this._loader=null}},Ll=!1;function Pl(){Ll||(Ll=!0,Ua("event/onHoverIn",Ol,{blocks:["FlowGraphPointerOverEventBlock","FlowGraphGetVariableBlock","FlowGraphIndexOfBlock","KHR_interactivity/FlowGraphGLTFDataProvider"],configuration:{stopPropagation:{name:"stopPropagation"},nodeIndex:{name:"variable",toBlock:"FlowGraphGetVariableBlock",dataTransformer:e=>Fl+e}},outputs:{values:{hoverNodeIndex:{name:"index",toBlock:"FlowGraphIndexOfBlock"},hoveredNode:{name:"meshUnderPointer",toBlock:"FlowGraphPointerOverEventBlock"},controllerIndex:{name:"pointerId"}},flows:{out:{name:"done"}}},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}],extraProcessor(e,t,n,s,o,r,i){var a,l,u,c,d,h,m;const f=o[o.length-1];f.config=f.config||{},f.config.glTF=i;const p=null===(u=null===(l=null===(a=e.configuration)||void 0===a?void 0:a.nodeIndex)||void 0===l?void 0:l.value)||void 0===u?void 0:u[0];if(void 0===p||"number"!=typeof p)throw new Error("nodeIndex not found in configuration");const _=Fl+p;return o[1].config.variable=_,r._userVariables[_]={className:"Mesh",id:null===(d=null===(c=null==i?void 0:i.nodes)||void 0===c?void 0:c[p]._babylonTransformNode)||void 0===d?void 0:d.id,uniqueId:null===(m=null===(h=null==i?void 0:i.nodes)||void 0===h?void 0:h[p]._babylonTransformNode)||void 0===m?void 0:m.uniqueId},o}}),Ua("event/onHoverOut",Ol,{blocks:["FlowGraphPointerOutEventBlock","FlowGraphGetVariableBlock","FlowGraphIndexOfBlock","KHR_interactivity/FlowGraphGLTFDataProvider"],configuration:{stopPropagation:{name:"stopPropagation"},nodeIndex:{name:"variable",toBlock:"FlowGraphGetVariableBlock",dataTransformer:e=>El+e}},outputs:{values:{hoverNodeIndex:{name:"index",toBlock:"FlowGraphIndexOfBlock"},hoveredNode:{name:"meshOutOfPointer",toBlock:"FlowGraphPointerOutEventBlock"},controllerIndex:{name:"pointerId"}},flows:{out:{name:"done"}}},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}],extraProcessor(e,t,n,s,o,r,i){var a,l,u,c,d,h,m;const f=o[o.length-1];f.config=f.config||{},f.config.glTF=i;const p=null===(u=null===(l=null===(a=e.configuration)||void 0===a?void 0:a.nodeIndex)||void 0===l?void 0:l.value)||void 0===u?void 0:u[0];if(void 0===p||"number"!=typeof p)throw new Error("nodeIndex not found in configuration");const _=El+p;return o[1].config.variable=_,r._userVariables[_]={className:"Mesh",id:null===(d=null===(c=null==i?void 0:i.nodes)||void 0===c?void 0:c[p]._babylonTransformNode)||void 0===d?void 0:d.id,uniqueId:null===(m=null===(h=null==i?void 0:i.nodes)||void 0===h?void 0:h[p]._babylonTransformNode)||void 0===m?void 0:m.uniqueId},o}}),vs("/nodes/{}/extensions/KHR_node_hoverability/hoverable",{get:e=>{const t=e._babylonTransformNode;return!t||void 0===t.pointerOverDisableMeshTesting||t.pointerOverDisableMeshTesting},set:(e,t)=>{var n;null===(n=t._primitiveBabylonMeshes)||void 0===n||n.forEach(t=>{t.pointerOverDisableMeshTesting=!e})},getTarget:e=>e._babylonTransformNode,getPropertyName:[()=>"pointerOverDisableMeshTesting"],type:"boolean"}),ns(Ol),ts(Ol,!0,e=>new Il(e)))}Pl();var Bl={__proto__:null,KHR_node_hoverability:Il,RegisterKHR_node_hoverability:Pl};const Nl="ExtrasAsMetadata";let kl=class{_assignExtras(e,t){if(t.extras&&Object.keys(t.extras).length>0){const n=e.metadata=e.metadata||{};(n.gltf=n.gltf||{}).extras=t.extras}}constructor(e){this.name=Nl,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){const s=this._loader.createMaterial(e,t,n);return this._assignExtras(s,t),s}loadAnimationAsync(e,t){return this._loader.loadAnimationAsync(e,t).then(e=>(this._assignExtras(e,t),e))}},Dl=!1;function Gl(){Dl||(Dl=!0,ns(Nl),ts(Nl,!1,e=>new kl(e)))}Gl();var Vl={__proto__:null,ExtrasAsMetadata:kl,RegisterExtrasAsMetadata:Gl};class Hl extends t.FlowGraphBlock{constructor(e){var n,s;super(e);const o=e.glTF,r=(null===(n=null==o?void 0:o.animations)||void 0===n?void 0:n.map(e=>e._babylonAnimationGroup))||[];this.animationGroups=this.registerDataOutput("animationGroups",t.RichTypeAny,r);const i=(null===(s=null==o?void 0:o.nodes)||void 0===s?void 0:s.map(e=>e._babylonTransformNode))||[];this.nodes=this.registerDataOutput("nodes",t.RichTypeAny,i)}getClassName(){return"FlowGraphGLTFDataProvider"}}var Kl={__proto__:null,FlowGraphGLTFDataProvider:Hl},$l={__proto__:null,AddObjectAccessorToKey:vs,EXT_lights_area:Bo,EXT_lights_ies:ho,EXT_lights_image_based:Vs,EXT_mesh_gpu_instancing:qs,EXT_meshopt_compression:Ys,EXT_texture_avif:io,EXT_texture_webp:to,ExtrasAsMetadata:kl,FlowGraphGLTFDataProvider:Hl,GetMappingForKey:gs,GetPathToObjectConverter:_s,InteractivityGraphToFlowGraphParser:Ja,KHR_animation_pointer:Ui,KHR_draco_mesh_compression:go,KHR_gaussian_splatting:wo,KHR_interactivity:fl,KHR_lights:Fo,KHR_materials_anisotropy:dr,KHR_materials_clearcoat:Yo,KHR_materials_coat:tr,KHR_materials_diffuse_roughness:vi,KHR_materials_diffuse_transmission:Jr,KHR_materials_dispersion:fi,KHR_materials_emissive_strength:_r,KHR_materials_fuzz:Cr,KHR_materials_ior:Nr,KHR_materials_iridescence:ir,KHR_materials_pbrSpecularGlossiness:Vo,KHR_materials_sheen:xr,KHR_materials_specular:Er,KHR_materials_transmission:jr,KHR_materials_unlit:qo,KHR_materials_variants:Hr,KHR_materials_volume:oi,KHR_materials_volume_scatter:ui,KHR_mesh_quantization:Mi,KHR_node_hoverability:Il,KHR_node_selectability:wl,KHR_node_visibility:bl,KHR_texture_basisu:Oi,KHR_texture_transform:Pi,KHR_xmp_json_ld:Gi,MSFT_audio_emitter:Aa,MSFT_lod:Sa,MSFT_minecraftMesh:La,MSFT_sRGBFactors:Da,RegisterEXT_lights_area:ko,RegisterEXT_lights_ies:fo,RegisterEXT_lights_image_based:Ks,RegisterEXT_mesh_gpu_instancing:zs,RegisterEXT_meshopt_compression:Zs,RegisterEXT_texture_avif:lo,RegisterEXT_texture_webp:so,RegisterExtrasAsMetadata:Gl,RegisterKHR_animation_pointer:Wi,RegisterKHR_draco_mesh_compression:vo,RegisterKHR_gaussian_splatting:Ro,RegisterKHR_interactivity:gl,RegisterKHR_lights:Io,RegisterKHR_materials_anisotropy:mr,RegisterKHR_materials_clearcoat:Zo,RegisterKHR_materials_coat:sr,RegisterKHR_materials_diffuse_roughness:xi,RegisterKHR_materials_diffuse_transmission:ti,RegisterKHR_materials_dispersion:_i,RegisterKHR_materials_emissive_strength:yr,RegisterKHR_materials_fuzz:Sr,RegisterKHR_materials_ior:Dr,RegisterKHR_materials_iridescence:lr,RegisterKHR_materials_pbrSpecularGlossiness:Ko,RegisterKHR_materials_sheen:Ar,RegisterKHR_materials_specular:Lr,RegisterKHR_materials_transmission:Yr,RegisterKHR_materials_unlit:zo,RegisterKHR_materials_variants:$r,RegisterKHR_materials_volume:ii,RegisterKHR_materials_volume_scatter:di,RegisterKHR_mesh_quantization:Ci,RegisterKHR_node_hoverability:Pl,RegisterKHR_node_selectability:Rl,RegisterKHR_node_visibility:Tl,RegisterKHR_texture_basisu:Ei,RegisterKHR_texture_transform:Ni,RegisterKHR_xmp_json_ld:Hi,RegisterMSFT_audio_emitter:wa,RegisterMSFT_lod:Fa,RegisterMSFT_minecraftMesh:Ba,RegisterMSFT_sRGBFactors:Va,SetInterpolationForKey:ys,TransmissionHelper:qr,_AddInteractivityObjectModel:pl,addNewInteractivityFlowGraphMapping:Ua,ensureTransmissionHelper:Wr,getAllSupportedNativeNodeTypes:Qa,getMappingForDeclaration:$a,getMappingForFullOperationName:Ka,gltfTypeToBabylonType:Za},Ul={__proto__:null,AddObjectAccessorToKey:vs,AnimationPropertyInfo:Es,ArrayItem:Ts,EXT_lights_area:Bo,EXT_lights_ies:ho,EXT_lights_image_based:Vs,EXT_mesh_gpu_instancing:qs,EXT_meshopt_compression:Ys,EXT_texture_avif:io,EXT_texture_webp:to,ExtrasAsMetadata:kl,FlowGraphGLTFDataProvider:Hl,GLTFFileLoader:mn,GLTFLoader:Ms,GetMappingForKey:gs,GetPathToObjectConverter:_s,InteractivityGraphToFlowGraphParser:Ja,KHR_animation_pointer:Ui,KHR_draco_mesh_compression:go,KHR_gaussian_splatting:wo,KHR_interactivity:fl,KHR_lights:Fo,KHR_materials_anisotropy:dr,KHR_materials_clearcoat:Yo,KHR_materials_coat:tr,KHR_materials_diffuse_roughness:vi,KHR_materials_diffuse_transmission:Jr,KHR_materials_dispersion:fi,KHR_materials_emissive_strength:_r,KHR_materials_fuzz:Cr,KHR_materials_ior:Nr,KHR_materials_iridescence:ir,KHR_materials_pbrSpecularGlossiness:Vo,KHR_materials_sheen:xr,KHR_materials_specular:Er,KHR_materials_transmission:jr,KHR_materials_unlit:qo,KHR_materials_variants:Hr,KHR_materials_volume:oi,KHR_materials_volume_scatter:ui,KHR_mesh_quantization:Mi,KHR_node_hoverability:Il,KHR_node_selectability:wl,KHR_node_visibility:bl,KHR_texture_basisu:Oi,KHR_texture_transform:Pi,KHR_xmp_json_ld:Gi,LoadBoundingInfoFromPositionAccessor:As,MSFT_audio_emitter:Aa,MSFT_lod:Sa,MSFT_minecraftMesh:La,MSFT_sRGBFactors:Da,OpenPBRMaterialLoadingAdapter:Bs,PBRMaterialLoadingAdapter:ks,RegisterEXT_lights_area:ko,RegisterEXT_lights_ies:fo,RegisterEXT_lights_image_based:Ks,RegisterEXT_mesh_gpu_instancing:zs,RegisterEXT_meshopt_compression:Zs,RegisterEXT_texture_avif:lo,RegisterEXT_texture_webp:so,RegisterExtrasAsMetadata:Gl,RegisterGLTF2Loader:Cs,RegisterKHR_animation_pointer:Wi,RegisterKHR_draco_mesh_compression:vo,RegisterKHR_gaussian_splatting:Ro,RegisterKHR_interactivity:gl,RegisterKHR_lights:Io,RegisterKHR_materials_anisotropy:mr,RegisterKHR_materials_clearcoat:Zo,RegisterKHR_materials_coat:sr,RegisterKHR_materials_diffuse_roughness:xi,RegisterKHR_materials_diffuse_transmission:ti,RegisterKHR_materials_dispersion:_i,RegisterKHR_materials_emissive_strength:yr,RegisterKHR_materials_fuzz:Sr,RegisterKHR_materials_ior:Dr,RegisterKHR_materials_iridescence:lr,RegisterKHR_materials_pbrSpecularGlossiness:Ko,RegisterKHR_materials_sheen:Ar,RegisterKHR_materials_specular:Lr,RegisterKHR_materials_transmission:Yr,RegisterKHR_materials_unlit:zo,RegisterKHR_materials_variants:$r,RegisterKHR_materials_volume:ii,RegisterKHR_materials_volume_scatter:di,RegisterKHR_mesh_quantization:Ci,RegisterKHR_node_hoverability:Pl,RegisterKHR_node_selectability:Rl,RegisterKHR_node_visibility:Tl,RegisterKHR_texture_basisu:Ei,RegisterKHR_texture_transform:Ni,RegisterKHR_xmp_json_ld:Hi,RegisterMSFT_audio_emitter:wa,RegisterMSFT_lod:Fa,RegisterMSFT_minecraftMesh:Ba,RegisterMSFT_sRGBFactors:Va,SetInterpolationForKey:ys,TransformNodeAnimationPropertyInfo:Is,TransmissionHelper:qr,WeightAnimationPropertyInfo:Ls,_AddInteractivityObjectModel:pl,addNewInteractivityFlowGraphMapping:Ua,ensureTransmissionHelper:Wr,getAllSupportedNativeNodeTypes:Qa,getMappingForDeclaration:$a,getMappingForFullOperationName:Ka,getQuaternion:Os,getVector3:Ss,getWeights:Fs,gltfTypeToBabylonType:Za,registerGLTFExtension:ts,registeredGLTFExtensions:es,unregisterGLTFExtension:ns};class ql{constructor(){this.materials=[]}parseMTL(e,n,s,o){if(n instanceof ArrayBuffer)return;const r=n.split("\n"),i=/\s+/;let a,l=null;for(let n=0;n<r.length;n++){const u=r[n].trim();if(0===u.length||"#"===u.charAt(0))continue;const c=u.indexOf(" ");let d=c>=0?u.substring(0,c):u;d=d.toLowerCase();const h=c>=0?u.substring(c+1).trim():"";if("newmtl"===d)l&&this.materials.push(l),e._blockEntityCollection=!!o,l=new t.StandardMaterial(h,e),l._parentContainer=o,e._blockEntityCollection=!1;else if("kd"===d&&l)a=h.split(i,3).map(parseFloat),l.diffuseColor=t.Color3.FromArray(a);else if("ka"===d&&l)a=h.split(i,3).map(parseFloat),l.ambientColor=t.Color3.FromArray(a);else if("ks"===d&&l)a=h.split(i,3).map(parseFloat),l.specularColor=t.Color3.FromArray(a);else if("ke"===d&&l)a=h.split(i,3).map(parseFloat),l.emissiveColor=t.Color3.FromArray(a);else if("ns"===d&&l)l.specularPower=parseFloat(h);else if("d"===d&&l)l.alpha=parseFloat(h);else if("map_ka"===d&&l)l.ambientTexture=ql._GetTexture(s,h,e);else if("map_kd"===d&&l)l.diffuseTexture=ql._GetTexture(s,h,e);else if("map_ks"===d&&l)l.specularTexture=ql._GetTexture(s,h,e);else if("map_ns"===d);else if("map_bump"===d&&l){const t=h.split(i),n=t.indexOf("-bm");let o=null;n>=0&&(o=t[n+1],t.splice(n,2)),l.bumpTexture=ql._GetTexture(s,t.join(" "),e),l.bumpTexture&&null!==o&&(l.bumpTexture.level=parseFloat(o))}else"map_d"===d&&l&&(l.opacityTexture=ql._GetTexture(s,h,e))}l&&this.materials.push(l)}static _GetTexture(e,n,s){if(!n)return null;let o=e;if("file:"===e){let e=n.lastIndexOf("\\");-1===e&&(e=n.lastIndexOf("/")),o+=e>-1?n.substring(e+1):n}else o+=n;return new t.Texture(o,s,!1,ql.INVERT_TEXTURE_Y)}}ql.INVERT_TEXTURE_Y=!0;class Wl{constructor(e,n,s){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 t.Color4(.5,.5,.5,1),this._hasLineData=!1,this._materialToUse=e,this._babylonMeshesArray=n,this._loadingOptions=s}_isInArray(e,t){e[t[0]]||(e[t[0]]={normals:[],idx:[]});const n=e[t[0]].normals.indexOf(t[1]);return-1===n?-1:e[t[0]].idx[n]}_isInArrayUV(e,t){e[t[0]]||(e[t[0]]={normals:[],idx:[],uv:[]});const n=e[t[0]].normals.indexOf(t[1]);return 1!=n&&t[2]===e[t[0]].uv[n]?e[t[0]].idx[n]:-1}_setData(e){var t,n;let s;null!==(t=e.indiceUvsFromObj)&&void 0!==t||(e.indiceUvsFromObj=-1),null!==(n=e.indiceNormalFromObj)&&void 0!==n||(e.indiceNormalFromObj=-1),s=this._loadingOptions.optimizeWithUV?this._isInArrayUV(this._tuplePosNorm,[e.indicePositionFromObj,e.indiceNormalFromObj,e.indiceUvsFromObj]):this._isInArray(this._tuplePosNorm,[e.indicePositionFromObj,e.indiceNormalFromObj]),-1===s?(this._indicesForBabylon.push(this._wrappedPositionForBabylon.length),this._wrappedPositionForBabylon.push(e.positionVectorFromOBJ),void 0!==e.textureVectorFromOBJ&&this._wrappedUvsForBabylon.push(e.textureVectorFromOBJ),void 0!==e.normalsVectorFromOBJ&&this._wrappedNormalsForBabylon.push(e.normalsVectorFromOBJ),void 0!==e.positionColorsFromOBJ&&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(s)}_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 new 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){var t;return this._loadingOptions.importVertexColors?null!==(t=this._extColors[e])&&void 0!==t?t:this._colors[e]:void 0}_setDataForCurrentFaceWithPattern1(e,t){this._getTriangles(e,t);for(let e=0;e<this._triangles.length;e++){const 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++){const t=this._triangles[e].split("/"),n=parseInt(t[0])-1,s=parseInt(t[1])-1;this._setData({indicePositionFromObj:n,indiceUvsFromObj:s,positionVectorFromOBJ:this._positions[n],textureVectorFromOBJ:this._uvs[s],positionColorsFromOBJ:this._getColor(n)})}this._triangles.length=0}_setDataForCurrentFaceWithPattern3(e,t){this._getTriangles(e,t);for(let e=0;e<this._triangles.length;e++){const t=this._triangles[e].split("/"),n=parseInt(t[0])-1,s=parseInt(t[1])-1,o=parseInt(t[2])-1;this._setData({indicePositionFromObj:n,indiceUvsFromObj:s,indiceNormalFromObj:o,positionVectorFromOBJ:this._positions[n],textureVectorFromOBJ:this._uvs[s],normalsVectorFromOBJ:this._normals[o]})}this._triangles.length=0}_setDataForCurrentFaceWithPattern4(e,t){this._getTriangles(e,t);for(let e=0;e<this._triangles.length;e++){const t=this._triangles[e].split("//"),n=parseInt(t[0])-1,s=parseInt(t[1])-1;this._setData({indicePositionFromObj:n,indiceNormalFromObj:s,positionVectorFromOBJ:this._positions[n],normalsVectorFromOBJ:this._normals[s],positionColorsFromOBJ:this._getColor(n)})}this._triangles.length=0}_setDataForCurrentFaceWithPattern5(e,t){this._getTriangles(e,t);for(let e=0;e<this._triangles.length;e++){const t=this._triangles[e].split("/"),n=this._positions.length+parseInt(t[0]),s=this._uvs.length+parseInt(t[1]),o=this._normals.length+parseInt(t[2]);this._setData({indicePositionFromObj:n,indiceUvsFromObj:s,indiceNormalFromObj:o,positionVectorFromOBJ:this._positions[n],textureVectorFromOBJ:this._uvs[s],normalsVectorFromOBJ:this._normals[o],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){const n=e.getVerticesData(t.VertexBuffer.PositionKind),s=e.getVerticesData(t.VertexBuffer.NormalKind),o={};if(!n||!s)return;for(let e=0;e<n.length/3;e++){const t=n[3*e+0]+"_"+n[3*e+1]+"_"+n[3*e+2];let s=o[t];s||(s=[],o[t]=s),s.push(e)}const r=new t.Vector3;for(const e in o){const t=o[e];if(t.length<2)continue;const n=t[0];for(let e=1;e<t.length;++e){const o=t[e];s[3*n+0]+=s[3*o+0],s[3*n+1]+=s[3*o+1],s[3*n+2]+=s[3*o+2]}r.copyFromFloats(s[3*n+0],s[3*n+1],s[3*n+2]),r.normalize();for(let e=0;e<t.length;++e){const n=t[e];s[3*n+0]=r.x,s[3*n+1]=r.y,s[3*n+2]=r.z}}e.setVerticesData(t.VertexBuffer.NormalKind,s)}static _IsLineElement(e){return e.startsWith("l")}static _IsObjectElement(e){return e.startsWith("o")}static _IsGroupElement(e){return e.startsWith("g")}static _GetZbrushMRGB(e,n){if(!e.startsWith("mrgb"))return null;if(e=e.replace("mrgb","").trim(),n)return[];const s=e.match(/[a-z0-9]/g);if(!s||s.length%8!=0)return[];const o=[];for(let e=0;e<s.length/8;e++){const n=s[8*e+2]+s[8*e+3],r=s[8*e+4]+s[8*e+5],i=s[8*e+6]+s[8*e+7];o.push(new t.Color4(parseInt(n,16)/255,parseInt(r,16)/255,parseInt(i,16)/255,1))}return o}parse(e,n,s,o,r){var i,a,l,u,c;n=(n=n.replace(/#MRGB/g,"mrgb")).replace(/#.*$/gm,"").trim(),this._loadingOptions.useLegacyBehavior?(this._pushTriangle=(e,t)=>this._triangles.push(e[0],e[t],e[t+1]),this._handednessSign=1):s.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);const d=n.split("\n"),h=[];let m=[];h.push(m);for(let e=0;e<d.length;e++){const t=d[e].trim().replace(/\s\s/g," ");if(0!==t.length&&"#"!==t.charAt(0))if((Wl._IsGroupElement(t)||Wl._IsObjectElement(t))&&(m=[],h.push(m)),Wl._IsLineElement(t)){const e=t.split(" ");for(let t=1;t<e.length-1;t++)m.push(`l ${e[t]} ${e[t+1]}`)}else m.push(t)}const f=h.flat();for(let e=0;e<f.length;e++){const n=f[e].trim().replace(/\s\s/g," ");let s;if(0!==n.length&&"#"!==n.charAt(0))if(Wl.VertexPattern.test(n)){if(s=n.match(/[^ ]+/g),this._positions.push(new t.Vector3(parseFloat(s[1]),parseFloat(s[2]),parseFloat(s[3]))),this._loadingOptions.importVertexColors)if(s.length>=7){const e=parseFloat(s[4]),n=parseFloat(s[5]),o=parseFloat(s[6]);this._colors.push(new t.Color4(e>1?e/255:e,n>1?n/255:n,o>1?o/255:o,7===s.length||void 0===s[7]?1:parseFloat(s[7])))}else this._colors.push(this._grayColor)}else if(null!==(s=Wl.NormalPattern.exec(n)))this._normals.push(new t.Vector3(parseFloat(s[1]),parseFloat(s[2]),parseFloat(s[3])));else if(null!==(s=Wl.UVPattern.exec(n)))this._uvs.push(new t.Vector2(parseFloat(s[1])*this._loadingOptions.UVScaling.x,parseFloat(s[2])*this._loadingOptions.UVScaling.y));else if(null!==(s=Wl.FacePattern3.exec(n)))this._setDataForCurrentFaceWithPattern3(s[1].trim().split(" "),1);else if(null!==(s=Wl.FacePattern4.exec(n)))this._setDataForCurrentFaceWithPattern4(s[1].trim().split(" "),1);else if(null!==(s=Wl.FacePattern5.exec(n)))this._setDataForCurrentFaceWithPattern5(s[1].trim().split(" "),1);else if(null!==(s=Wl.FacePattern2.exec(n)))this._setDataForCurrentFaceWithPattern2(s[1].trim().split(" "),1);else if(null!==(s=Wl.FacePattern1.exec(n)))this._setDataForCurrentFaceWithPattern1(s[1].trim().split(" "),1);else if(null!==(s=Wl.LinePattern1.exec(n)))this._setDataForCurrentFaceWithPattern1(s[1].trim().split(" "),0),this._hasLineData=!0;else if(null!==(s=Wl.LinePattern2.exec(n)))this._setDataForCurrentFaceWithPattern2(s[1].trim().split(" "),0),this._hasLineData=!0;else if(s=Wl._GetZbrushMRGB(n,!this._loadingOptions.importVertexColors))for(const e of s)this._extColors.push(e);else if(null!==(s=Wl.LinePattern3.exec(n)))this._setDataForCurrentFaceWithPattern3(s[1].trim().split(" "),0),this._hasLineData=!0;else if(Wl.GroupDescriptor.test(n)||Wl.ObjectDescriptor.test(n)){const e={name:n.substring(2).trim(),indices:null,positions:null,normals:null,uvs:null,colors:null,materialName:this._materialNameFromObj,isObject:Wl.ObjectDescriptor.test(n)};this._addPreviousObjMesh(),this._meshesFromObj.push(e),this._hasMeshes=!0,this._isFirstMaterial=!0,this._increment=1}else if(Wl.UseMtlDescriptor.test(n)){if(this._materialNameFromObj=n.substring(7).trim(),!this._isFirstMaterial||!this._hasMeshes){this._addPreviousObjMesh();const 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 Wl.MtlLibGroupDescriptor.test(n)?r(n.substring(7).trim()):Wl.SmoothDescriptor.test(n)||t.Logger.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(const e of this._positions)this._unwrappedPositionsForBabylon.push(e.x,e.y,e.z);if(this._normals.length)for(const e of this._normals)this._unwrappedNormalsForBabylon.push(e.x,e.y,e.z);if(this._uvs.length)for(const e of this._uvs)this._unwrappedUVForBabylon.push(e.x,e.y);if(this._extColors.length)for(const e of this._extColors)this._unwrappedColorsForBabylon.push(e.r,e.g,e.b,e.a);else if(this._colors.length)for(const e of this._colors)this._unwrappedColorsForBabylon.push(e.r,e.g,e.b,e.a);this._materialNameFromObj||(e=new t.StandardMaterial(t.Geometry.RandomId(),s),e.pointsCloud=!0,this._materialNameFromObj=e.name,this._normals.length||(e.disableLighting=!0,e.emissiveColor=t.Color3.White()))}this._meshesFromObj.push({name:t.Geometry.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 n=0;n<this._meshesFromObj.length;n++){if(e&&this._meshesFromObj[n].name)if(e instanceof Array){if(-1===e.indexOf(this._meshesFromObj[n].name))continue}else if(this._meshesFromObj[n].name!==e)continue;this._handledMesh=this._meshesFromObj[n],s._blockEntityCollection=!!o;const r=new t.Mesh(this._meshesFromObj[n].name,s);if(r._parentContainer=o,s._blockEntityCollection=!1,this._handledMesh._babylonMesh=r,!this._handledMesh.isObject)for(let e=n-1;e>=0;--e)if(this._meshesFromObj[e].isObject&&this._meshesFromObj[e]._babylonMesh){r.parent=this._meshesFromObj[e]._babylonMesh;break}if(this._materialToUse.push(this._meshesFromObj[n].materialName),this._handledMesh.hasLines&&(null!==(i=r._internalMetadata)&&void 0!==i||(r._internalMetadata={}),r._internalMetadata._isLine=!0),0===(null===(a=this._handledMesh.positions)||void 0===a?void 0:a.length)){this._babylonMeshesArray.push(r);continue}const d=new t.VertexData;if(d.indices=this._handledMesh.indices,d.positions=this._handledMesh.positions,this._loadingOptions.computeNormals||!(null===(l=this._handledMesh.normals)||void 0===l?void 0:l.length)){const e=new Array;t.VertexData.ComputeNormals(this._handledMesh.positions,this._handledMesh.indices,e),d.normals=e}else d.normals=this._handledMesh.normals;(null===(u=this._handledMesh.uvs)||void 0===u?void 0:u.length)&&(d.uvs=this._handledMesh.uvs),(null===(c=this._handledMesh.colors)||void 0===c?void 0:c.length)&&(d.colors=this._handledMesh.colors),d.applyToMesh(r),this._loadingOptions.invertY&&(r.scaling.y*=-1),this._loadingOptions.optimizeNormals&&this._optimizeNormals(r),this._babylonMeshesArray.push(r),this._handledMesh.directMaterial&&(r.material=this._handledMesh.directMaterial)}}}Wl.ObjectDescriptor=/^o/,Wl.GroupDescriptor=/^g/,Wl.MtlLibGroupDescriptor=/^mtllib /,Wl.UseMtlDescriptor=/^usemtl /,Wl.SmoothDescriptor=/^s /,Wl.VertexPattern=/^v(\s+[\d|.|+|\-|e|E]+){3,7}/,Wl.NormalPattern=/^vn(\s+[\d|.|+|\-|e|E]+)( +[\d|.|+|\-|e|E]+)( +[\d|.|+|\-|e|E]+)/,Wl.UVPattern=/^vt(\s+[\d|.|+|\-|e|E]+)( +[\d|.|+|\-|e|E]+)/,Wl.FacePattern1=/^f\s+(([\d]{1,}[\s]?){3,})+/,Wl.FacePattern2=/^f\s+((([\d]{1,}\/[\d]{1,}[\s]?){3,})+)/,Wl.FacePattern3=/^f\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){3,})+)/,Wl.FacePattern4=/^f\s+((([\d]{1,}\/\/[\d]{1,}[\s]?){3,})+)/,Wl.FacePattern5=/^f\s+(((-[\d]{1,}\/-[\d]{1,}\/-[\d]{1,}[\s]?){3,})+)/,Wl.LinePattern1=/^l\s+(([\d]{1,}[\s]?){2,})+/,Wl.LinePattern2=/^l\s+((([\d]{1,}\/[\d]{1,}[\s]?){2,})+)/,Wl.LinePattern3=/^l\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){2,})+)/;const zl={name:"obj",extensions:".obj"};class jl{static get INVERT_TEXTURE_Y(){return ql.INVERT_TEXTURE_Y}static set INVERT_TEXTURE_Y(e){ql.INVERT_TEXTURE_Y=e}constructor(e){this.name=zl.name,this.extensions=zl.extensions,this._assetContainer=null,this._loadingOptions=Object.assign(Object.assign({},jl._DefaultLoadingOptions),null!=e?e:{})}static get _DefaultLoadingOptions(){return{computeNormals:jl.COMPUTE_NORMALS,optimizeNormals:jl.OPTIMIZE_NORMALS,importVertexColors:jl.IMPORT_VERTEX_COLORS,invertY:jl.INVERT_Y,invertTextureY:jl.INVERT_TEXTURE_Y,UVScaling:jl.UV_SCALING,materialLoadingFailsSilently:jl.MATERIAL_LOADING_FAILS_SILENTLY,optimizeWithUV:jl.OPTIMIZE_WITH_UV,skipMaterials:jl.SKIP_MATERIALS,useLegacyBehavior:jl.USE_LEGACY_BEHAVIOR}}_loadMTL(e,n,s,o){const r=n+e;t.Tools.LoadFile(r,s,void 0,void 0,!1,(e,t)=>{o(r,t)})}createPlugin(e){return new jl(e[zl.name])}canDirectLoad(){return!1}importMeshAsync(e,t,n,s){return this._parseSolidAsync(e,t,n,s).then(e=>({meshes:e,particleSystems:[],skeletons:[],animationGroups:[],transformNodes:[],geometries:[],lights:[],spriteManagers:[]}))}loadAsync(e,t,n){return this.importMeshAsync(null,e,t,n).then(()=>{})}loadAssetContainerAsync(e,n,s){const o=new t.AssetContainer(e);return this._assetContainer=o,this.importMeshAsync(null,e,n,s).then(e=>(e.meshes.forEach(e=>o.meshes.push(e)),e.meshes.forEach(e=>{const t=e.material;t&&-1==o.materials.indexOf(t)&&(o.materials.push(t),t.getActiveTextures().forEach(e=>{-1==o.textures.indexOf(e)&&o.textures.push(e)}))}),this._assetContainer=null,o)).catch(e=>{throw this._assetContainer=null,e})}_parseSolidAsync(e,n,s,o){let r="";const i=new ql,a=[],l=[];s=s.replace(/#.*$/gm,"").trim(),new Wl(a,l,this._loadingOptions).parse(e,s,n,this._assetContainer,e=>{r=e});const u=[];return""===r||this._loadingOptions.skipMaterials||u.push(new Promise((e,s)=>{this._loadMTL(r,o,u=>{try{i.parseMTL(n,u,o,this._assetContainer);for(let e=0;e<i.materials.length;e++){let t=0;const n=[];let s;for(;(s=a.indexOf(i.materials[e].name,t))>-1;)n.push(s),t=s+1;if(-1===s&&0===n.length)i.materials[e].dispose();else for(let t=0;t<n.length;t++){const s=l[n[t]],o=i.materials[e];s.material=o,s.getTotalIndices()||(o.pointsCloud=!0)}}e()}catch(n){t.Tools.Warn(`Error processing MTL file: '${r}'`),this._loadingOptions.materialLoadingFailsSilently?e():s(n)}},(n,o)=>{t.Tools.Warn(`Error downloading MTL file: '${r}'`),this._loadingOptions.materialLoadingFailsSilently?e():s(o)})})),Promise.all(u).then(()=>{const e=e=>{var t,n;return Boolean(null!==(n=null===(t=e._internalMetadata)||void 0===t?void 0:t._isLine)&&void 0!==n&&n)};return l.forEach(s=>{var o,r;if(e(s)){let i=null!==(o=s.material)&&void 0!==o?o:new t.StandardMaterial(s.name+"_line",n);i.getBindedMeshes().filter(t=>!e(t)).length>0&&(i=null!==(r=i.clone(i.name+"_line"))&&void 0!==r?r:i),i.wireframe=!0,s.material=i,s._internalMetadata&&(s._internalMetadata._isLine=void 0)}}),l})}}jl.OPTIMIZE_WITH_UV=!0,jl.INVERT_Y=!1,jl.IMPORT_VERTEX_COLORS=!1,jl.COMPUTE_NORMALS=!1,jl.OPTIMIZE_NORMALS=!1,jl.UV_SCALING=new t.Vector2(1,1),jl.SKIP_MATERIALS=!1,jl.MATERIAL_LOADING_FAILS_SILENTLY=!0,jl.USE_LEGACY_BEHAVIOR=!1;let Xl=!1;function Yl(){Xl||(Xl=!0,t.RegisterSceneLoaderPlugin(new jl))}Yl();var Ql={__proto__:null,OBJFileLoader:jl,RegisterOBJFileLoader:Yl},Zl={__proto__:null,MTLFileLoader:ql,OBJFileLoader:jl,RegisterOBJFileLoader:Yl,SolidParser:Wl};const Jl={name:"stl",extensions:{".stl":{isBinary:!0}}};class eu{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=Jl.name,this.extensions=Jl.extensions}importMesh(e,n,s,o,r){let i;if("string"!=typeof s){if(this._isBinary(s)){const e=new t.Mesh("stlmesh",n);return this._parseBinary(e,s),r&&r.push(e),!0}s=(new TextDecoder).decode(new Uint8Array(s))}for(;i=this.solidPattern.exec(s);){let s=i[1];const o=i[3];if(o&&s!=o)return t.Tools.Error("Error in STL, solid name != endsolid name"),!1;if(e&&s)if(e instanceof Array){if(!e.indexOf(s))continue}else if(s!==e)continue;s=s||"stlmesh";const a=new t.Mesh(s,n);this._parseASCII(a,i[2]),r&&r.push(a)}return!0}load(e,t,n){return this.importMesh(null,e,t,n,null)}loadAssetContainer(e,n,s){const o=new t.AssetContainer(e);return e._blockEntityCollection=!0,this.importMesh(null,e,n,s,o.meshes),e._blockEntityCollection=!1,o}_isBinary(e){const t=new DataView(e);if(t.byteLength<=80)return!1;if(84+50*t.getUint32(80,!0)===t.byteLength)return!0;const n=[115,111,108,105,100];for(let e=0;e<5;e++)if(t.getUint8(e)!==n[e])return!0;return!1}_parseBinary(e,n){const s=new DataView(n),o=s.getUint32(80,!0);let r=0;const i=new Float32Array(3*o*3),a=new Float32Array(3*o*3),l=new Uint32Array(3*o);let u=0;for(let e=0;e<o;e++){const t=84+50*e,n=s.getFloat32(t,!0),o=s.getFloat32(t+4,!0),c=s.getFloat32(t+8,!0);for(let e=1;e<=3;e++){const l=t+12*e;i[r]=s.getFloat32(l,!0),a[r]=n,eu.DO_NOT_ALTER_FILE_COORDINATES?(i[r+1]=s.getFloat32(l+4,!0),i[r+2]=s.getFloat32(l+8,!0),a[r+1]=o,a[r+2]=c):(i[r+2]=s.getFloat32(l+4,!0),i[r+1]=s.getFloat32(l+8,!0),a[r+2]=o,a[r+1]=c),r+=3}eu.DO_NOT_ALTER_FILE_COORDINATES?(l[u]=u,l[u+1]=u+2,l[u+2]=u+1,u+=3):(l[u]=u++,l[u]=u++,l[u]=u++)}e.setVerticesData(t.VertexBuffer.PositionKind,i),e.setVerticesData(t.VertexBuffer.NormalKind,a),e.setIndices(l),e.computeWorldMatrix(!0)}_parseASCII(e,n){const s=[],o=[],r=[];let i,a=0;for(;i=this.facetsPattern.exec(n);){const e=i[1],t=this.normalPattern.exec(e);if(this.normalPattern.lastIndex=0,!t)continue;const n=[Number(t[1]),Number(t[5]),Number(t[3])];let l;for(;l=this.vertexPattern.exec(e);)eu.DO_NOT_ALTER_FILE_COORDINATES?(s.push(Number(l[1]),Number(l[3]),Number(l[5])),o.push(n[0],n[2],n[1])):(s.push(Number(l[1]),Number(l[5]),Number(l[3])),o.push(n[0],n[1],n[2]));eu.DO_NOT_ALTER_FILE_COORDINATES?(r.push(a,a+2,a+1),a+=3):r.push(a++,a++,a++),this.vertexPattern.lastIndex=0}this.facetsPattern.lastIndex=0,e.setVerticesData(t.VertexBuffer.PositionKind,s),e.setVerticesData(t.VertexBuffer.NormalKind,o),e.setIndices(r),e.computeWorldMatrix(!0)}}eu.DO_NOT_ALTER_FILE_COORDINATES=!1;let tu=!1;function nu(){tu||(tu=!0,t.RegisterSceneLoaderPlugin(new eu))}nu();var su={__proto__:null,RegisterSTLFileLoader:nu,STLFileLoader:eu},ou={__proto__:null,RegisterSTLFileLoader:nu,STLFileLoader:eu};const ru={name:"splat",extensions:{".splat":{isBinary:!0},".ply":{isBinary:!0},".spz":{isBinary:!0},".json":{isBinary:!1},".sog":{isBinary:!0}}},iu=.28209479177387814;function au(e,t,n){return b(this,void 0,void 0,function*(){const s=new Promise((s,o)=>{const r=n.createCanvasImage();if(!r)throw new Error("Failed to create ImageBitmap");let i;if(r.onload=()=>{try{const e=n.createCanvas(r.width,r.height);if(!e)throw new Error("Failed to create canvas");const t=e.getContext("2d");if(!t)throw new Error("Failed to get 2D context");t.drawImage(r,0,0);const o=t.getImageData(0,0,e.width,e.height);s({bits:new Uint8Array(o.data.buffer),width:o.width,height:o.height})}catch(e){o(`Error loading image ${r.src} with exception: ${e}`)}},r.onerror=e=>{o(`Error loading image ${r.src} with exception: ${e}`)},r.crossOrigin="anonymous","string"==typeof e){if(!t)throw new Error("filename is required when using a URL");r.src=e+t}else{const t=new Blob([e],{type:"image/webp"});i=URL.createObjectURL(t),r.src=i}});return yield s})}function lu(e,n,s){return b(this,void 0,void 0,function*(){let o,r;if(e instanceof Map){r=e;const t=r.get("meta.json");if(!t)throw new Error("meta.json not found in files Map");o=JSON.parse((new TextDecoder).decode(t))}else o=e;const i=[...o.means.files,...o.scales.files,...o.quats.files,...o.sh0.files];o.shN&&i.push(...o.shN.files);const a=yield Promise.all(i.map(e=>b(this,void 0,void 0,function*(){if(r&&r.has(e)){const t=r.get(e);return yield au(t,e,s.getEngine())}return yield au(n,e,s.getEngine())})));return yield function(e,n,s){return b(this,void 0,void 0,function*(){const o=e.count?e.count:e.means.shape[0],r=new ArrayBuffer(32*o),i=new Float32Array(r),a=new Float32Array(r),l=new Uint8ClampedArray(r),u=new Uint8ClampedArray(r),c=e=>Math.sign(e)*(Math.exp(Math.abs(e))-1),d=n[0].bits,h=n[1].bits;if(!Array.isArray(e.means.mins)||!Array.isArray(e.means.maxs))throw new Error("Missing arrays in SOG data.");for(let n=0;n<o;n++){const s=4*n;for(let o=0;o<3;o++){const r=e.means.mins[o],a=e.means.maxs[o],l=h[s+o]<<8|d[s+o],u=t.Scalar.Lerp(r,a,l/65535);i[8*n+o]=c(u)}}const m=n[2].bits;if(2===e.version){if(!e.scales.codebook)throw new Error("Missing codebook in SOG version 2 scales data.");for(let t=0;t<o;t++){const n=4*t;for(let s=0;s<3;s++){const o=e.scales.codebook[m[n+s]],r=Math.exp(o);a[8*t+3+s]=r}}}else{if(!Array.isArray(e.scales.mins)||!Array.isArray(e.scales.maxs))throw new Error("Missing arrays in SOG scales data.");for(let n=0;n<o;n++){const s=4*n;for(let o=0;o<3;o++){const r=m[s+o],i=t.Scalar.Lerp(e.scales.mins[o],e.scales.maxs[o],r/255),l=Math.exp(i);a[8*n+3+o]=l}}}const f=n[4].bits;if(2===e.version){if(!e.sh0.codebook)throw new Error("Missing codebook in SOG version 2 sh0 data.");for(let t=0;t<o;t++){const n=4*t;for(let s=0;s<3;s++){const o=.5+e.sh0.codebook[f[n+s]]*iu;l[32*t+24+s]=Math.max(0,Math.min(255,Math.round(255*o)))}l[32*t+24+3]=f[n+3]}}else{if(!Array.isArray(e.sh0.mins)||!Array.isArray(e.sh0.maxs))throw new Error("Missing arrays in SOG sh0 data.");for(let n=0;n<o;n++){const s=4*n;for(let o=0;o<4;o++){const r=e.sh0.mins[o],i=e.sh0.maxs[o],a=f[s+o],u=t.Scalar.Lerp(r,i,a/255);let c;c=o<3?.5+u*iu:1/(1+Math.exp(-u)),l[32*n+24+o]=Math.max(0,Math.min(255,Math.round(255*c)))}}}const p=e=>2*(e/255-.5)/Math.SQRT2,_=n[3].bits;for(let e=0;e<o;e++){const t=_[4*e+0],n=_[4*e+1],s=_[4*e+2],o=_[4*e+3],r=p(t),i=p(n),a=p(s),l=o-252,c=r*r+i*i+a*a,d=Math.sqrt(Math.max(0,1-c));let h;switch(l){case 0:h=[d,r,i,a];break;case 1:h=[r,d,i,a];break;case 2:h=[r,i,d,a];break;case 3:h=[r,i,a,d];break;default:throw new Error("Invalid quaternion mode")}u[32*e+28+0]=127.5*h[0]+127.5,u[32*e+28+1]=127.5*h[1]+127.5,u[32*e+28+2]=127.5*h[2]+127.5,u[32*e+28+3]=127.5*h[3]+127.5}if(e.shN){const i=e.shN.bands?Math.pow(e.shN.bands+1,2)-1:e.shN.shape[1]/3,a=void 0!==e.shN.bands&&null!==e.shN.bands?e.shN.bands:Math.round(Math.sqrt(i+1)-1),l=n[5].bits,u=n[6].bits,c=n[5].width,d=3*i,h=Math.ceil(d/16),m=s.getEngine().getCaps().maxTextureSize,f=Math.ceil(o/m),p=t.AllocateShBuffers(h,f*m*4*4);if(2===e.version){if(!e.shN.codebook)throw new Error("Missing codebook in SOG version 2 shN data.");for(let t=0;t<o;t++){const n=u[4*t+0]+(u[4*t+1]<<8),s=n%64*i,o=Math.floor(n/64);for(let n=0;n<i;n++)for(let r=0;r<3;r++){const i=3*n+r,a=Math.floor(i/16),u=p[a],d=i%16,h=16*t,m=127.5*e.shN.codebook[l[4*(s+n)+r+o*c*4]]+127.5;u[d+h]=Math.max(0,Math.min(255,m))}}}else for(let n=0;n<o;n++){const s=u[4*n+0]+(u[4*n+1]<<8),o=s%64*i,r=Math.floor(s/64),a=e.shN.mins,d=e.shN.maxs;for(let e=0;e<3;e++)for(let s=0;s<i/3;s++){const i=3*s+e,u=Math.floor(i/16),h=p[u],m=i%16,f=16*n,_=127.5*t.Scalar.Lerp(a,d,l[4*(o+s)+e+r*c*4]/255)+127.5;h[m+f]=Math.max(0,Math.min(255,_))}}return yield new Promise(e=>{e({mode:0,data:r,hasVertexColors:!1,sh:p,shDegree:a})})}return yield new Promise(e=>{e({mode:0,data:r,hasVertexColors:!1})})})}(o,a,s)})}function uu(e,n){return function(e,n,s,o){const r=new t.RawTexture(n,s,o,t.Constants.TEXTUREFORMAT_RGBA,e,!1,!1,t.Constants.TEXTURE_NEAREST_SAMPLINGMODE,t.Constants.TEXTURETYPE_UNSIGNED_BYTE);return r.wrapU=t.Constants.TEXTURE_CLAMP_ADDRESSMODE,r.wrapV=t.Constants.TEXTURE_CLAMP_ADDRESSMODE,r}(e,n.bits,n.width,n.height)}function cu(e,n,s){return b(this,void 0,void 0,function*(){const o=s.getEngine();if("function"==typeof createImageBitmap)try{const r=n.toLowerCase().endsWith(".png")?"image/png":"image/webp";let i;if("string"==typeof e){const s=yield t.Tools.LoadFileAsync(e+n,!0);i=new Blob([s],{type:r})}else i=new Blob([e],{type:r});const a=yield createImageBitmap(i,{premultiplyAlpha:"none",colorSpaceConversion:"none"});try{const e=new t.RawTexture(null,a.width,a.height,t.Constants.TEXTUREFORMAT_RGBA,s,!1,!1,t.Constants.TEXTURE_NEAREST_SAMPLINGMODE,t.Constants.TEXTURETYPE_UNSIGNED_BYTE);e.wrapU=t.Constants.TEXTURE_CLAMP_ADDRESSMODE,e.wrapV=t.Constants.TEXTURE_CLAMP_ADDRESSMODE;const n=e.getInternalTexture();return n&&o.updateDynamicTexture(n,a,!1,!1),e}finally{a.close()}}catch(e){}const r=yield au(e,n,o);return uu(s,r)})}function du(e,n,s,o){const r=e=>Math.sign(e)*(Math.exp(Math.abs(e))-1);if(!Array.isArray(e.means.mins)||!Array.isArray(e.means.maxs))throw new Error("Missing arrays in SOG data.");const i=new Float32Array(4*o);for(let a=0;a<o;a++){const o=4*a;for(let l=0;l<3;l++){const u=s[o+l]<<8|n[o+l],c=t.Scalar.Lerp(e.means.mins[l],e.means.maxs[l],u/65535);i[4*a+l]=r(c)}i[4*a+3]=1}return i}function hu(e,n,s){return b(this,arguments,void 0,function*(e,n,s,o=!0,r,i){var a,l,u,c,d,h,m;let f,p;if(e instanceof Map){p=e;const t=p.get("meta.json");if(!t)throw new Error("meta.json not found in files Map");f=JSON.parse((new TextDecoder).decode(t))}else f=e;const _=e=>b(this,void 0,void 0,function*(){if(p&&p.has(e))return yield au(p.get(e),e,s.getEngine());if(r){const t=new Uint8Array(yield r.loadFileAsync(n+e,i));return yield au(t,e,s.getEngine())}return yield au(n,e,s.getEngine())}),g=e=>b(this,void 0,void 0,function*(){if(p&&p.has(e))return yield cu(p.get(e),e,s);if(r){const t=new Uint8Array(yield r.loadFileAsync(n+e,i));return yield cu(t,e,s)}return yield cu(n,e,s)}),y=[...f.scales.files,...f.quats.files,...f.sh0.files,...null!==(l=null===(a=f.shN)||void 0===a?void 0:a.files)&&void 0!==l?l:[]];let v,x,T,A,M,w=null;if(o){const[e,t]=yield Promise.all([Promise.all(f.means.files.map(_)),Promise.all(y.map(g))]);w=[e[0],e[1]],M=t,v=uu(s,e[0]),x=uu(s,e[1]),T=e[0].width,A=e[0].height}else{const[e,t]=yield Promise.all([Promise.all(f.means.files.map(g)),Promise.all(y.map(g))]);M=t,v=e[0],x=e[1];const n=v.getSize();T=n.width,A=n.height}const C=null!==(u=f.count)&&void 0!==u?u:f.means.shape[0],R=T*A;if(R<C)throw new Error(`SOG texture contains ${R} texels, but metadata references ${C} splats.`);const S=M[0],O=M[1],F=M[2];let E,I,L,P=0,B=0;if(f.shN&&M.length>=5&&(E=M[3],I=M[4],P=f.shN.bands?Math.pow(f.shN.bands+1,2)-1:f.shN.shape[1]/3,B=null!==(c=f.shN.bands)&&void 0!==c?c:Math.round(Math.sqrt(P+1)-1)),2===f.version){const e=256,n=new Float32Array(3*e);f.scales.codebook&&n.set(f.scales.codebook.slice(0,e),0),f.sh0.codebook&&n.set(f.sh0.codebook.slice(0,e),e),(null===(d=f.shN)||void 0===d?void 0:d.codebook)&&n.set(f.shN.codebook.slice(0,e),2*e),L=new t.RawTexture(n,3*e,1,t.Constants.TEXTUREFORMAT_R,s,!1,!1,t.Constants.TEXTURE_NEAREST_SAMPLINGMODE,t.Constants.TEXTURETYPE_FLOAT),L.wrapU=t.Constants.TEXTURE_CLAMP_ADDRESSMODE,L.wrapV=t.Constants.TEXTURE_CLAMP_ADDRESSMODE}const N=f.means.mins,k=f.means.maxs,D={version:2===f.version?2:1,splatCount:C,shDegree:B,meansTextureL:v,meansTextureU:x,scalesTexture:S,quatsTexture:O,sh0Texture:F,shCentroidsTexture:E,shLabelsTexture:I,codebookTexture:L,meansMin:[N[0],N[1],N[2]],meansMax:[k[0],k[1],k[2]],scalesMin:Array.isArray(f.scales.mins)?[f.scales.mins[0],f.scales.mins[1],f.scales.mins[2]]:void 0,scalesMax:Array.isArray(f.scales.maxs)?[f.scales.maxs[0],f.scales.maxs[1],f.scales.maxs[2]]:void 0,sh0Min:Array.isArray(f.sh0.mins)?[f.sh0.mins[0],f.sh0.mins[1],f.sh0.mins[2],f.sh0.mins[3]]:void 0,sh0Max:Array.isArray(f.sh0.maxs)?[f.sh0.maxs[0],f.sh0.maxs[1],f.sh0.maxs[2],f.sh0.maxs[3]]:void 0,shnMin:"number"==typeof(null===(h=f.shN)||void 0===h?void 0:h.mins)?f.shN.mins:void 0,shnMax:"number"==typeof(null===(m=f.shN)||void 0===m?void 0:m.maxs)?f.shN.maxs:void 0,shCoeffCount:P,positions:w?du(f,w[0].bits,w[1].bits,C):new Float32Array(0)};return{mode:0,data:new ArrayBuffer(0),hasVertexColors:!1,shDegree:B,sogTextures:D}})}const mu="precision highp float;\nattribute vec3 position;\nvoid main() {\n gl_Position = vec4(position.xy, 0.0, 1.0);\n}\n",fu="\nattribute position : vec3<f32>;\n@vertex\nfn main(input : VertexInputs) -> FragmentInputs {\n vertexOutputs.position = vec4<f32>(input.position.xy, 0.0, 1.0);\n}\n";class pu{get supportsAsyncCentersReadback(){var e;const t=this._scene.getEngine();if(t.isWebGPU)return!0;const n=t;return!!n._gl&&"function"==typeof n._readPixelsAsync&&(null!==(e=n.webGLVersion)&&void 0!==e?e: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,s,o){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?1:0,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)),s&&s.textureCount>0){if(s.externalMrts)this._shMrts=s.externalMrts.slice(0,s.textureCount),this._ownsShMrts=!1;else{for(let e=0;e<s.textureCount;e++)this._shMrts.push(this._createShMrt(`gsWorkBufferSh${e}`,!0));this._ownsShMrts=!0}this._shMaterial=this._createShMaterial()}o&&(o.externalMrt?(this._rotMrt=o.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&&this.isRelayoutReady()}backupRegion(){if(this._disposed||this._ownsMrt)return;if(!this.isRelayoutReady())return void t.Logger.Warn("GaussianSplattingWorkBuffer: backup skipped because the copy shaders are not ready; streamed region data may be lost on the atlas rebuild.");const e=this._textureSize,n=Math.max(1,Math.floor(this._capacity/e)),s=Math.floor(this._baseOffset/e);if(this._backupMrt||(this._backupMrt=this._createMrt("gsAtlasBackup",!1,e,n)),this._renderRelayoutPass(this._backupMrt,this._mrt.textures,this._mrt.textures[0],0,e,e,0,-s),this._shMrts.length&&this._shCopyMaterial){this._backupShMrts||(this._backupShMrts=this._shMrts.map((t,s)=>this._createShMrt(`gsShAtlasBackup${s}`,!1,e,n)));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,-s)}this._rotMrt&&this._rotCopyMaterial&&(this._backupRotMrt||(this._backupRotMrt=this._createRotMrt("gsRotAtlasBackup",!1,e,n)),this._renderRotCopyPass(this._backupRotMrt,this._rotMrt.textures,this._mrt.textures[0],0,e,e,0,-s)),this._quad.material=this._material}restoreRegion(){var e;if(this._disposed||this._ownsMrt||!this._backupMrt||!this._copyMaterial)return;const t=this._textureSize,n=Math.max(1,Math.floor(this._capacity/t)),s=Math.floor(this._baseOffset/t),o=this._scene.getEngine();o.enableScissor(0,s,t,n);try{if(this._renderRelayoutPass(this._mrt,this._backupMrt.textures,this._backupMrt.textures[0],0,t,t,0,s),this._backupShMrts&&this._shMrts.length&&this._shCopyMaterial)for(let e=0;e<this._shMrts.length&&e<this._backupShMrts.length;e++)this._renderShCopyPass(this._shMrts[e],this._backupShMrts[e].textures[0],this._mrt.textures[0],0,t,t,0,s);this._backupRotMrt&&this._rotMrt&&this._rotCopyMaterial&&this._renderRotCopyPass(this._rotMrt,this._backupRotMrt.textures,this._mrt.textures[0],0,t,t,0,s)}finally{o.disableScissor(),this._quad.material=this._material}if(this._backupMrt.dispose(),this._backupMrt=null,this._backupShMrts){for(const e of this._backupShMrts)e.dispose();this._backupShMrts=null}null===(e=this._backupRotMrt)||void 0===e||e.dispose(),this._backupRotMrt=null}_createMrt(e,n,s=this._textureSize,o=this._textureSize){const r=this._scene.getEngine()._caps.textureHalfFloatRender?t.Constants.TEXTURETYPE_HALF_FLOAT:t.Constants.TEXTURETYPE_FLOAT,i=new t.MultiRenderTarget(e,{width:s,height:o},4,this._scene,{types:[t.Constants.TEXTURETYPE_FLOAT,r,r,t.Constants.TEXTURETYPE_UNSIGNED_BYTE],samplingModes:[t.Constants.TEXTURE_NEAREST_SAMPLINGMODE,t.Constants.TEXTURE_NEAREST_SAMPLINGMODE,t.Constants.TEXTURE_NEAREST_SAMPLINGMODE,t.Constants.TEXTURE_NEAREST_SAMPLINGMODE],formats:[t.Constants.TEXTUREFORMAT_RGBA,t.Constants.TEXTUREFORMAT_RGBA,t.Constants.TEXTUREFORMAT_RGBA,t.Constants.TEXTUREFORMAT_RGBA],generateDepthBuffer:!1,generateDepthTexture:!1,generateMipMaps:!1},[`${e}Centers`,`${e}CovA`,`${e}CovB`,`${e}Colors`]);return i.clearColor=new t.Color4(0,0,0,0),i.renderList=[],n&&i.onClearObservable.add(()=>{}),i}_createShMrt(e,n,s=this._textureSize,o=this._textureSize){const r=new t.MultiRenderTarget(e,{width:s,height:o},1,this._scene,{types:[t.Constants.TEXTURETYPE_UNSIGNED_INTEGER],formats:[t.Constants.TEXTUREFORMAT_RGBA_INTEGER],samplingModes:[t.Constants.TEXTURE_NEAREST_SAMPLINGMODE],generateDepthBuffer:!1,generateDepthTexture:!1,generateMipMaps:!1},[e]);return r.clearColor=new t.Color4(0,0,0,0),r.renderList=[],n&&r.onClearObservable.add(()=>{}),r}_createRotMrt(e,n,s=this._textureSize,o=this._textureSize){const r=this._scene.getEngine()._caps.textureHalfFloatRender?t.Constants.TEXTURETYPE_HALF_FLOAT:t.Constants.TEXTURETYPE_FLOAT,i=new t.MultiRenderTarget(e,{width:s,height:o},3,this._scene,{types:[r,r,r],formats:[t.Constants.TEXTUREFORMAT_RGBA,t.Constants.TEXTUREFORMAT_RGBA,t.Constants.TEXTUREFORMAT_RGBA],samplingModes:[t.Constants.TEXTURE_NEAREST_SAMPLINGMODE,t.Constants.TEXTURE_NEAREST_SAMPLINGMODE,t.Constants.TEXTURE_NEAREST_SAMPLINGMODE],generateDepthBuffer:!1,generateDepthTexture:!1,generateMipMaps:!1},[`${e}A`,`${e}B`,`${e}Scale`]);return i.clearColor=new t.Color4(0,0,0,0),i.renderList=[],n&&i.onClearObservable.add(()=>{}),i}decodeAsync(e,t){return b(this,void 0,void 0,function*(){if(this._disposed)return;this._applyPack(e);const n=null!==this._shMaterial&&this._shMrts.length>0;n&&this._applyShPack(e);const s=null!==this._rotMaterial&&null!==this._rotMrt;s&&this._applyRotPack(e),yield new Promise(o=>{const r=()=>{if(this._disposed)return void o();if(!this._material.isReady(this._quad)||n&&!this._shMaterial.isReady(this._quad)||s&&!this._rotMaterial.isReady(this._quad))return void this._scene.onBeforeRenderObservable.addOnce(r);const i=this._textureSize,a=this._baseOffset+t;this._material.setInt("uOffset",a),n&&this._shMaterial.setInt("uOffset",a),s&&this._rotMaterial.setInt("uOffset",a);const l=Math.floor(a/i),u=Math.max(1,Math.ceil((a+e.splatCount)/i)-l),c=this._scene.getEngine();c.enableScissor(0,l,i,u);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}s&&(this._quad.material=this._rotMaterial,this._rotMrt.renderList=[this._quad],this._rotMrt.render(),this._quad.material=this._material)}finally{c.disableScissor()}o()};this._scene.onBeforeRenderObservable.addOnce(r)})})}isRelayoutReady(){if(this._disposed)return!1;this._copyMaterial||(this._copyMaterial=this._createCopyMaterial()),this._shMrts.length&&!this._shCopyMaterial&&(this._shCopyMaterial=this._createShCopyMaterial()),this._rotMrt&&!this._rotCopyMaterial&&(this._rotCopyMaterial=this._createRotCopyMaterial()),this._bindCopyMaterialsToAtlas();const e=0===this._shMrts.length||null!==this._shCopyMaterial&&this._shCopyMaterial.isReady(this._quad),t=!this._rotMrt||null!==this._rotCopyMaterial&&this._rotCopyMaterial.isReady(this._quad);return this._copyMaterial.isReady(this._quad)&&e&&t}_bindCopyMaterialsToAtlas(){const 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){const 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;const n=this._textureSize,s=n,o=this._ownsMrt?n:Math.max(1,Math.floor(this._capacity/n));this._relayoutMapData||(this._relayoutMapData=new Float32Array(s*o));const r=this._relayoutMapData;r.fill(-1),r.set(e.subarray(0,Math.min(e.length,r.length))),this._relayoutMapTexture?this._relayoutMapTexture.update(r):this._relayoutMapTexture=new t.RawTexture(r,s,o,t.Constants.TEXTUREFORMAT_R,this._scene,!1,!1,t.Constants.TEXTURE_NEAREST_SAMPLINGMODE,t.Constants.TEXTURETYPE_FLOAT);const i=this._relayoutMapTexture;if(this._ownsMrt){const e=this._createMrt("gsRelayoutTemp",!1);try{this._renderRelayoutPass(e,this._mrt.textures,i,1),this._renderRelayoutPass(this._mrt,e.textures,i,0)}finally{e.dispose()}if(this._shMrts.length&&this._shCopyMaterial)for(let e=0;e<this._shMrts.length;e++){const t=this._createShMrt("gsShRelayoutTemp",!1);try{this._renderShCopyPass(t,this._shMrts[e].textures[0],i,1),this._renderShCopyPass(this._shMrts[e],t.textures[0],i,0)}finally{t.dispose()}}if(this._rotMrt&&this._rotCopyMaterial){const e=this._createRotMrt("gsRotRelayoutTemp",!1);try{this._renderRotCopyPass(e,this._rotMrt.textures,i,1),this._renderRotCopyPass(this._rotMrt,e.textures,i,0)}finally{e.dispose()}}return void(this._quad.material=this._material)}const a=Math.floor(this._baseOffset/n),l=o,u=this._scene.getEngine(),c=this._createMrt("gsRelayoutTemp",!1,n,l),d=this._shMrts.length&&this._shCopyMaterial?this._shMrts.map((e,t)=>this._createShMrt(`gsShRelayoutTemp${t}`,!1,n,l)):[],h=this._rotMrt&&this._rotCopyMaterial?this._createRotMrt("gsRotRelayoutTemp",!1,n,l):null;try{this._renderRelayoutPass(c,this._mrt.textures,i,1,n,n,this._baseOffset,0);for(let e=0;e<d.length;e++)this._renderShCopyPass(d[e],this._shMrts[e].textures[0],i,1,n,n,this._baseOffset,0);h&&this._renderRotCopyPass(h,this._rotMrt.textures,i,1,n,n,this._baseOffset,0),u.enableScissor(0,a,n,l);try{this._renderRelayoutPass(this._mrt,c.textures,i,0,n,n,0,a);for(let e=0;e<d.length;e++)this._renderShCopyPass(this._shMrts[e],d[e].textures[0],i,0,n,n,0,a);h&&this._renderRotCopyPass(this._rotMrt,h.textures,i,0,n,n,0,a)}finally{u.disableScissor()}}finally{c.dispose();for(const e of d)e.dispose();null==h||h.dispose(),this._quad.material=this._material}}_renderRelayoutPass(e,t,n,s,o=this._textureSize,r=this._textureSize,i=0,a=0){const l=this._copyMaterial;l.setTexture("uMapTex",n),l.setTexture("uSrc0",t[0]),l.setTexture("uSrc1",t[1]),l.setTexture("uSrc2",t[2]),l.setTexture("uSrc3",t[3]),l.setInt("uDstWidth",o),l.setInt("uSrcWidth",r),l.setInt("uUseMap",s),l.setInt("uSrcBaseOffset",i),l.setInt("uDstBaseRow",a),this._quad.material=l,e.renderList=[this._quad],e.render()}_createCopyMaterial(){const e=1===this._shaderLanguage,n=new t.ShaderMaterial("gsWorkBufferRelayout",this._scene,{vertexSource:e?fu:mu,fragmentSource:e?"\nvar uMapTexSampler : sampler;\nvar uMapTex : texture_2d<f32>;\nvar uSrc0Sampler : sampler;\nvar uSrc0 : texture_2d<f32>;\nvar uSrc1Sampler : sampler;\nvar uSrc1 : texture_2d<f32>;\nvar uSrc2Sampler : sampler;\nvar uSrc2 : texture_2d<f32>;\nvar uSrc3Sampler : sampler;\nvar uSrc3 : texture_2d<f32>;\n\nuniform uDstWidth : i32;\nuniform uSrcWidth : i32;\nuniform uUseMap : i32;\n// Region-scoped relayout (hosted compound atlas), both default 0 (standalone square path unchanged).\nuniform uSrcBaseOffset : i32;\nuniform uDstBaseRow : i32;\n\n@fragment\nfn main(input : FragmentInputs) -> FragmentOutputs {\n let p : vec2<i32> = vec2<i32>(i32(fragmentInputs.position.x), i32(fragmentInputs.position.y));\n var srcIdx : i32;\n if (uniforms.uUseMap == 1) {\n let m : f32 = textureLoad(uMapTex, p, 0).r;\n if (m < 0.0) {\n discard;\n }\n srcIdx = uniforms.uSrcBaseOffset + i32(m + 0.5);\n } else {\n srcIdx = (p.y - uniforms.uDstBaseRow) * uniforms.uDstWidth + p.x;\n }\n let s : vec2<i32> = vec2<i32>(srcIdx - (srcIdx / uniforms.uSrcWidth) * uniforms.uSrcWidth, srcIdx / uniforms.uSrcWidth);\n fragmentOutputs.fragData0 = textureLoad(uSrc0, s, 0);\n fragmentOutputs.fragData1 = textureLoad(uSrc1, s, 0);\n fragmentOutputs.fragData2 = textureLoad(uSrc2, s, 0);\n fragmentOutputs.fragData3 = textureLoad(uSrc3, s, 0);\n}\n":"precision highp float;\nprecision highp int;\n\nuniform sampler2D uMapTex;\nuniform sampler2D uSrc0;\nuniform sampler2D uSrc1;\nuniform sampler2D uSrc2;\nuniform sampler2D uSrc3;\nuniform int uDstWidth;\nuniform int uSrcWidth;\nuniform int uUseMap;\n// Region-scoped relayout (hosted compound atlas), both default 0 (standalone square path unchanged):\n// uSrcBaseOffset — added to the map's (region-local) source index so pass 1 reads the correct GLOBAL atlas texel.\n// uDstBaseRow — subtracted from the atlas destination row so pass 2's identity copy reads the region-local temp.\nuniform int uSrcBaseOffset;\nuniform int uDstBaseRow;\n\nlayout(location = 0) out vec4 glFragData[4];\n\nvoid main() {\n ivec2 p = ivec2(gl_FragCoord.xy);\n int srcIdx;\n if (uUseMap == 1) {\n float m = texelFetch(uMapTex, p, 0).r;\n if (m < 0.0) {\n discard;\n }\n srcIdx = uSrcBaseOffset + int(m + 0.5);\n } else {\n srcIdx = (p.y - uDstBaseRow) * uDstWidth + p.x;\n }\n ivec2 s = ivec2(srcIdx - (srcIdx / uSrcWidth) * uSrcWidth, srcIdx / uSrcWidth);\n glFragData[0] = texelFetch(uSrc0, s, 0);\n glFragData[1] = texelFetch(uSrc1, s, 0);\n glFragData[2] = texelFetch(uSrc2, s, 0);\n glFragData[3] = texelFetch(uSrc3, s, 0);\n}\n"},{attributes:["position"],uniforms:["uDstWidth","uSrcWidth","uUseMap","uSrcBaseOffset","uDstBaseRow"],samplers:["uMapTex","uSrc0","uSrc1","uSrc2","uSrc3"],shaderLanguage:this._shaderLanguage});return n.backFaceCulling=!1,n.disableDepthWrite=!0,n}_renderShCopyPass(e,t,n,s,o=this._textureSize,r=this._textureSize,i=0,a=0){const l=this._shCopyMaterial;l.setTexture("uMapTex",n),l.setTexture("uSrcSh",t),l.setInt("uDstWidth",o),l.setInt("uSrcWidth",r),l.setInt("uUseMap",s),l.setInt("uSrcBaseOffset",i),l.setInt("uDstBaseRow",a),this._quad.material=l,e.renderList=[this._quad],e.render()}_createShCopyMaterial(){const e=1===this._shaderLanguage,n=new t.ShaderMaterial("gsWorkBufferShCopy",this._scene,{vertexSource:e?fu:mu,fragmentSource:e?'\nvar uMapTexSampler : sampler;\nvar uMapTex : texture_2d<f32>;\n// Integer source sampled via textureLoad only — NO paired sampler (a sampler on a Uint texture fails WebGPU\n// validation: "None of the supported sample types (Uint)"). Mirrors the draw shader\'s shTexture0 declaration.\nvar uSrcSh : texture_2d<u32>;\n\nuniform uDstWidth : i32;\nuniform uSrcWidth : i32;\nuniform uUseMap : i32;\nuniform uSrcBaseOffset : i32;\nuniform uDstBaseRow : i32;\n\n@fragment\nfn main(input : FragmentInputs) -> FragmentOutputs {\n let p : vec2<i32> = vec2<i32>(i32(fragmentInputs.position.x), i32(fragmentInputs.position.y));\n var srcIdx : i32;\n if (uniforms.uUseMap == 1) {\n let m : f32 = textureLoad(uMapTex, p, 0).r;\n if (m < 0.0) {\n discard;\n }\n srcIdx = uniforms.uSrcBaseOffset + i32(m + 0.5);\n } else {\n srcIdx = (p.y - uniforms.uDstBaseRow) * uniforms.uDstWidth + p.x;\n }\n let s : vec2<i32> = vec2<i32>(srcIdx - (srcIdx / uniforms.uSrcWidth) * uniforms.uSrcWidth, srcIdx / uniforms.uSrcWidth);\n // Wrap in an explicit vec4<u32> so the WGSL processor emits an integer fragData location (its detection keys\n // off a literal vec4<u32>/vec4u in the assignment; a bare textureLoad(...) would default to vec4<f32>).\n fragmentOutputs.fragData0 = vec4<u32>(textureLoad(uSrcSh, s, 0));\n}\n':"precision highp float;\nprecision highp int;\nprecision highp usampler2D;\n\nuniform sampler2D uMapTex;\nuniform usampler2D uSrcSh;\nuniform int uDstWidth;\nuniform int uSrcWidth;\nuniform int uUseMap;\nuniform int uSrcBaseOffset;\nuniform int uDstBaseRow;\n\nlayout(location = 0) out uvec4 outSh;\n\nvoid main() {\n ivec2 p = ivec2(gl_FragCoord.xy);\n int srcIdx;\n if (uUseMap == 1) {\n float m = texelFetch(uMapTex, p, 0).r;\n if (m < 0.0) {\n discard;\n }\n srcIdx = uSrcBaseOffset + int(m + 0.5);\n } else {\n srcIdx = (p.y - uDstBaseRow) * uDstWidth + p.x;\n }\n ivec2 s = ivec2(srcIdx - (srcIdx / uSrcWidth) * uSrcWidth, srcIdx / uSrcWidth);\n outSh = texelFetch(uSrcSh, s, 0);\n}\n"},{attributes:["position"],uniforms:["uDstWidth","uSrcWidth","uUseMap","uSrcBaseOffset","uDstBaseRow"],samplers:["uMapTex","uSrcSh"],shaderLanguage:this._shaderLanguage});return n.backFaceCulling=!1,n.disableDepthWrite=!0,n}_renderRotCopyPass(e,t,n,s,o=this._textureSize,r=this._textureSize,i=0,a=0){const l=this._rotCopyMaterial;l.setTexture("uMapTex",n),l.setTexture("uSrc0",t[0]),l.setTexture("uSrc1",t[1]),l.setTexture("uSrc2",t[2]),l.setInt("uDstWidth",o),l.setInt("uSrcWidth",r),l.setInt("uUseMap",s),l.setInt("uSrcBaseOffset",i),l.setInt("uDstBaseRow",a),this._quad.material=l,e.renderList=[this._quad],e.render()}_createRotCopyMaterial(){const e=1===this._shaderLanguage,n=new t.ShaderMaterial("gsWorkBufferRotCopy",this._scene,{vertexSource:e?fu:mu,fragmentSource:e?"\nvar uMapTexSampler : sampler;\nvar uMapTex : texture_2d<f32>;\nvar uSrc0Sampler : sampler;\nvar uSrc0 : texture_2d<f32>;\nvar uSrc1Sampler : sampler;\nvar uSrc1 : texture_2d<f32>;\nvar uSrc2Sampler : sampler;\nvar uSrc2 : texture_2d<f32>;\n\nuniform uDstWidth : i32;\nuniform uSrcWidth : i32;\nuniform uUseMap : i32;\nuniform uSrcBaseOffset : i32;\nuniform uDstBaseRow : i32;\n\n@fragment\nfn main(input : FragmentInputs) -> FragmentOutputs {\n let p : vec2<i32> = vec2<i32>(i32(fragmentInputs.position.x), i32(fragmentInputs.position.y));\n var srcIdx : i32;\n if (uniforms.uUseMap == 1) {\n let m : f32 = textureLoad(uMapTex, p, 0).r;\n if (m < 0.0) {\n discard;\n }\n srcIdx = uniforms.uSrcBaseOffset + i32(m + 0.5);\n } else {\n srcIdx = (p.y - uniforms.uDstBaseRow) * uniforms.uDstWidth + p.x;\n }\n let s : vec2<i32> = vec2<i32>(srcIdx - (srcIdx / uniforms.uSrcWidth) * uniforms.uSrcWidth, srcIdx / uniforms.uSrcWidth);\n fragmentOutputs.fragData0 = textureLoad(uSrc0, s, 0);\n fragmentOutputs.fragData1 = textureLoad(uSrc1, s, 0);\n fragmentOutputs.fragData2 = textureLoad(uSrc2, s, 0);\n}\n":"precision highp float;\nprecision highp int;\n\nuniform sampler2D uMapTex;\nuniform sampler2D uSrc0;\nuniform sampler2D uSrc1;\nuniform sampler2D uSrc2;\nuniform int uDstWidth;\nuniform int uSrcWidth;\nuniform int uUseMap;\nuniform int uSrcBaseOffset;\nuniform int uDstBaseRow;\n\nlayout(location = 0) out vec4 glFragData[3];\n\nvoid main() {\n ivec2 p = ivec2(gl_FragCoord.xy);\n int srcIdx;\n if (uUseMap == 1) {\n float m = texelFetch(uMapTex, p, 0).r;\n if (m < 0.0) {\n discard;\n }\n srcIdx = uSrcBaseOffset + int(m + 0.5);\n } else {\n srcIdx = (p.y - uDstBaseRow) * uDstWidth + p.x;\n }\n ivec2 s = ivec2(srcIdx - (srcIdx / uSrcWidth) * uSrcWidth, srcIdx / uSrcWidth);\n glFragData[0] = texelFetch(uSrc0, s, 0);\n glFragData[1] = texelFetch(uSrc1, s, 0);\n glFragData[2] = texelFetch(uSrc2, s, 0);\n}\n"},{attributes:["position"],uniforms:["uDstWidth","uSrcWidth","uUseMap","uSrcBaseOffset","uDstBaseRow"],samplers:["uMapTex","uSrc0","uSrc1","uSrc2"],shaderLanguage:this._shaderLanguage});return n.backFaceCulling=!1,n.disableDepthWrite=!0,n}readCentersRangeAsync(e,t){return b(this,void 0,void 0,function*(){var n,s;if(this._disposed||t<=0||!this.supportsAsyncCentersReadback)return null;const o=this._textureSize,r=this._baseOffset+e,i=Math.floor(r/o),a=Math.ceil((r+t)/o)-i,l=4*(r-i*o),u=l+4*t,c=this._mrt.textures[0],d=this._scene.getEngine();if(d.isWebGPU){const e=yield c.readPixels(0,0,null,!0,!0,0,i,o,a);if(this._disposed||!e)return null;const t=e instanceof Float32Array?e:new Float32Array(e.buffer,e.byteOffset,e.byteLength/4);return t.length>=u?t.subarray(l,u):null}const h=d,m=h._gl,f=null===(s=null===(n=c.getInternalTexture())||void 0===n?void 0:n._hardwareTexture)||void 0===s?void 0:s.underlyingResource;if(!f)return null;const p=new Float32Array(o*a*4);this._readFbo||(this._readFbo=m.createFramebuffer());const _=h._currentFramebuffer;m.bindFramebuffer(m.FRAMEBUFFER,this._readFbo),m.framebufferTexture2D(m.FRAMEBUFFER,m.COLOR_ATTACHMENT0,m.TEXTURE_2D,f,0),m.readBuffer(m.COLOR_ATTACHMENT0);const g=h._readPixelsAsync(0,i,o,a,m.RGBA,m.FLOAT,p);return m.bindFramebuffer(m.FRAMEBUFFER,_),_||m.readBuffer(m.BACK),g?(yield g,this._disposed||p.length<u?null:p.subarray(l,u)):null})}dispose(){var e,t,n,s,o,r,i,a,l,u;if(this._disposed=!0,this._readFbo&&(null===(e=this._scene.getEngine()._gl)||void 0===e||e.deleteFramebuffer(this._readFbo),this._readFbo=null),this._quad.dispose(),this._material.dispose(!0,!1),null===(t=this._shMaterial)||void 0===t||t.dispose(!0,!1),null===(n=this._rotMaterial)||void 0===n||n.dispose(!0,!1),null===(s=this._copyMaterial)||void 0===s||s.dispose(!0,!1),null===(o=this._shCopyMaterial)||void 0===o||o.dispose(!0,!1),null===(r=this._rotCopyMaterial)||void 0===r||r.dispose(!0,!1),null===(i=this._relayoutMapTexture)||void 0===i||i.dispose(),null===(a=this._backupMrt)||void 0===a||a.dispose(),this._backupMrt=null,this._backupShMrts){for(const e of this._backupShMrts)e.dispose();this._backupShMrts=null}if(null===(l=this._backupRotMrt)||void 0===l||l.dispose(),this._backupRotMrt=null,this._ownsMrt&&this._mrt.dispose(),this._ownsShMrts)for(const e of this._shMrts)e.dispose();this._shMrts=[],this._ownsRotMrt&&(null===(u=this._rotMrt)||void 0===u||u.dispose()),this._rotMrt=null}_createQuad(){const e=new t.Mesh("gsWorkBufferQuad",this._scene),n=new t.VertexData;return n.positions=[-1,-1,0,3,-1,0,-1,3,0],n.indices=[0,1,2],n.applyToMesh(e),this._scene.removeMesh(e),e}_createMaterial(){const e=1===this._shaderLanguage,n=new t.ShaderMaterial("gsSogDecode",this._scene,{vertexSource:e?fu:mu,fragmentSource:e?"\nvar sogMeansLTexSampler : sampler;\nvar sogMeansLTex : texture_2d<f32>;\nvar sogMeansUTexSampler : sampler;\nvar sogMeansUTex : texture_2d<f32>;\nvar sogScalesTexSampler : sampler;\nvar sogScalesTex : texture_2d<f32>;\nvar sogQuatsTexSampler : sampler;\nvar sogQuatsTex : texture_2d<f32>;\nvar sogSh0TexSampler : sampler;\nvar sogSh0Tex : texture_2d<f32>;\nvar sogCodebookTexSampler : sampler;\nvar sogCodebookTex : texture_2d<f32>;\n\nuniform sogMeansMin : vec3<f32>;\nuniform sogMeansMax : vec3<f32>;\nuniform sogScalesMin : vec3<f32>;\nuniform sogScalesMax : vec3<f32>;\nuniform sogSh0Min : vec4<f32>;\nuniform sogSh0Max : vec4<f32>;\nuniform uVersion : i32;\nuniform uOffset : i32;\nuniform uCount : i32;\nuniform uDestWidth : i32;\nuniform uSrcWidth : i32;\n\n@fragment\nfn main(input : FragmentInputs) -> FragmentOutputs {\n let p : vec2<i32> = vec2<i32>(i32(fragmentInputs.position.x), i32(fragmentInputs.position.y));\n let global : i32 = p.y * uniforms.uDestWidth + p.x;\n if (global < uniforms.uOffset || global >= uniforms.uOffset + uniforms.uCount) {\n discard;\n }\n let k : i32 = global - uniforms.uOffset;\n let src : vec2<i32> = vec2<i32>(k - (k / uniforms.uSrcWidth) * uniforms.uSrcWidth, k / uniforms.uSrcWidth);\n\n let mL : vec3<f32> = textureLoad(sogMeansLTex, src, 0).xyz;\n let mU : vec3<f32> = textureLoad(sogMeansUTex, src, 0).xyz;\n let sRaw : vec3<f32> = textureLoad(sogScalesTex, src, 0).xyz;\n let qRaw : vec4<f32> = textureLoad(sogQuatsTex, src, 0);\n let c0 : vec4<f32> = textureLoad(sogSh0Tex, src, 0);\n\n let q16 : vec3<f32> = (mU * 256.0 + mL) * (255.0 / 65535.0);\n let nPos : vec3<f32> = mix(uniforms.sogMeansMin, uniforms.sogMeansMax, q16);\n let center : vec3<f32> = sign(nPos) * (exp(abs(nPos)) - vec3<f32>(1.0));\n\n var splatScale : vec3<f32>;\n if (uniforms.uVersion == 2) {\n let sIdx : vec3<f32> = floor(sRaw * 255.0 + 0.5);\n splatScale.x = exp(textureLoad(sogCodebookTex, vec2<i32>(i32(sIdx.x), 0), 0).r);\n splatScale.y = exp(textureLoad(sogCodebookTex, vec2<i32>(i32(sIdx.y), 0), 0).r);\n splatScale.z = exp(textureLoad(sogCodebookTex, vec2<i32>(i32(sIdx.z), 0), 0).r);\n } else {\n splatScale = exp(mix(uniforms.sogScalesMin, uniforms.sogScalesMax, sRaw));\n }\n\n let invSqrt2 : f32 = 0.70710678118;\n let qabc : vec3<f32> = (qRaw.xyz - vec3<f32>(0.5)) * 2.0 * invSqrt2;\n let qMode : i32 = i32(qRaw.w * 255.0 + 0.5) - 252;\n let qd : f32 = sqrt(max(0.0, 1.0 - dot(qabc, qabc)));\n var quat : vec4<f32>;\n if (qMode == 0) {\n quat = vec4<f32>(qd, qabc.x, qabc.y, qabc.z);\n } else if (qMode == 1) {\n quat = vec4<f32>(qabc.x, qd, qabc.y, qabc.z);\n } else if (qMode == 2) {\n quat = vec4<f32>(qabc.x, qabc.y, qd, qabc.z);\n } else {\n quat = vec4<f32>(qabc.x, qabc.y, qabc.z, qd);\n }\n\n let qw : f32 = quat.x;\n let qx : f32 = quat.y;\n let qy : f32 = quat.z;\n let qz : f32 = quat.w;\n let R : mat3x3<f32> = mat3x3<f32>(\n 1.0 - 2.0 * (qy * qy + qz * qz), 2.0 * (qx * qy + qw * qz), 2.0 * (qx * qz - qw * qy),\n 2.0 * (qx * qy - qw * qz), 1.0 - 2.0 * (qx * qx + qz * qz), 2.0 * (qy * qz + qw * qx),\n 2.0 * (qx * qz + qw * qy), 2.0 * (qy * qz - qw * qx), 1.0 - 2.0 * (qx * qx + qy * qy)\n );\n let S2 : mat3x3<f32> = mat3x3<f32>(\n 4.0 * splatScale.x * splatScale.x, 0.0, 0.0,\n 0.0, 4.0 * splatScale.y * splatScale.y, 0.0,\n 0.0, 0.0, 4.0 * splatScale.z * splatScale.z\n );\n let Sigma : mat3x3<f32> = R * S2 * transpose(R);\n\n let SH_C0 : f32 = 0.28209479177387814;\n var colRgb : vec3<f32>;\n var colA : f32;\n if (uniforms.uVersion == 2) {\n var c3 : vec3<f32>;\n c3.x = textureLoad(sogCodebookTex, vec2<i32>(256 + i32(c0.x * 255.0 + 0.5), 0), 0).r;\n c3.y = textureLoad(sogCodebookTex, vec2<i32>(256 + i32(c0.y * 255.0 + 0.5), 0), 0).r;\n c3.z = textureLoad(sogCodebookTex, vec2<i32>(256 + i32(c0.z * 255.0 + 0.5), 0), 0).r;\n colRgb = vec3<f32>(0.5) + c3 * SH_C0;\n colA = c0.w;\n } else {\n let cLerp : vec4<f32> = mix(uniforms.sogSh0Min, uniforms.sogSh0Max, c0);\n colRgb = vec3<f32>(0.5) + cLerp.xyz * SH_C0;\n colA = 1.0 / (1.0 + exp(-cLerp.w));\n }\n\n fragmentOutputs.fragData0 = vec4<f32>(center, 1.0);\n fragmentOutputs.fragData1 = vec4<f32>(Sigma[0][0], Sigma[0][1], Sigma[0][2], Sigma[1][1]);\n fragmentOutputs.fragData2 = vec4<f32>(Sigma[1][2], Sigma[2][2], 0.0, 0.0);\n fragmentOutputs.fragData3 = vec4<f32>(colRgb, colA);\n}\n":"precision highp float;\nprecision highp int;\n\nuniform sampler2D sogMeansLTex;\nuniform sampler2D sogMeansUTex;\nuniform sampler2D sogScalesTex;\nuniform sampler2D sogQuatsTex;\nuniform sampler2D sogSh0Tex;\nuniform sampler2D sogCodebookTex;\n\nuniform vec3 sogMeansMin;\nuniform vec3 sogMeansMax;\nuniform vec3 sogScalesMin;\nuniform vec3 sogScalesMax;\nuniform vec4 sogSh0Min;\nuniform vec4 sogSh0Max;\nuniform int uVersion;\nuniform int uOffset;\nuniform int uCount;\nuniform int uDestWidth;\nuniform int uSrcWidth;\n\nlayout(location = 0) out vec4 glFragData[4];\n\nmat3 transposeM(mat3 m) {\n 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]);\n}\n\nvoid main() {\n ivec2 p = ivec2(gl_FragCoord.xy);\n int global = p.y * uDestWidth + p.x;\n if (global < uOffset || global >= uOffset + uCount) {\n discard;\n }\n int k = global - uOffset;\n ivec2 src = ivec2(k - (k / uSrcWidth) * uSrcWidth, k / uSrcWidth);\n\n vec3 mL = texelFetch(sogMeansLTex, src, 0).xyz;\n vec3 mU = texelFetch(sogMeansUTex, src, 0).xyz;\n vec3 sRaw = texelFetch(sogScalesTex, src, 0).xyz;\n vec4 qRaw = texelFetch(sogQuatsTex, src, 0);\n vec4 c0 = texelFetch(sogSh0Tex, src, 0);\n\n // Position: q16 = (u<<8)|l normalized; n = lerp(min,max,q16); pos = sign(n)*(exp(|n|)-1)\n vec3 q16 = (mU * 256.0 + mL) * (255.0 / 65535.0);\n vec3 nPos = mix(sogMeansMin, sogMeansMax, q16);\n vec3 center = sign(nPos) * (exp(abs(nPos)) - vec3(1.0));\n\n // Scale (v1: lerp+exp ; v2: codebook lookup)\n vec3 splatScale;\n if (uVersion == 2) {\n vec3 sIdx = floor(sRaw * 255.0 + 0.5);\n splatScale.x = exp(texelFetch(sogCodebookTex, ivec2(int(sIdx.x), 0), 0).r);\n splatScale.y = exp(texelFetch(sogCodebookTex, ivec2(int(sIdx.y), 0), 0).r);\n splatScale.z = exp(texelFetch(sogCodebookTex, ivec2(int(sIdx.z), 0), 0).r);\n } else {\n splatScale = exp(mix(sogScalesMin, sogScalesMax, sRaw));\n }\n\n // Quaternion (largest-omitted, mode in alpha as 252 + omitted-index)\n const float invSqrt2 = 0.70710678118;\n vec3 qabc = (qRaw.xyz - vec3(0.5)) * 2.0 * invSqrt2;\n int qMode = int(qRaw.w * 255.0 + 0.5) - 252;\n float qd = sqrt(max(0.0, 1.0 - dot(qabc, qabc)));\n vec4 quat;\n if (qMode == 0) {\n quat = vec4(qd, qabc.x, qabc.y, qabc.z);\n } else if (qMode == 1) {\n quat = vec4(qabc.x, qd, qabc.y, qabc.z);\n } else if (qMode == 2) {\n quat = vec4(qabc.x, qabc.y, qd, qabc.z);\n } else {\n quat = vec4(qabc.x, qabc.y, qabc.z, qd);\n }\n\n float qw = quat.x, qx = quat.y, qy = quat.z, qz = quat.w;\n mat3 R = mat3(\n 1.0 - 2.0 * (qy * qy + qz * qz), 2.0 * (qx * qy + qw * qz), 2.0 * (qx * qz - qw * qy),\n 2.0 * (qx * qy - qw * qz), 1.0 - 2.0 * (qx * qx + qz * qz), 2.0 * (qy * qz + qw * qx),\n 2.0 * (qx * qz + qw * qy), 2.0 * (qy * qz - qw * qx), 1.0 - 2.0 * (qx * qx + qy * qy)\n );\n mat3 S2 = mat3(\n 4.0 * splatScale.x * splatScale.x, 0.0, 0.0,\n 0.0, 4.0 * splatScale.y * splatScale.y, 0.0,\n 0.0, 0.0, 4.0 * splatScale.z * splatScale.z\n );\n mat3 Sigma = R * S2 * transposeM(R);\n\n // Color (sh0)\n const float SH_C0 = 0.28209479177387814;\n vec3 colRgb;\n float colA;\n if (uVersion == 2) {\n vec3 c3;\n c3.x = texelFetch(sogCodebookTex, ivec2(256 + int(c0.x * 255.0 + 0.5), 0), 0).r;\n c3.y = texelFetch(sogCodebookTex, ivec2(256 + int(c0.y * 255.0 + 0.5), 0), 0).r;\n c3.z = texelFetch(sogCodebookTex, ivec2(256 + int(c0.z * 255.0 + 0.5), 0), 0).r;\n colRgb = vec3(0.5) + c3 * SH_C0;\n colA = c0.w;\n } else {\n vec4 cLerp = mix(sogSh0Min, sogSh0Max, c0);\n colRgb = vec3(0.5) + cLerp.xyz * SH_C0;\n colA = 1.0 / (1.0 + exp(-cLerp.w));\n }\n\n glFragData[0] = vec4(center, 1.0);\n glFragData[1] = vec4(Sigma[0][0], Sigma[0][1], Sigma[0][2], Sigma[1][1]);\n glFragData[2] = vec4(Sigma[1][2], Sigma[2][2], 0.0, 0.0);\n glFragData[3] = vec4(colRgb, colA);\n}\n"},{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 n.backFaceCulling=!1,n.disableDepthWrite=!0,n}_applyPack(e){var n,s,o,r,i;const a=this._material,l=e.meansTextureL.getSize().width;a.setTexture("sogMeansLTex",e.meansTextureL),a.setTexture("sogMeansUTex",e.meansTextureU),a.setTexture("sogScalesTex",e.scalesTexture),a.setTexture("sogQuatsTex",e.quatsTexture),a.setTexture("sogSh0Tex",e.sh0Texture),a.setTexture("sogCodebookTex",null!==(n=e.codebookTexture)&&void 0!==n?n:e.sh0Texture),a.setVector3("sogMeansMin",new t.Vector3(e.meansMin[0],e.meansMin[1],e.meansMin[2])),a.setVector3("sogMeansMax",new t.Vector3(e.meansMax[0],e.meansMax[1],e.meansMax[2]));const u=null!==(s=e.scalesMin)&&void 0!==s?s:[0,0,0],c=null!==(o=e.scalesMax)&&void 0!==o?o:[0,0,0];a.setVector3("sogScalesMin",new t.Vector3(u[0],u[1],u[2])),a.setVector3("sogScalesMax",new t.Vector3(c[0],c[1],c[2]));const d=null!==(r=e.sh0Min)&&void 0!==r?r:[0,0,0,0],h=null!==(i=e.sh0Max)&&void 0!==i?i:[0,0,0,0];a.setVector4("sogSh0Min",new t.Vector4(d[0],d[1],d[2],d[3])),a.setVector4("sogSh0Max",new t.Vector4(h[0],h[1],h[2],h[3])),a.setInt("uVersion",e.version),a.setInt("uCount",e.splatCount),a.setInt("uDestWidth",this._textureSize),a.setInt("uSrcWidth",l)}_createShMaterial(){const e=1===this._shaderLanguage,n=new t.ShaderMaterial("gsSogShDecodeToWorkBuffer",this._scene,{vertexSource:e?fu:mu,fragmentSource:e?"\nvar sogShLabelsTexSampler : sampler;\nvar sogShLabelsTex : texture_2d<f32>;\nvar sogShCentroidsTexSampler : sampler;\nvar sogShCentroidsTex : texture_2d<f32>;\nvar sogCodebookTexSampler : sampler;\nvar sogCodebookTex : texture_2d<f32>;\n\nuniform sogShnMin : f32;\nuniform sogShnMax : f32;\nuniform uVersion : i32;\nuniform uOffset : i32;\nuniform uCount : i32;\nuniform uDestWidth : i32;\nuniform uSrcWidth : i32;\nuniform uCoeffs : i32;\nuniform uShTextureIndex : i32;\n\n@fragment\nfn main(input : FragmentInputs) -> FragmentOutputs {\n let p : vec2<i32> = vec2<i32>(i32(fragmentInputs.position.x), i32(fragmentInputs.position.y));\n let global : i32 = p.y * uniforms.uDestWidth + p.x;\n if (global < uniforms.uOffset || global >= uniforms.uOffset + uniforms.uCount) {\n discard;\n }\n let kLocal : i32 = global - uniforms.uOffset;\n\n let lsz : vec2<i32> = vec2<i32>(textureDimensions(sogShLabelsTex, 0));\n let lsrc : vec2<i32> = vec2<i32>(kLocal - (kLocal / lsz.x) * lsz.x, kLocal / lsz.x);\n let labelRaw : vec4<f32> = textureLoad(sogShLabelsTex, lsrc, 0);\n let n : i32 = i32(labelRaw.r * 255.0 + 0.5) + i32(labelRaw.g * 255.0 + 0.5) * 256;\n let u : i32 = (n - (n / 64) * 64) * uniforms.uCoeffs;\n let v : i32 = n / 64;\n\n var packed : array<u32, 4> = array<u32, 4>(0u, 0u, 0u, 0u);\n\n for (var b : i32 = 0; b < 16; b = b + 1) {\n let s : i32 = uniforms.uShTextureIndex * 16 + b;\n let kc : i32 = s / 3;\n let j : i32 = s - kc * 3;\n var byteVal : f32 = 128.0;\n if (kc < uniforms.uCoeffs) {\n let centroidRaw : vec4<f32> = textureLoad(sogShCentroidsTex, vec2<i32>(u + kc, v), 0);\n var ch : f32 = centroidRaw.b;\n if (j == 0) { ch = centroidRaw.r; } else if (j == 1) { ch = centroidRaw.g; }\n var coeff : f32;\n if (uniforms.uVersion == 2) {\n let cidx : i32 = i32(ch * 255.0 + 0.5);\n coeff = textureLoad(sogCodebookTex, vec2<i32>(512 + cidx, 0), 0).r;\n } else {\n coeff = mix(uniforms.sogShnMin, uniforms.sogShnMax, ch);\n }\n byteVal = clamp(coeff * 127.5 + 127.5, 0.0, 255.0);\n }\n let bv : u32 = u32(byteVal + 0.5);\n let comp : i32 = b / 4;\n packed[comp] = packed[comp] | (bv << u32((b - comp * 4) * 8));\n }\n fragmentOutputs.fragData0 = vec4<u32>(packed[0], packed[1], packed[2], packed[3]);\n}\n":"precision highp float;\nprecision highp int;\n\nuniform sampler2D sogShLabelsTex;\nuniform sampler2D sogShCentroidsTex;\nuniform sampler2D sogCodebookTex;\nuniform float sogShnMin;\nuniform float sogShnMax;\nuniform int uVersion;\nuniform int uOffset;\nuniform int uCount;\nuniform int uDestWidth;\nuniform int uSrcWidth;\nuniform int uCoeffs;\nuniform int uShTextureIndex;\n\nlayout(location = 0) out uvec4 outSh;\n\nvoid main() {\n ivec2 p = ivec2(gl_FragCoord.xy);\n int global = p.y * uDestWidth + p.x;\n if (global < uOffset || global >= uOffset + uCount) {\n discard;\n }\n int kLocal = global - uOffset;\n\n // 16-bit label for this source splat (LSB in r, MSB in g), indexed over the labels texture's own width.\n ivec2 lsz = textureSize(sogShLabelsTex, 0);\n ivec2 lsrc = ivec2(kLocal - (kLocal / lsz.x) * lsz.x, kLocal / lsz.x);\n vec4 labelRaw = texelFetch(sogShLabelsTex, lsrc, 0);\n int n = int(labelRaw.r * 255.0 + 0.5) + int(labelRaw.g * 255.0 + 0.5) * 256;\n int u = (n - (n / 64) * 64) * uCoeffs;\n int v = n / 64;\n\n uint packed0 = 0u;\n uint packed1 = 0u;\n uint packed2 = 0u;\n uint packed3 = 0u;\n\n for (int b = 0; b < 16; b++) {\n int s = uShTextureIndex * 16 + b; // flat SH scalar index\n int kc = s / 3; // higher-order coefficient (0-based)\n int j = s - kc * 3; // channel (0=r,1=g,2=b)\n float byteVal = 128.0; // neutral (decompose(128) ~= 0)\n if (kc < uCoeffs) {\n vec4 centroidRaw = texelFetch(sogShCentroidsTex, ivec2(u + kc, v), 0);\n float ch = (j == 0) ? centroidRaw.r : ((j == 1) ? centroidRaw.g : centroidRaw.b);\n float coeff;\n if (uVersion == 2) {\n int cidx = int(ch * 255.0 + 0.5);\n coeff = texelFetch(sogCodebookTex, ivec2(512 + cidx, 0), 0).r;\n } else {\n coeff = mix(sogShnMin, sogShnMax, ch);\n }\n byteVal = clamp(coeff * 127.5 + 127.5, 0.0, 255.0);\n }\n uint bv = uint(byteVal + 0.5);\n int comp = b / 4;\n uint contrib = bv << uint((b - comp * 4) * 8);\n if (comp == 0) { packed0 |= contrib; }\n else if (comp == 1) { packed1 |= contrib; }\n else if (comp == 2) { packed2 |= contrib; }\n else { packed3 |= contrib; }\n }\n outSh = uvec4(packed0, packed1, packed2, packed3);\n}\n"},{attributes:["position"],uniforms:["sogShnMin","sogShnMax","uVersion","uOffset","uCount","uDestWidth","uSrcWidth","uCoeffs","uShTextureIndex"],samplers:["sogShLabelsTex","sogShCentroidsTex","sogCodebookTex"],shaderLanguage:this._shaderLanguage});return n.backFaceCulling=!1,n.disableDepthWrite=!0,n}_applyShPack(e){var t,n,s,o,r;const i=this._shMaterial,a=!!e.shLabelsTexture&&!!e.shCentroidsTexture,l=null!==(t=e.shLabelsTexture)&&void 0!==t?t:e.sh0Texture,u=null!==(n=e.shCentroidsTexture)&&void 0!==n?n:e.sh0Texture;i.setTexture("sogShLabelsTex",l),i.setTexture("sogShCentroidsTex",u),i.setTexture("sogCodebookTex",null!==(s=e.codebookTexture)&&void 0!==s?s:l),i.setFloat("sogShnMin",null!==(o=e.shnMin)&&void 0!==o?o:0),i.setFloat("sogShnMax",null!==(r=e.shnMax)&&void 0!==r?r:0),i.setInt("uVersion",e.version),i.setInt("uCount",e.splatCount),i.setInt("uDestWidth",this._textureSize),i.setInt("uSrcWidth",l.getSize().width),i.setInt("uCoeffs",a?e.shCoeffCount:0)}_createRotMaterial(){const e=1===this._shaderLanguage,n=new t.ShaderMaterial("gsSogRotDecodeToWorkBuffer",this._scene,{vertexSource:e?fu:mu,fragmentSource:e?"\nvar sogScalesTexSampler : sampler;\nvar sogScalesTex : texture_2d<f32>;\nvar sogQuatsTexSampler : sampler;\nvar sogQuatsTex : texture_2d<f32>;\nvar sogCodebookTexSampler : sampler;\nvar sogCodebookTex : texture_2d<f32>;\n\nuniform sogScalesMin : vec3<f32>;\nuniform sogScalesMax : vec3<f32>;\nuniform uVersion : i32;\nuniform uOffset : i32;\nuniform uCount : i32;\nuniform uDestWidth : i32;\nuniform uSrcWidth : i32;\n\n@fragment\nfn main(input : FragmentInputs) -> FragmentOutputs {\n let p : vec2<i32> = vec2<i32>(i32(fragmentInputs.position.x), i32(fragmentInputs.position.y));\n let global : i32 = p.y * uniforms.uDestWidth + p.x;\n if (global < uniforms.uOffset || global >= uniforms.uOffset + uniforms.uCount) {\n discard;\n }\n let k : i32 = global - uniforms.uOffset;\n let src : vec2<i32> = vec2<i32>(k - (k / uniforms.uSrcWidth) * uniforms.uSrcWidth, k / uniforms.uSrcWidth);\n\n let sRaw : vec3<f32> = textureLoad(sogScalesTex, src, 0).xyz;\n let qRaw : vec4<f32> = textureLoad(sogQuatsTex, src, 0);\n\n var splatScale : vec3<f32>;\n if (uniforms.uVersion == 2) {\n let sIdx : vec3<f32> = floor(sRaw * 255.0 + 0.5);\n splatScale.x = exp(textureLoad(sogCodebookTex, vec2<i32>(i32(sIdx.x), 0), 0).r);\n splatScale.y = exp(textureLoad(sogCodebookTex, vec2<i32>(i32(sIdx.y), 0), 0).r);\n splatScale.z = exp(textureLoad(sogCodebookTex, vec2<i32>(i32(sIdx.z), 0), 0).r);\n } else {\n splatScale = exp(mix(uniforms.sogScalesMin, uniforms.sogScalesMax, sRaw));\n }\n\n let invSqrt2 : f32 = 0.70710678118;\n let qabc : vec3<f32> = (qRaw.xyz - vec3<f32>(0.5)) * 2.0 * invSqrt2;\n let qMode : i32 = i32(qRaw.w * 255.0 + 0.5) - 252;\n let qd : f32 = sqrt(max(0.0, 1.0 - dot(qabc, qabc)));\n var quat : vec4<f32>;\n if (qMode == 0) {\n quat = vec4<f32>(qd, qabc.x, qabc.y, qabc.z);\n } else if (qMode == 1) {\n quat = vec4<f32>(qabc.x, qd, qabc.y, qabc.z);\n } else if (qMode == 2) {\n quat = vec4<f32>(qabc.x, qabc.y, qd, qabc.z);\n } else {\n quat = vec4<f32>(qabc.x, qabc.y, qabc.z, qd);\n }\n\n let qw : f32 = quat.x;\n let qx : f32 = quat.y;\n let qy : f32 = quat.z;\n let qz : f32 = quat.w;\n let R : mat3x3<f32> = mat3x3<f32>(\n 1.0 - 2.0 * (qy * qy + qz * qz), 2.0 * (qx * qy + qw * qz), 2.0 * (qx * qz - qw * qy),\n 2.0 * (qx * qy - qw * qz), 1.0 - 2.0 * (qx * qx + qz * qz), 2.0 * (qy * qz + qw * qx),\n 2.0 * (qx * qz + qw * qy), 2.0 * (qy * qz - qw * qx), 1.0 - 2.0 * (qx * qx + qy * qy)\n );\n\n fragmentOutputs.fragData0 = vec4<f32>(R[0], R[1].x);\n fragmentOutputs.fragData1 = vec4<f32>(R[1].y, R[1].z, R[2].x, R[2].y);\n fragmentOutputs.fragData2 = vec4<f32>(R[2].z, 2.0 * splatScale.x, 2.0 * splatScale.y, 2.0 * splatScale.z);\n}\n":"precision highp float;\nprecision highp int;\n\nuniform sampler2D sogScalesTex;\nuniform sampler2D sogQuatsTex;\nuniform sampler2D sogCodebookTex;\n\nuniform vec3 sogScalesMin;\nuniform vec3 sogScalesMax;\nuniform int uVersion;\nuniform int uOffset;\nuniform int uCount;\nuniform int uDestWidth;\nuniform int uSrcWidth;\n\nlayout(location = 0) out vec4 glFragData[3];\n\nvoid main() {\n ivec2 p = ivec2(gl_FragCoord.xy);\n int global = p.y * uDestWidth + p.x;\n if (global < uOffset || global >= uOffset + uCount) {\n discard;\n }\n int k = global - uOffset;\n ivec2 src = ivec2(k - (k / uSrcWidth) * uSrcWidth, k / uSrcWidth);\n\n vec3 sRaw = texelFetch(sogScalesTex, src, 0).xyz;\n vec4 qRaw = texelFetch(sogQuatsTex, src, 0);\n\n vec3 splatScale;\n if (uVersion == 2) {\n vec3 sIdx = floor(sRaw * 255.0 + 0.5);\n splatScale.x = exp(texelFetch(sogCodebookTex, ivec2(int(sIdx.x), 0), 0).r);\n splatScale.y = exp(texelFetch(sogCodebookTex, ivec2(int(sIdx.y), 0), 0).r);\n splatScale.z = exp(texelFetch(sogCodebookTex, ivec2(int(sIdx.z), 0), 0).r);\n } else {\n splatScale = exp(mix(sogScalesMin, sogScalesMax, sRaw));\n }\n\n const float invSqrt2 = 0.70710678118;\n vec3 qabc = (qRaw.xyz - vec3(0.5)) * 2.0 * invSqrt2;\n int qMode = int(qRaw.w * 255.0 + 0.5) - 252;\n float qd = sqrt(max(0.0, 1.0 - dot(qabc, qabc)));\n vec4 quat;\n if (qMode == 0) {\n quat = vec4(qd, qabc.x, qabc.y, qabc.z);\n } else if (qMode == 1) {\n quat = vec4(qabc.x, qd, qabc.y, qabc.z);\n } else if (qMode == 2) {\n quat = vec4(qabc.x, qabc.y, qd, qabc.z);\n } else {\n quat = vec4(qabc.x, qabc.y, qabc.z, qd);\n }\n\n float qw = quat.x, qx = quat.y, qy = quat.z, qz = quat.w;\n mat3 R = mat3(\n 1.0 - 2.0 * (qy * qy + qz * qz), 2.0 * (qx * qy + qw * qz), 2.0 * (qx * qz - qw * qy),\n 2.0 * (qx * qy - qw * qz), 1.0 - 2.0 * (qx * qx + qz * qz), 2.0 * (qy * qz + qw * qx),\n 2.0 * (qx * qz + qw * qy), 2.0 * (qy * qz - qw * qx), 1.0 - 2.0 * (qx * qx + qy * qy)\n );\n\n glFragData[0] = vec4(R[0], R[1].x);\n glFragData[1] = vec4(R[1].y, R[1].z, R[2].x, R[2].y);\n glFragData[2] = vec4(R[2].z, 2.0 * splatScale.x, 2.0 * splatScale.y, 2.0 * splatScale.z);\n}\n"},{attributes:["position"],uniforms:["sogScalesMin","sogScalesMax","uVersion","uOffset","uCount","uDestWidth","uSrcWidth"],samplers:["sogScalesTex","sogQuatsTex","sogCodebookTex"],shaderLanguage:this._shaderLanguage});return n.backFaceCulling=!1,n.disableDepthWrite=!0,n}_applyRotPack(e){var n,s,o;const r=this._rotMaterial,i=e.scalesTexture.getSize().width;r.setTexture("sogScalesTex",e.scalesTexture),r.setTexture("sogQuatsTex",e.quatsTexture),r.setTexture("sogCodebookTex",null!==(n=e.codebookTexture)&&void 0!==n?n:e.scalesTexture);const a=null!==(s=e.scalesMin)&&void 0!==s?s:[0,0,0],l=null!==(o=e.scalesMax)&&void 0!==o?o:[0,0,0];r.setVector3("sogScalesMin",new t.Vector3(a[0],a[1],a[2])),r.setVector3("sogScalesMax",new t.Vector3(l[0],l[1],l[2])),r.setInt("uVersion",e.version),r.setInt("uCount",e.splatCount),r.setInt("uDestWidth",this._textureSize),r.setInt("uSrcWidth",i)}}class _u{constructor(e){var t,n;this._activeCount=0,this._queue=[],this._pending=new Map,this._groups=new Map,this._disposed=!1,this.maxConcurrent=Math.max(1,null!==(t=null==e?void 0:e.maxConcurrent)&&void 0!==t?t:2),this.maxRetries=Math.max(0,null!==(n=null==e?void 0:e.maxRetries)&&void 0!==n?n:2)}get isIdle(){return 0===this._pending.size}loadFileAsync(e,t){return b(this,void 0,void 0,function*(){if(this._disposed)throw new Error("GaussianSplattingDownloadManager has been disposed.");const n=this._pending.get(e);if(n)return yield n.promise;const s={url:e,groupId:t,settled:!1,cancelled:!1,started:!1,slotReleased:!1};if(s.promise=new Promise((e,t)=>{s.resolve=e,s.reject=t}),this._pending.set(e,s),void 0!==t){let n=this._groups.get(t);n||(n=new Set,this._groups.set(t,n)),n.add(e)}return this._queue.push(s),this._pump(),yield s.promise})}cancel(e){const t=this._pending.get(e);t&&this._abort(t,new Error(`GaussianSplattingDownloadManager: download cancelled (${e}).`))}cancelGroup(e){const t=this._groups.get(e);if(t){for(const e of Array.from(t))this.cancel(e);this._groups.delete(e)}}dispose(){if(!this._disposed){this._disposed=!0,this._queue.length=0;for(const e of Array.from(this._pending.values()))this._abort(e,new Error("GaussianSplattingDownloadManager has been disposed."))}}_abort(e,t){var n,s;if(e.settled)return;e.cancelled=!0;const o=this._queue.indexOf(e);-1!==o&&this._queue.splice(o,1),null===(n=e.request)||void 0===n||n.abort(),null===(s=e.cancelAttempt)||void 0===s||s.call(e,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),void 0!==e.groupId){const t=this._groups.get(e.groupId);t&&(t.delete(e.url),0===t.size&&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;){const e=this._queue.shift();e.settled||(e.started=!0,this._activeCount++,this._runTaskAsync(e).finally(()=>{this._releaseSlot(e)}))}}_runTaskAsync(e){return b(this,void 0,void 0,function*(){let t;for(let n=0;n<=this.maxRetries;n++){if(this._disposed||e.cancelled)return;try{const t=yield this._downloadAttemptAsync(e);return void this._settle(e,()=>e.resolve(t))}catch(n){if(e.cancelAttempt=void 0,this._disposed||e.cancelled)return;t=n}}this._settle(e,()=>e.reject(t))})}_downloadAttemptAsync(e){return b(this,void 0,void 0,function*(){return yield new Promise((n,s)=>{e.cancelAttempt=s,e.request=t.Tools.LoadFile(e.url,e=>n(e),void 0,void 0,!0,(t,n)=>s(n instanceof Error?n:new Error(`GaussianSplattingDownloadManager: failed to load ${e.url}.`)))})})}}class gu{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}}class yu{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;const 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;const 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;const 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;const t=e._prev,n=e._next,s=t&&t._free,o=n&&n._free;s&&o?(t._size+=e._size+n._size,this._removeFromMainList(e),this._removeFromMainList(n),this._removeFromBucket(n),this._release(e),this._release(n),this._rebucket(t)):s?(t._size+=e._size,this._removeFromMainList(e),this._release(e),this._rebucket(t)):o?(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;const 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{const 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(),0===this._freeRegionCount||(0===e?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++){const n=t[e],s=this.allocate(n);if(!s){let s=n;for(let n=e+1;n<t.length;n++)s+=t[n];const o=this._usedSize+s,r=Math.ceil(o*this._growMultiplier);r>this._capacity&&this.grow(r),this.defrag(0);for(let n=e;n<t.length;n++)t[n]=this.allocate(t[n]);return!0}t[e]=s}return!1}_bucketFor(e){return 31-Math.clz32(e)}_addToBucket(e){const 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){const 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){const s=this._pool.length>0?this._pool.pop():new gu;return s._offset=e,s._size=t,s._free=n,s._prev=null,s._next=null,s._prevFree=null,s._nextFree=null,s._bucket=-1,s}_release(e){e._prev=null,e._next=null,e._prevFree=null,e._nextFree=null,e._bucket=-1,this._pool.push(e)}_insertAfterInMainList(e,t){null===t?(e._prev=null,e._next=this._headAll,this._headAll&&(this._headAll._prev=e),this._headAll=e,this._tailAll||(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){const t=this._bucketFor(e),n=this._freeBucketHeads.length;if(t<n){let n=null,s=this._freeBucketHeads[t];for(;s&&!(s._size>=e&&(!n||s._size<n._size)&&(n=s,s._size===e));)s=s._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;){const 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;const s=this._capacity-t;if(s>0){const e=this._obtain(t,s,!0);this._insertAfterInMainList(e,this._tailAll),this._addToBucket(e)}}_defragIncremental(e,t){const n=Math.ceil(e/2),s=e-n;for(let e=0;e<n;e++){let e=this._tailAll;for(;e&&e._free;)e=e._prev;if(!e)break;const n=this._findFreeBlock(e._size);if(!n||n._offset>=e._offset)break;this._moveBlock(e,n),t.add(e)}let o=this._headAll;for(let e=0;e<s&&o;){const n=o._next;if(o._free&&n&&!n._free){const s=n,r=o;s._offset=r._offset,r._offset=s._offset+s._size;const i=r._prev,a=s._next;if(s._prev=i,s._next=r,r._prev=s,r._next=a,i?i._next=s:this._headAll=s,a?a._prev=r:this._tailAll=r,r._next&&r._next._free){const e=r._next;r._size+=e._size,this._removeFromMainList(e),this._removeFromBucket(e),this._release(e),this._rebucket(r)}t.add(s),e++,o=r._next}else o=n}}_moveBlock(e,t){const n=e._size,s=t._offset,o=e._prev;this._removeFromMainList(e);const r=this._obtain(e._offset,n,!0);if(this._insertAfterInMainList(r,o),this._addToBucket(r),r._next&&r._next._free){const e=r._next;r._size+=e._size,this._removeFromMainList(e),this._removeFromBucket(e),this._release(e),this._rebucket(r)}if(r._prev&&r._prev._free){const e=r._prev;e._size+=r._size,this._removeFromMainList(r),this._removeFromBucket(r),this._release(r),this._rebucket(e)}if(e._offset=s,t._size===n){const 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)}}class vu{constructor(e,t,n){this._blocks=new Map,this._cooldown=new Map,this._pinned=new Set,this._allocator=new yu(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){var t;return null===(t=this._blocks.get(e))||void 0===t?void 0:t.offset}allocate(e,t){const n=this._blocks.get(e);if(n)return n.offset;let s=this._allocator.allocate(t);return s||(this._evictAllCooled(),s=this._allocator.allocate(t),s)?(this._blocks.set(e,s),s.offset):null}pin(e,t){const n=this.allocate(e,t);return null!==n&&this._pinned.add(e),n}free(e){if(this._pinned.has(e))return;const t=this._blocks.get(e);t&&(this._allocator.free(t),this._blocks.delete(e),this._cooldown.delete(e))}compact(){const e=new Map;for(const[t,n]of Array.from(this._blocks))e.set(t,n.offset);this._allocator.defrag(0);const t=[];for(const[n,s]of Array.from(this._blocks)){const o=e.get(n);o!==s.offset&&t.push({file:n,oldOffset:o,newOffset:s.offset,count:s.size})}return t}getResidentBlocks(){const e=[];for(const[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(0===this._cooldown.size)return[];const e=[];for(const[t,n]of Array.from(this._cooldown))n<=1?e.push(t):this._cooldown.set(t,n-1);for(const t of e)this._evict(t);return e}dispose(){this._blocks.clear(),this._cooldown.clear(),this._pinned.clear()}_evictAllCooled(){const e=Array.from(this._cooldown.keys());for(const t of e)this._evict(t)}_evict(e){const t=this._blocks.get(e);t&&(this._allocator.free(t),this._blocks.delete(e)),this._cooldown.delete(e),this._onEvict(e)}}const bu=Math.tan(22.5*Math.PI/180),xu=new t.Matrix,Tu=new t.Vector3,Au=new t.Vector3,Mu=new t.Vector3,wu=new t.Vector3(0,0,1),Cu=[[0,1],[1,2],[2,3],[3,0],[4,5],[5,6],[6,7],[7,4],[0,4],[1,5],[2,6],[3,7]],Ru=2*Cu.length,Su=[new t.Color4(1,.2,.2,1),new t.Color4(1,.6,.1,1),new t.Color4(1,1,.2,1),new t.Color4(.3,1,.3,1),new t.Color4(.2,1,1,1),new t.Color4(.4,.5,1,1),new t.Color4(.9,.4,1,1),new t.Color4(1,1,1,1)];class Ou extends t.GaussianSplattingMesh{static IsLODMetadata(e){if("object"!=typeof e||null===e)return!1;const t=e;return"number"==typeof t.lodLevels&&Array.isArray(t.filenames)&&"object"==typeof t.tree&&null!==t.tree}constructor(e,n,s,o,r={}){var i,a,l;super(e,null,o,!1),this._leafNodes=[],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._maxDetailLod=0,this._frustumCulling=!0,this._frustumPlanes=[new t.Plane(0,0,0,0),new t.Plane(0,0,0,0),new t.Plane(0,0,0,0),new t.Plane(0,0,0,0),new t.Plane(0,0,0,0),new t.Plane(0,0,0,0)],this._cullViewProj=new t.Matrix,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._decodedFiles=new Set,this._loadingFiles=new Set,this._decodeQueue=[],this._fileRefs=new Map,this._cancelledDecodes=new Set,this._evictionEnabled=!1,this._residentBudget=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._framesSinceLodUpdate=0,this._lastLodCamPos=new t.Vector3(1/0,1/0,1/0),this._forceLodUpdate=!1,this._boundsMin=new t.Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._boundsMax=new t.Vector3(-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=s,this._streamOptions=r,this._hostCompound=null!==(i=r.hostCompound)&&void 0!==i?i:null,this._decodeSh=null===(a=r.decodeSh)||void 0===a||a,this._needsRotationScale=null!==(l=r.needsRotationScale)&&void 0!==l&&l;const u=Math.max(0,n.lodLevels-1);if(this._lodRangeMax=u,void 0!==r.lodBaseDistance&&(this._lodBaseDistance=Math.max(.1,r.lodBaseDistance)),void 0!==r.lodMultiplier&&(this._lodMultiplier=Math.max(1.2,r.lodMultiplier)),void 0!==r.lodBehindPenalty&&(this._lodBehindPenalty=Math.max(1,r.lodBehindPenalty)),void 0!==r.lodRangeMin&&(this._lodRangeMin=Math.max(0,Math.min(r.lodRangeMin,u))),void 0!==r.lodRangeMax&&(this._lodRangeMax=Math.max(this._lodRangeMin,Math.min(r.lodRangeMax,u))),void 0!==r.maxDecodesPerFrame&&(this._maxDecodesPerFrame=Math.max(1,r.maxDecodesPerFrame)),void 0!==r.lodCooldownFrames&&(this._lodCooldownFrames=Math.max(0,r.lodCooldownFrames)),void 0!==r.lodUpdateInterval&&(this._lodUpdateInterval=Math.max(1,r.lodUpdateInterval)),void 0!==r.lodUpdateDistance&&(this._lodUpdateDistance=Math.max(0,r.lodUpdateDistance)),void 0!==r.maxDetailLod&&(this._maxDetailLod=Math.max(0,Math.floor(r.maxDetailLod))),void 0!==r.frustumCulling&&(this._frustumCulling=r.frustumCulling),r.debugLodSource&&(this._debugLodSource=r.debugLodSource),void 0!==r.evictionCooldownFrames&&(this._evictionCooldownFrames=Math.max(0,Math.floor(r.evictionCooldownFrames))),void 0!==r.maxResidentSplats&&r.maxResidentSplats>0&&(this._maxResidentSplats=Math.floor(r.maxResidentSplats)),void 0!==r.memoryBudgetMb&&r.memoryBudgetMb>0&&(this._memoryBudgetMb=r.memoryBudgetMb),this._downloadManager=new _u({maxConcurrent:r.maxConcurrentDownloads,maxRetries:r.maxDownloadRetries}),this._hostCompound){this.setEnabled(!1),this.isPickable=!1,this.doNotSerialize=!0,this._partReadyPromise=new Promise((e,t)=>{this._partReadyResolve=e,this._partReadyReject=t}),this._partReadyPromise.catch(()=>{});const e=this._hostCompound.onDisposeObservable.add(()=>{this._disposed||(this._partReleasedByHost=!0,this.dispose())});this._hostUnsubDispose=()=>this._hostCompound.onDisposeObservable.remove(e)}else this.scaling.y*=-1,this.rotation.x=-Math.PI/2;this._collectLodEntries(n.tree),r.debugDisplay&&(this.debugDisplay=!0),this._streamAllAsync().then(()=>{const e=this._partReadySettled;this._rejectPartReady("GaussianSplattingStream: stream produced no splats."),e||!this._hostCompound||this._disposed||this._disposeAndReclaim()},e=>{var n,s;t.Logger.Error("GaussianSplattingStream: streaming failed: "+(null!==(n=null==e?void 0:e.message)&&void 0!==n?n:e)),this._rejectPartReady("GaussianSplattingStream: streaming failed: "+(null!==(s=null==e?void 0:e.message)&&void 0!==s?s:e)),this._hostCompound&&!this._disposed&&this._disposeAndReclaim()})}getClassName(){return"GaussianSplattingStream"}isReady(e=!1){return!!this._hostCompound||super.isReady(e)}get streamingPartProxy(){var e,t;return null!==(t=null===(e=this._host)||void 0===e?void 0:e.proxy)&&void 0!==t?t:null}whenPartReadyAsync(){return b(this,void 0,void 0,function*(){var e;yield null!==(e=this._partReadyPromise)&&void 0!==e?e:Promise.resolve()})}_resolvePartReady(){var e;this._partReadySettled||(this._partReadySettled=!0,null===(e=this._partReadyResolve)||void 0===e||e.call(this))}_rejectPartReady(e){var t;this._partReadySettled||(this._partReadySettled=!0,null===(t=this._partReadyReject)||void 0===t||t.call(this,new Error(e)))}whenSettledAsync(){return b(this,arguments,void 0,function*(e=3){if(this._disposed)return;this._forceLodUpdate=!0;const t=Math.max(1,e),n=this._scene;let s=0;const o=()=>this._isLoadingIdle()&&this._sinkIsDepthSortSettled?++s>=t:(s=0,!1);if(n.getEngine().activeRenderLoops.length>0)return void(yield new Promise(e=>{let t=null;t=n.onAfterRenderObservable.add(()=>{(this._disposed||o())&&(t&&(n.onAfterRenderObservable.remove(t),t=null),e())})}));const r=n.getEngine(),i=globalThis.requestAnimationFrame;for(;!this._disposed;){if(r.beginFrame(),n.render(),r.endFrame(),o())return;yield new Promise(e=>{"function"==typeof i?i(()=>e()):setTimeout(e,16)})}})}_isLoadingIdle(){return this._baseLayerReady&&0===this._decodeQueue.length&&0===this._loadingFiles.size&&this._downloadManager.isIdle}get maxDetailLod(){return this._maxDetailLod}set maxDetailLod(e){const t=Math.max(0,Math.floor(e));this._maxDetailLod!==t&&(this._maxDetailLod=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){var t,n,s,o,r,i;this._disposed||(this._disposed=!0,this._rejectPartReady("GaussianSplattingStream: disposed before the part was ready."),null===(t=this._unsubBeforeRebuild)||void 0===t||t.call(this),null===(n=this._unsubAfterRebuild)||void 0===n||n.call(this),this._unsubBeforeRebuild=null,this._unsubAfterRebuild=null,null===(s=this._hostUnsubRemove)||void 0===s||s.call(this),null===(o=this._hostUnsubDispose)||void 0===o||o.call(this),this._hostUnsubRemove=null,this._hostUnsubDispose=null,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),this._lodObserver=null),this._clearDebugDisplay(),this._downloadManager.dispose(),null===(r=this._residency)||void 0===r||r.dispose(),this._residency=null,null===(i=this._workBuffer)||void 0===i||i.dispose(),this._workBuffer=null,super.dispose(e))}_disposeAndReclaim(){const 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)}evaluateOptimalLods(e=this._scene.activeCamera){if(!e||0===this._leafNodes.length)return;const n=Math.max(0,this._metadata.lodLevels-1),s=this._lodBaseDistance,o=this._lodMultiplier,r=this._lodBehindPenalty,i=this._lodRangeMin,a=this._lodRangeMax,l=this._scene.getEngine().getAspectRatio(e)||1;let u=Math.tan(.5*e.fov);e.fovMode===t.Camera.FOVMODE_HORIZONTAL_FIXED&&(u/=l);const c=u*l,d=Math.min(u,c)/bu;this._getEffectiveWorldMatrix(!1).invertToRef(xu);const h=t.Vector3.TransformCoordinatesToRef(e.globalPosition,xu,Tu),m=h.x,f=h.y,p=h.z;let _=0,g=0,y=0;if(r>1){e.getDirectionToRef(wu,Mu);const n=t.Vector3.TransformNormalToRef(Mu,xu,Au);n.normalize(),_=n.x,g=n.y,y=n.z}for(const e of this._leafNodes){const t=e.bound.min,l=e.bound.max,u=(m<t[0]?t[0]:m>l[0]?l[0]:m)-m,c=(f<t[1]?t[1]:f>l[1]?l[1]:f)-f,h=(p<t[2]?t[2]:p>l[2]?l[2]:p)-p,v=Math.sqrt(u*u+c*c+h*h);let b=v;if(r>1&&v>.01){const e=(_*u+g*c+y*h)/v;e<0&&(b=v*(1+-e*(r-1)))}const x=b*d;let T;if(0===n||x<s)T=0;else for(T=n;T>1&&x<s*Math.pow(o,T-1);)T--;T<i?T=i:T>a&&(T=a),this._frustumCulling&&!1===e.inFrustum&&(T=a),e.optimalLod=T}}_displayedLodLevel(e){var t,n,s;return"optimal"===this._debugLodSource?null!==(n=null!==(t=e.optimalLod)&&void 0!==t?t:e.activeLod)&&void 0!==n?n:0:null!==(s=e.activeLod)&&void 0!==s?s:0}_refreshDebugDisplay(){"optimal"===this._debugLodSource&&this.evaluateOptimalLods(),this._buildDebugMesh();const 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(){"optimal"===this._debugLodSource&&this.evaluateOptimalLods(),this._computeDebugSignature()!==this._debugSignature&&this._updateDebugColors()}_buildDebugMesh(){this._debugMesh&&(this._debugMesh.dispose(),this._debugMesh=null),this._debugColorData=null;const e=[],n=[];for(const s of this._leafNodes){const o=Su[this._displayedLodLevel(s)%Su.length],r=s.bound.min,i=s.bound.max,a=[new t.Vector3(r[0],r[1],r[2]),new t.Vector3(i[0],r[1],r[2]),new t.Vector3(i[0],i[1],r[2]),new t.Vector3(r[0],i[1],r[2]),new t.Vector3(r[0],r[1],i[2]),new t.Vector3(i[0],r[1],i[2]),new t.Vector3(i[0],i[1],i[2]),new t.Vector3(r[0],i[1],i[2])];for(const t of Cu)e.push([a[t[0]],a[t[1]]]),n.push([o,o])}if(this._debugSignature=this._computeDebugSignature(),0===e.length)return;const s=t.CreateLineSystem(this.name+"_lodDebug",{lines:e,colors:n,updatable:!0,useVertexAlpha:!1},this._scene);s.parent=this,s.isPickable=!1,s.doNotSerialize=!0,s.reservedDataStore={hidden:!0},this._debugMesh=s,this._debugColorData=new Float32Array(this._leafNodes.length*Ru*4)}_updateDebugColors(){if(!this._debugMesh||!this._debugColorData)return;const e=this._debugColorData;let n=0;for(const t of this._leafNodes){const s=Su[this._displayedLodLevel(t)%Su.length];for(let t=0;t<Ru;t++)e[n++]=s.r,e[n++]=s.g,e[n++]=s.b,e[n++]=s.a}this._debugMesh.updateVerticesData(t.VertexBuffer.ColorKind,e),this._debugSignature=this._computeDebugSignature()}_computeDebugSignature(){let e=0;for(const t of this._leafNodes)e=31*e+this._displayedLodLevel(t)|0;return e}_clearDebugDisplay(){this._debugObserver&&(this._scene.onBeforeRenderObservable.remove(this._debugObserver),this._debugObserver=null),this._debugMesh&&(this._debugMesh.dispose(),this._debugMesh=null),this._debugColorData=null,this._debugSignature=0}_collectLodEntries(e){if(e.children){for(const t of e.children)this._collectLodEntries(t);return}if(!e.lods)return;const n=[];for(const t of Object.keys(e.lods)){const s=Number(t),o=e.lods[t];Number.isFinite(s)&&o&&o.count>0&&n.push(s)}0!==n.length&&(n.sort((e,t)=>e-t),e.availableLevels=n,e.baseLod=n[n.length-1],e.activeLod=void 0,e.lodCooldown=0,e.inFrustum=!0,e.cullBounds=new t.BoundingInfo(t.Vector3.FromArray(e.bound.min),t.Vector3.FromArray(e.bound.max)),this._leafNodes.push(e))}_streamAllAsync(){return b(this,void 0,void 0,function*(){const e=this._collectAllFileIds(),n=yield this._gatherCountsAsync(e);if(this._disposed)return;this._resolveResidentBudget();let s=1;n>0&&(s+=n);for(const t of e){const e=this._fileCounts.get(t);void 0!==e&&e>0&&(s+=e)}if(s<=1)return;this._evictionEnabled=this._residentBudget>0&&this._residentBudget<s;const o=this._evictionEnabled?Math.max(this._residentBudget,1):s;if(this._residency=new vu(o,this._evictionCooldownFrames,e=>this._onFileEvicted(e)),this._residency.pin(-2,1),n>0){const e=this._residency.pin(-1,n);null!==e?this._environmentRange={offset:e,count:n}:(t.Logger.Warn("GaussianSplattingStream: environment does not fit the memory budget; skipping it."),this._environmentFiles=null)}if(this._hostCompound){const e=t.Matrix.Compose(new t.Vector3(1,-1,1),t.Quaternion.RotationYawPitchRoll(0,-Math.PI/2,0),t.Vector3.ZeroReadOnly),n=this._hostCompound.reserveStreamingPart(o,e,this.name+"_part",this._shTextureCount,this._streamShDegree,this._needsRotationScale);this._host=n,this._positionBase=n.base;const s=this._hostCompound,r=s.onPartRemovedObservable.add(e=>{!this._disposed&&this._host&&e===this._host.partIndex&&(this._partReleasedByHost=!0,this.dispose())});this._hostUnsubRemove=()=>s.onPartRemovedObservable.remove(r);const i=this._shTextureCount>0&&n.shMrtAtlas?{textureCount:this._shTextureCount,externalMrts:n.shMrtAtlas}:void 0,a=this._needsRotationScale&&n.rotMrtAtlas?{externalMrt:n.rotMrtAtlas}:void 0;this._workBuffer=new pu(this._scene,n.capacity,{mrt:n.mrtAtlas,width:n.atlasWidth,baseOffset:n.base},i,a),this._readbackCandidate=this._workBuffer.supportsAsyncCentersReadback,this._splatPositions=n.splatPositions,this._vertexCount=o;const l=this._workBuffer;this._unsubBeforeRebuild=n.onBeforeAtlasRebuild(()=>{l.backupRegion(),this._positionSnapshot=this._splatPositions?this._splatPositions.slice(4*this._positionBase,4*(this._positionBase+this._vertexCount)):null}),this._unsubAfterRebuild=n.onAfterAtlasRebuild(()=>{n.mrtAtlas&&l.rebindAtlas(n.mrtAtlas),l.rebindShAtlas(n.shMrtAtlas),l.rebindRotAtlas(n.rotMrtAtlas),this._positionBase=n.base,l.setBaseOffset(n.base),l.restoreRegion(),this._splatPositions=n.splatPositions,this._positionSnapshot&&this._splatPositions&&(this._splatPositions.set(this._positionSnapshot,4*this._positionBase),this._positionSnapshot=null)}),n.setActiveRanges([])}else{const e=this._shTextureCount>0?{textureCount:this._shTextureCount}:void 0,t=this._needsRotationScale?{}:void 0;this._workBuffer=new pu(this._scene,o,void 0,e,t),this._readbackCandidate=this._workBuffer.supportsAsyncCentersReadback;const n=new Float32Array(4*o),s=this._workBuffer.textures,r=e?this._workBuffer.shTextures:void 0,i=t?this._workBuffer.rotationTextures:void 0;this._setExternalWorkBuffer(s[0],s[1],s[2],s[3],n,o,r,this._streamShDegree,i),this.setSplatIndexRanges([]),this.setEnabled(!0)}if(this._host&&this._workBuffer&&(yield this._waitForCanBackupAsync(this._workBuffer),this._disposed))return;this._environmentRange&&this._environmentFiles&&(yield this._decodeEnvironmentAsync()),this._environmentFiles=null;const r=new Set;for(const e of this._leafNodes){const t=e.lods[String(e.baseLod)];t&&this._fileCounts.has(t.file)&&r.add(t.file)}for(const e of Array.from(r)){if(this._disposed)return;yield this._decodeFileAsync(e)}this._disposed||(this._baseLayerReady=!0,this._lodObserver||(this._lodObserver=this._scene.onBeforeRenderObservable.add(()=>this._onLodFrame())),this._resolvePartReady())})}_waitForCanBackupAsync(e){return b(this,void 0,void 0,function*(){for(let t=0;t<600&&!this._disposed;t++){if(e.canBackup)return;yield new Promise(e=>this._scene.onBeforeRenderObservable.addOnce(()=>e()))}this._disposed||e.canBackup||t.Logger.Warn("GaussianSplattingStream: backup/restore copy shaders did not compile in time; a grow/compaction before they are ready may drop streamed data.")})}_resolveResidentBudget(){let e=this._maxResidentSplats;if(this._memoryBudgetMb>0){const t=this._scene.getEngine().getCaps().textureHalfFloatRender?24:48,n=84+16*this._shTextureCount+(this._needsRotationScale?t:0),s=Math.floor(1024*this._memoryBudgetMb*1024/n);e=e>0?Math.min(e,s):s}this._residentBudget=e}_collectAllFileIds(){const e=new Set;for(const t of this._leafNodes)for(const n of t.availableLevels){const s=t.lods[String(n)];s&&e.add(s.file)}return Array.from(e).sort((e,t)=>e-t)}_gatherCountsAsync(e){return b(this,void 0,void 0,function*(){var n;let s=0,o=0,r=0;const i=e=>{const t=Ou._GetShInfo(e);t.degree>o&&(o=t.degree),t.coeffs>r&&(r=t.coeffs)};if(this._metadata.environment)try{const e=this._rootUrl+this._metadata.environment,t=yield this._downloadManager.loadFileAsync(e),n=yield this._unzipAsync(new Uint8Array(t)),o=n.get("meta.json");if(o){const e=JSON.parse((new TextDecoder).decode(o));s=Ou._GetSplatCount(e),i(e),this._environmentFiles=n}}catch(e){t.Logger.Warn("GaussianSplattingStream: failed to load environment: "+(null!==(n=null==e?void 0:e.message)&&void 0!==n?n:e))}yield Promise.all(e.map(e=>b(this,void 0,void 0,function*(){var n;const s=this._metadata.filenames[e];if(s)try{const t=this._rootUrl+s,n=t.substring(0,t.lastIndexOf("/")+1),o=yield this._downloadManager.loadFileAsync(t),r=JSON.parse((new TextDecoder).decode(new Uint8Array(o)));this._fileCounts.set(e,Ou._GetSplatCount(r)),this._fileMeta.set(e,{sogData:r,subRootUrl:n})}catch(e){t.Logger.Warn(`GaussianSplattingStream: failed to load metadata for ${s}: ${null!==(n=null==e?void 0:e.message)&&void 0!==n?n:e}`)}else t.Logger.Warn(`GaussianSplattingStream: missing filename for file index ${e}.`)})));for(const{sogData:e}of this._fileMeta.values())i(e);return this._decodeSh&&o>0&&r>0&&(this._streamShDegree=o,this._shTextureCount=Math.ceil(3*r/16)),s})}_enqueueDecode(e){this._decodedFiles.has(e)||this._loadingFiles.has(e)||!this._fileMeta.has(e)||-1===this._decodeQueue.indexOf(e)&&this._decodeQueue.push(e)}_pumpDecodeQueue(){let e=0;for(;this._decodeQueue.length>0&&e<this._maxDecodesPerFrame;){const n=this._decodeQueue.shift();this._decodedFiles.has(n)||this._loadingFiles.has(n)||(e++,this._decodeFileAsync(n).catch(e=>{var n;t.Logger.Warn("GaussianSplattingStream: decode failed: "+(null!==(n=null==e?void 0:e.message)&&void 0!==n?n:e))}))}}_applyPositions(e,t,n){this._splatPositions.set(e,4*(this._positionBase+t)),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}_probeReadbackAsync(e,n,s){return b(this,void 0,void 0,function*(){if(this._readbackProbed=!0,!this._workBuffer)return;const o=Math.min(n,1024);let r=!1;try{const t=yield this._workBuffer.readCentersRangeAsync(e,o);if(this._disposed)return;if(t&&t.length>=4*o){r=!0;for(let e=0;e<o&&r;e++)for(let n=0;n<3;n++){const o=t[4*e+n],i=s[4*e+n];if(Math.abs(o-i)>.01*(1+Math.abs(i))){r=!1;break}}}}catch(e){r=!1}this._useGpuPositionReadback=r,t.Logger.Log(r?"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.")})}_applyDecodedPositionsAsync(e,t,n){return b(this,void 0,void 0,function*(){if(this._useGpuPositionReadback&&this._workBuffer){const e=yield this._workBuffer.readCentersRangeAsync(t,n);if(this._disposed)return!1;if(e&&this._splatPositions)return this._applyPositions(e,t,n),!0}const s=e.positions.length>=4*n?e.positions.subarray(0,4*n):null;return!(!s||!this._splatPositions||(this._applyPositions(s,t,n),!this._readbackProbed&&this._readbackCandidate&&(yield this._probeReadbackAsync(t,n,s)),0))})}_decodeEnvironmentAsync(){return b(this,void 0,void 0,function*(){var e;if(!this._environmentRange||!this._environmentFiles||!this._workBuffer)return;const n=this._environmentRange;try{const e=(yield hu(this._environmentFiles,"",this._scene,!this._useGpuPositionReadback,this._downloadManager)).sogTextures;if(!e)return;try{if(this._disposed||!this._workBuffer)return;if(yield this._workBuffer.decodeAsync(e,n.offset),this._disposed)return;if(yield this._applyDecodedPositionsAsync(e,n.offset,n.count),this._disposed)return;this._refreshActiveRanges()}finally{Ou._DisposePack(e)}}catch(n){t.Logger.Warn("GaussianSplattingStream: failed to decode environment: "+(null!==(e=null==n?void 0:n.message)&&void 0!==e?e:n))}})}_decodeFileAsync(e){return b(this,void 0,void 0,function*(){if(this._decodedFiles.has(e)||this._loadingFiles.has(e)||!this._residency)return;const n=this._fileMeta.get(e),s=this._fileCounts.get(e);if(!n||void 0===s)return;this._loadingFiles.add(e),this._cancelledDecodes.delete(e);let o=!1;try{const r=(yield hu(n.sogData,n.subRootUrl,this._scene,!this._useGpuPositionReadback,this._downloadManager,e)).sogTextures;if(!r)return;const i=yield this._acquireDecodeGateAsync();try{if(this._disposed||!this._workBuffer||this._cancelledDecodes.has(e))return;let n=this._residency.allocate(e,s);if(null===n&&(n=yield this._relayoutAndAllocateAsync(e,s)),null===n)return void(this._cancelledDecodes.has(e)||t.Logger.Warn(`GaussianSplattingStream: resident memory budget full; skipping LOD file ${e}.`));if(o=!0,this._disposed||!this._workBuffer||this._cancelledDecodes.has(e))return;if(yield this._workBuffer.decodeAsync(r,n),this._disposed||this._cancelledDecodes.has(e))return;if(yield this._applyDecodedPositionsAsync(r,n,s),this._disposed)return;this._decodedFiles.add(e),this._applyDesiredLods()&&this._refreshActiveRanges()}finally{Ou._DisposePack(r),i()}}catch(t){if(!this._cancelledDecodes.has(e))throw t}finally{o&&!this._decodedFiles.has(e)&&this._residency.free(e),this._loadingFiles.delete(e),this._cancelledDecodes.delete(e)}})}_acquireDecodeGateAsync(){return b(this,void 0,void 0,function*(){const e=this._decodeGate;let t;return this._decodeGate=new Promise(e=>{t=e}),yield e,t})}_relayoutAndAllocateAsync(e,t){return b(this,void 0,void 0,function*(){return this._residency&&this._workBuffer?this._residency.freeSize<t?null:yield new Promise(n=>{const s=()=>{!this._disposed&&this._residency&&this._workBuffer&&!this._cancelledDecodes.has(e)?this._workBuffer.isRelayoutReady()?(this._performRelayout(),n(this._residency.allocate(e,t))):this._scene.onBeforeRenderObservable.addOnce(s):n(null)};this._scene.onBeforeRenderObservable.addOnce(s)}):null})}_performRelayout(){if(!this._residency||!this._workBuffer||!this._splatPositions)return;const e=this._relayoutOldOffsets;e.clear();for(const t of this._residency.getResidentBlocks())e.set(t.file,t.offset);if(0===this._residency.compact().length)return;const t=this._residency.capacity;this._relayoutSrcIndex&&this._relayoutSrcIndex.length===t||(this._relayoutSrcIndex=new Float32Array(t));const n=this._relayoutSrcIndex;n.fill(-1);const s=this._residency.getResidentBlocks();for(const t of s){const s=e.get(t.file);for(let e=0;e<t.count;e++)n[t.offset+e]=s+e}this._workBuffer.relayoutSync(n);const o=this._splatPositions,r=this._positionBase;s.sort((e,t)=>e.offset-t.offset);for(const t of s){const n=e.get(t.file);n!==t.offset&&o.copyWithin(4*(r+t.offset),4*(r+n),4*(r+n+t.count))}if(this._environmentRange){const e=this._residency.offset(-1);void 0!==e&&(this._environmentRange.offset=e)}this._sinkNotifyDataChanged(),this._refreshActiveRanges()}_onFileEvicted(e){this._decodedFiles.delete(e)}_cappedLevelForNode(e,t){const n=e.availableLevels,s=this._maxDetailLod;let o=-1,r=Number.POSITIVE_INFINITY;for(const e of n){if(e<s)continue;const n=Math.abs(e-t);n<r&&(o=e,r=n)}return o<0?e.baseLod:o}_computeTargetLevels(){var e;for(const t of this._leafNodes){const n=null!==(e=t.optimalLod)&&void 0!==e?e:t.baseLod;t.targetLevel=this._cappedLevelForNode(t,n)}}_applyDesiredLods(){var e;let t=!1;for(const n of this._leafNodes){if(n.lodCooldown&&n.lodCooldown>0)continue;const s=null!==(e=n.targetLevel)&&void 0!==e?e:n.baseLod;let o;if(s!==n.activeLod){const e=n.lods[String(s)];e&&(this._decodedFiles.has(e.file)?(this._switchActiveFile(n,e.file),n.activeLod=s,n.lodCooldown=this._lodCooldownFrames,t=!0):o=e.file)}n.pendingFile!==o&&(void 0!==n.pendingFile&&this._releaseFileRef(n.pendingFile),void 0!==o&&this._acquirePendingFile(o),n.pendingFile=o)}return t}_switchActiveFile(e,t){e.activeFile!==t&&(void 0!==e.activeFile&&this._releaseFileRef(e.activeFile),this._acquireFileRef(t),e.activeFile=t)}_acquireFileRef(e){var t,n;const s=(null!==(t=this._fileRefs.get(e))&&void 0!==t?t:0)+1;this._fileRefs.set(e,s),1===s&&(null===(n=this._residency)||void 0===n||n.cancelEviction(e))}_acquirePendingFile(e){this._acquireFileRef(e),this._enqueueDecode(e)}_releaseFileRef(e){var t,n;const s=(null!==(t=this._fileRefs.get(e))&&void 0!==t?t:0)-1;if(s>0)return void this._fileRefs.set(e,s);if(this._fileRefs.delete(e),this._decodedFiles.has(e))return void(this._evictionEnabled&&(null===(n=this._residency)||void 0===n||n.scheduleEviction(e)));const o=this._decodeQueue.indexOf(e);-1!==o&&this._decodeQueue.splice(o,1),this._loadingFiles.has(e)&&(this._cancelledDecodes.add(e),this._downloadManager.cancelGroup(e))}_onLodFrame(){var e;if(this._disposed||!this._baseLayerReady)return;let n=!1;for(const e of this._leafNodes)e.lodCooldown&&e.lodCooldown>0&&(e.lodCooldown--,0===e.lodCooldown&&void 0!==e.targetLevel&&e.targetLevel!==e.activeLod&&(n=!0));this._evictionEnabled&&(null===(e=this._residency)||void 0===e||e.tick()),this._pumpDecodeQueue();const s=this._updateNodeFrustum();let o=this._forceLodUpdate||s||n;if(!o&&++this._framesSinceLodUpdate>=this._lodUpdateInterval){const e=this._scene.activeCamera,n=this._lodUpdateDistance;(!e||t.Vector3.DistanceSquared(e.globalPosition,this._lastLodCamPos)>=n*n)&&(e&&this._lastLodCamPos.copyFrom(e.globalPosition),o=!0)}o&&(this._forceLodUpdate=!1,this._framesSinceLodUpdate=0,this.evaluateOptimalLods(this._scene.activeCamera),this._computeTargetLevels(),this._applyDesiredLods()&&this._refreshActiveRanges())}_updateNodeFrustum(){const e=this._scene.activeCamera;let n=!1;if(!this._frustumCulling||!e){for(const e of this._leafNodes)!1===e.inFrustum&&(e.inFrustum=!0,n=!0);return n}const s=this._getEffectiveWorldMatrix(!1);e.getViewMatrix().multiplyToRef(e.getProjectionMatrix(),this._cullViewProj),t.Frustum.GetPlanesToRef(this._cullViewProj,this._frustumPlanes);for(const e of this._leafNodes){e.cullBounds.update(s);const t=e.cullBounds.isInFrustum(this._frustumPlanes);t!==e.inFrustum&&(e.inFrustum=t,n=!0)}return n}static _GetSplatCount(e){var t;return null!==(t=e.count)&&void 0!==t?t:Array.isArray(e.means.shape)?e.means.shape[0]:0}static _GetShInfo(e){if(!e.shN)return{degree:0,coeffs:0};let n=0;const s=e.shN.bands;if("number"==typeof s&&Number.isFinite(s)&&s>0)n=Math.floor(s);else if(Array.isArray(e.shN.shape)&&Number.isFinite(e.shN.shape[1])&&e.shN.shape[1]>0){const t=Math.floor(e.shN.shape[1]/3);n=t>0?Math.round(Math.sqrt(t+1)-1):0}return n>0?(n>4&&(t.Logger.Warn(`GaussianSplattingStream: SH degree ${n} exceeds the maximum supported (4); clamping.`),n=4),{degree:n,coeffs:Math.pow(n+1,2)-1}):{degree:0,coeffs:0}}static _DisposePack(e){var t,n,s;e.meansTextureL.dispose(),e.meansTextureU.dispose(),e.scalesTexture.dispose(),e.quatsTexture.dispose(),e.sh0Texture.dispose(),null===(t=e.shCentroidsTexture)||void 0===t||t.dispose(),null===(n=e.shLabelsTexture)||void 0===n||n.dispose(),null===(s=e.codebookTexture)||void 0===s||s.dispose()}_updateBounds(e,n){const s=this._boundsMin,o=this._boundsMax;for(let t=0;t<n;t++){const n=e[4*t+0],r=e[4*t+1],i=e[4*t+2];s.minimizeInPlaceFromFloats(n,r,i),o.maximizeInPlaceFromFloats(n,r,i)}this._host?this._host.expandBounds(s,o):this.setBoundingInfo(new t.BoundingInfo(s,o))}_refreshActiveRanges(){var e;const t=[];this._environmentRange&&t.push({offset:this._environmentRange.offset,count:this._environmentRange.count});for(const n of this._leafNodes){if(void 0===n.activeLod)continue;const s=n.lods[String(n.activeLod)];if(!s)continue;const o=null===(e=this._residency)||void 0===e?void 0:e.offset(s.file);void 0!==o&&t.push({offset:o+s.offset,count:s.count})}this._sinkSetActiveRanges(Ou._CoalesceRanges(t))}static _CoalesceRanges(e){if(e.length<=1)return e;const 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++){const s=n[n.length-1],o=t[e],r=s.offset+s.count;if(o.offset<=r){const e=Math.max(r,o.offset+o.count);s.count=e-s.offset}else n.push({offset:o.offset,count:o.count})}return n}_unzipAsync(e){return b(this,void 0,void 0,function*(){var n;let s=this._streamOptions.fflate;s||(void 0===window.fflate&&(yield t.Tools.LoadScriptAsync(null!==(n=this._streamOptions.deflateURL)&&void 0!==n?n:"https://unpkg.com/fflate/umd/index.js")),s=window.fflate);const o=s.unzipSync(e),r=new Map;for(const[e,t]of Object.entries(o))r.set(e,t);return r})}}const Fu=.28209479177387814;let Eu=null,Iu=null;class Lu{constructor(e={}){this.name=ru.name,this._assetContainer=null,this.extensions=ru.extensions,this._loadingOptions=Object.assign(Object.assign({},Lu._DefaultLoadingOptions),e)}createPlugin(e){return new Lu(e[ru.name])}importMeshAsync(e,t,n,s,o,r){return b(this,void 0,void 0,function*(){const o=this._tryCreateLODStream(t,n,s);return o?{meshes:[o],particleSystems:[],skeletons:[],animationGroups:[],transformNodes:[],geometries:[],lights:[],spriteManagers:[]}:yield this._parseAsync(e,t,n,s).then(e=>({meshes:e,particleSystems:[],skeletons:[],animationGroups:[],transformNodes:[],geometries:[],lights:[],spriteManagers:[]}))})}_tryCreateLODStream(e,t,n){if("string"!=typeof t)return null;let s;try{s=JSON.parse(t)}catch(e){return null}if(!Ou.IsLODMetadata(s))return null;const o=e._blockEntityCollection;e._blockEntityCollection=!!this._assetContainer;try{const t=new Ou("GaussianSplattingStream",s,n,e,{deflateURL:this._loadingOptions.deflateURL,fflate:this._loadingOptions.fflate});return t._parentContainer=this._assetContainer,t}finally{e._blockEntityCollection=o}}static _BuildPointCloud(e,n){if(!n.byteLength)return!1;const s=new Uint8Array(n),o=new Float32Array(n),r=s.length/32;return e.addPoints(r,function(e,n){const r=o[8*n+0],i=o[8*n+1],a=o[8*n+2];e.position=new t.Vector3(r,i,a);const l=s[32*n+24+0]/255,u=s[32*n+24+1]/255,c=s[32*n+24+2]/255;e.color=new t.Color4(l,u,c,1)}),!0}static _BuildMesh(e,n){const s=new t.Mesh("PLYMesh",e),o=new Uint8Array(n.data),r=new Float32Array(n.data),i=o.length/32,a=[],l=new t.VertexData;for(let e=0;e<i;e++){const t=r[8*e+0],n=r[8*e+1],s=r[8*e+2];a.push(t,n,s)}if(n.hasVertexColors){const e=new Float32Array(4*i);for(let t=0;t<i;t++){const n=o[32*t+24+0]/255,s=o[32*t+24+1]/255,r=o[32*t+24+2]/255;e[4*t+0]=n,e[4*t+1]=s,e[4*t+2]=r,e[4*t+3]=1}l.colors=e}return l.positions=a,l.indices=n.faces,l.applyToMesh(s),s}_unzipWithFFlateAsync(e){return b(this,void 0,void 0,function*(){var n;let s=this._loadingOptions.fflate;s||(void 0===window.fflate&&(yield t.Tools.LoadScriptAsync(null!==(n=this._loadingOptions.deflateURL)&&void 0!==n?n:"https://unpkg.com/fflate/umd/index.js")),s=window.fflate);const{unzipSync:o}=s,r=o(e),i=new Map;for(const[e,t]of Object.entries(r))i.set(e,t);return i})}_parseAsync(e,n,s,o){const r=[],i=e=>{var s;n._blockEntityCollection=!!this._assetContainer;const o=null!==(s=this._loadingOptions.gaussianSplattingMesh)&&void 0!==s?s:new t.GaussianSplattingMesh("GaussianSplatting",null,n,this._loadingOptions.keepInRam,this._loadingOptions.needsRotationScaleTextures);o._parentContainer=this._assetContainer,r.push(o),e.sogTextures?o.setSogTextureData(e.sogTextures):o.updateData(e.data,e.sh,{flipY:!1},void 0,e.shDegree),o.scaling.y*=-1,o.computeWorldMatrix(!0),o.safeOrbitCameraLimits=Lu._ExtractSafeOrbitLimits(e),n._blockEntityCollection=!1},a=n.getEngine();let l=this._loadingOptions.useSogTextures;l&&!a.isWebGPU&&a.version<2&&(t.Logger.Warn("SPLATFileLoader: useSogTextures requires WebGL2 or WebGPU. Falling back to CPU path."),l=!1);const u=l?hu:lu;if("string"==typeof s){const e=JSON.parse(s);if(e&&e.means&&e.scales&&e.quats&&e.sh0)return new Promise((t,s)=>{u(e,o,n).then(e=>{i(e),t(r)}).catch(e=>{s(new Error("Failed to parse SOG data.",{cause:e}))})})}const c=s instanceof ArrayBuffer?new Uint8Array(s):s;if(80===c[0]&&75===c[1])return new Promise((e,t)=>{this._unzipWithFFlateAsync(c).then(s=>{u(s,o,n).then(t=>{i(t),e(r)}).catch(e=>{t(new Error("Failed to parse SOG zip data.",{cause:e}))})})});const d=e=>{Lu._ConvertPLYToSplat(s).then(s=>b(this,void 0,void 0,function*(){var o;switch(n._blockEntityCollection=!!this._assetContainer,s.mode){case 0:{const e=null!==(o=this._loadingOptions.gaussianSplattingMesh)&&void 0!==o?o:new t.GaussianSplattingMesh("GaussianSplatting",null,n,this._loadingOptions.keepInRam,this._loadingOptions.needsRotationScaleTextures);switch(e._parentContainer=this._assetContainer,r.push(e),e.updateData(s.data,s.sh,{flipY:!1},void 0,s.shDegree),e.scaling.y*=-1,"RightHanded"===s.chirality&&(e.scaling.y*=-1),s.upAxis){case"X":e.rotation=new t.Vector3(0,0,Math.PI/2);break;case"Y":e.rotation=new t.Vector3(0,0,Math.PI);break;case"Z":e.rotation=new t.Vector3(-Math.PI/2,Math.PI,0)}e.computeWorldMatrix(!0),e.safeOrbitCameraLimits=Lu._ExtractSafeOrbitLimits(s)}break;case 1:{const e=new t.PointsCloudSystem("PointCloud",1,n);Lu._BuildPointCloud(e,s.data)?yield e.buildMeshAsync().then(e=>{r.push(e)}):e.dispose()}break;case 2:if(!s.faces)throw new Error("PLY mesh doesn't contain face informations.");r.push(Lu._BuildMesh(n,s));break;default:throw new Error("Unsupported Splat mode")}n._blockEntityCollection=!1,this.applyAutoCameraLimits(Lu._ExtractSafeOrbitLimits(s),n),e(r)}))},h=31===c[0]&&139===c[1],m=78===c[0]&&71===c[1]&&83===c[2]&&80===c[3];if(!h&&!m)return new Promise(e=>{d(e)});const f=(e,s)=>{var o;n._blockEntityCollection=!!this._assetContainer;const i=null!==(o=this._loadingOptions.gaussianSplattingMesh)&&void 0!==o?o:new t.GaussianSplattingMesh("GaussianSplatting",null,n,this._loadingOptions.keepInRam,this._loadingOptions.needsRotationScaleTextures);if(e.trainedWithAntialiasing){const e=i.material;e.kernelSize=.1,e.compensation=!0}i._parentContainer=this._assetContainer,r.push(i),i.updateData(e.data,e.sh,{flipY:!1},void 0,e.shDegree),this._loadingOptions.flipY||(i.scaling.y*=-1,i.computeWorldMatrix(!0)),n._blockEntityCollection=!1;const a=Lu._ExtractSafeOrbitLimits(e);i.safeOrbitCameraLimits=a,this.applyAutoCameraLimits(a,n),s(r)};if(this._loadingOptions.spzLibraryUrl)return function(e){return b(this,void 0,void 0,function*(){if(Eu&&Iu===e)return yield Eu;const n=t._LoadScriptModuleAsync(`import createSpzModule from '${e}';\n const module = await createSpzModule();\n const returnedValue = module;`);return Iu=e,Eu=n,yield n})}(this._loadingOptions.spzLibraryUrl).then(e=>function(e,n){return b(this,void 0,void 0,function*(){return yield t.runCoroutineAsync(function*(e,n,s=!1){const o=e.numPoints,r=new ArrayBuffer(32*o),i=new Float32Array(r),a=new Uint8Array(r),l=e.positions,u=e.scales,c=e.colors,d=e.alphas,h=e.rotations;let m=null;const f=e.shDegree;let p,_,g=null,y=0,v=null,b=null,x=null;if(f>0&&e.sh.length>0){y=3*((f+1)*(f+1)-1);const s=Math.ceil(y/16),r=n.getEngine().getCaps().maxTextureSize,i=Math.ceil(o/r);m=t.AllocateShBuffers(s,i*r*4*4),v=new Int32Array(s),b=new Int32Array(s);for(let e=0;e<s;e++)v[e]=16*e,b[e]=Math.min(16*(e+1),y);x=m,g=e.sh}for(let e=0;e<o;e++){const t=8*e,n=32*e,o=3*e,r=4*e;i[t+0]=l[o+0],i[t+1]=l[o+1],i[t+2]=l[o+2],i[t+3]=Math.exp(u[o+0]),i[t+4]=Math.exp(u[o+1]),i[t+5]=Math.exp(u[o+2]);const m=255*(.5+Fu*c[o+0]),f=255*(.5+Fu*c[o+1]),p=255*(.5+Fu*c[o+2]);a[n+24]=m<=0?0:m>=255?255:m+.5|0,a[n+25]=f<=0?0:f>=255?255:f+.5|0,a[n+26]=p<=0?0:p>=255?255:p+.5|0,a[n+27]=1/(1+Math.exp(-d[e]))*255+.5|0;const _=127.5*h[r+3]+127.5,T=127.5*h[r+0]+127.5,A=127.5*h[r+1]+127.5,M=127.5*h[r+2]+127.5;if(a[n+28]=_<=0?0:_>=255?255:_+.5|0,a[n+29]=T<=0?0:T>=255?255:T+.5|0,a[n+30]=A<=0?0:A>=255?255:A+.5|0,a[n+31]=M<=0?0:M>=255?255:M+.5|0,g&&x&&v&&b){const t=e*y,n=16*e;for(let e=0;e<x.length;e++){const s=x[e],o=v[e],r=b[e];for(let e=o;e<r;e++){const r=128*g[t+e]+128;s[n+e-o]=r<=0?0:r>=255?255:r+.5|0}}}e%32768==0&&s&&(yield)}if(e.extensions)for(const t of e.extensions){const e=t;if(void 0!==e.safeOrbitRadiusMin){p=e.safeOrbitRadiusMin,_=[e.safeOrbitElevationMin,e.safeOrbitElevationMax];break}}return{mode:0,data:r,hasVertexColors:!1,sh:null!==m?m:void 0,shDegree:f>0?f:void 0,trainedWithAntialiasing:!!e.antialiased,safeOrbitCameraRadiusMin:p,safeOrbitCameraElevationMinMax:_}}(e,n,!0),t.createYieldingScheduler())})}(e.loadSpzFromBuffer(new Uint8Array(s),{to:e.CoordinateSystem.RUB}),n).then(e=>new Promise(t=>{f(e,t)})));if(m)return Promise.reject(new 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."));const p=new ReadableStream({start(e){e.enqueue(new Uint8Array(s)),e.close()}}),_=new DecompressionStream("gzip"),g=p.pipeThrough(_);return new Promise(e=>{new Response(g).arrayBuffer().then(s=>{(function(e,n){const s=new Uint8Array(e),o=new Uint32Array(e.slice(0,12)),r=o[2],i=s[12],a=s[13],l=s[14],u=s[15],c=o[1];if(u||1347635022!=o[0]||c<2||c>4)return new Promise(e=>{e({mode:3,data:new ArrayBuffer(0),hasVertexColors:!1})});const d=new ArrayBuffer(32*r),h=1/(1<<a),m=new Int32Array(1),f=new Uint8Array(m.buffer),p=function(e,t){return f[0]=e[t+0],f[1]=e[t+1],f[2]=e[t+2],f[3]=128&e[t+2]?255:0,m[0]*h};let _=16;const g=new Float32Array(d),y=new Float32Array(d),v=new Uint8ClampedArray(d),b=new Uint8ClampedArray(d);for(let e=0;e<r;e++)g[8*e+0]=p(s,_+0),g[8*e+1]=p(s,_+3),g[8*e+2]=p(s,_+6),_+=9;for(let e=0;e<r;e++){for(let n=0;n<3;n++){const o=(s[_+r+3*e+n]-127.5)/38.25;v[32*e+24+n]=t.Scalar.Clamp(255*(.5+Fu*o),0,255)}v[32*e+24+3]=s[_+e]}_+=4*r;for(let e=0;e<r;e++)y[8*e+3+0]=Math.exp(s[_+0]/16-10),y[8*e+3+1]=Math.exp(s[_+1]/16-10),y[8*e+3+2]=Math.exp(s[_+2]/16-10),_+=3;if(c>=3){const e=Math.SQRT1_2;for(let t=0;t<r;t++){const n=[s[_+0],s[_+1],s[_+2],s[_+3]],o=n[0]+(n[1]<<8)+(n[2]<<16)+(n[3]<<24),r=511,i=[],a=o>>>30;let l=o,u=0;for(let t=3;t>=0;--t)if(t!==a){const n=l&r,s=l>>>9&1;l>>>=10,i[t]=e*(n/r),1===s&&(i[t]=-i[t]),u+=i[t]*i[t]}const c=1-u;i[a]=Math.sqrt(Math.max(c,0));const d=[3,0,1,2];for(let e=0;e<4;e++)b[32*t+28+e]=Math.round(127.5+127.5*i[d[e]]);_+=4}}else for(let e=0;e<r;e++){const t=s[_+0],n=s[_+1],o=s[_+2],r=t/127.5-1,i=n/127.5-1,a=o/127.5-1;b[32*e+28+1]=t,b[32*e+28+2]=n,b[32*e+28+3]=o;const l=1-(r*r+i*i+a*a);b[32*e+28+0]=127.5+127.5*Math.sqrt(l<0?0:l),_+=3}if(i){const e=3*((i+1)*(i+1)-1),o=Math.ceil(e/16);let a=_;const u=n.getEngine().getCaps().maxTextureSize,c=Math.ceil(r/u),h=t.AllocateShBuffers(o,c*u*4*4);for(let t=0;t<r;t++)for(let n=0;n<e;n++){const e=s[a++],o=Math.floor(n/16);h[o][n%16+16*t]=e}return new Promise(e=>{e({mode:0,data:d,hasVertexColors:!1,sh:h,shDegree:i,trainedWithAntialiasing:!!l})})}return new Promise(e=>{e({mode:0,data:d,hasVertexColors:!1,trainedWithAntialiasing:!!l})})})(s,n,this._loadingOptions).then(t=>{f(t,e)})}).catch(()=>{d(e)})})}static _ExtractSafeOrbitLimits(e){return void 0===e.safeOrbitCameraRadiusMin&&void 0===e.safeOrbitCameraElevationMinMax?null:{radiusMin:e.safeOrbitCameraRadiusMin,elevationMinMax:e.safeOrbitCameraElevationMinMax}}applyAutoCameraLimits(e,t){var n;if(!this._loadingOptions.disableAutoCameraLimits&&e&&"ArcRotateCamera"===(null===(n=t.activeCamera)||void 0===n?void 0:n.getClassName())){const n=t.activeCamera;e.elevationMinMax&&(n.lowerBetaLimit=.5*Math.PI-e.elevationMinMax[1],n.upperBetaLimit=.5*Math.PI-e.elevationMinMax[0]),e.radiusMin&&(n.lowerRadiusLimit=e.radiusMin)}}loadAssetContainerAsync(e,n,s){const o=new t.AssetContainer(e);return this._assetContainer=o,this.importMeshAsync(null,e,n,s).then(e=>{for(const t of e.meshes)o.meshes.push(t);return this._assetContainer=null,o}).catch(e=>{throw this._assetContainer=null,e})}loadAsync(e,t,n){return this.importMeshAsync(null,e,t,n).then(()=>{})}static _ConvertPLYToSplat(e){const n=new Uint8Array(e),s=(new TextDecoder).decode(n.slice(0,10240)),o=s.indexOf("end_header\n");if(o<0||!s)return new Promise(t=>{t({mode:0,data:e,rawSplat:!0})});const r=parseInt(/element vertex (\d+)\n/.exec(s)[1]),i=/element face (\d+)\n/.exec(s);let a=0;i&&(a=parseInt(i[1]));const l=/element chunk (\d+)\n/.exec(s);let u=0;l&&(u=parseInt(l[1]));let c=0,d=0;const h={double:8,int:4,uint:4,float:4,short:2,ushort:2,uchar:1,list:0};let m=1;const f=[],p=[],_=s.slice(0,o).split("\n"),g={};for(const n of _)if(n.startsWith("property ")){const[,s,o]=n.split(" ");if(1==m)p.push({name:o,type:s,offset:d}),d+=h[s];else if(0==m)f.push({name:o,type:s,offset:c}),c+=h[s];else if(2==m)f.push({name:o,type:s,offset:c});else if(3==m){const t=new DataView(e,d,2*h.float);g.safeOrbitCameraElevationMinMax=[t.getFloat32(0,!0),t.getFloat32(4,!0)]}else if(4==m){const t=new DataView(e,d,h.float);g.safeOrbitCameraRadiusMin=t.getFloat32(0,!0)}else if(5==m){const t=new DataView(e,d,h.uchar);"up_axis"==o?g.upAxis=0==t.getUint8(0)?"X":1==t.getUint8(0)?"Y":"Z":"chirality"==o&&(g.chirality=0==t.getUint8(0)?"LeftHanded":"RightHanded")}h[s]||t.Logger.Warn(`Unsupported property type: ${s}.`)}else if(n.startsWith("element ")){const[,e]=n.split(" ");"chunk"==e?m=1:"vertex"==e?m=0:"sh"==e?m=2:"safe_orbit_camera_elevation_min_max_radians"==e?m=3:"safe_orbit_camera_radius_min"==e?m=4:"up_axis"!=e&&"chirality"!=e||(m=5)}const y=c,v=d;return t.GaussianSplattingMesh.ConvertPLYWithSHToSplatAsync(e).then(t=>b(this,void 0,void 0,function*(){const n=new DataView(e,o+11);let s=v*u+y*r;const i=[];if(a)for(let e=0;e<a;e++){const e=n.getUint8(s);if(3==e){s+=1;for(let t=0;t<e;t++){const e=n.getUint32(s+4*(2-t),!0);i.push(e)}s+=12}}if(u)return yield new Promise(e=>{e({mode:0,data:t.buffer,sh:t.sh,shDegree:t.shDegree,faces:i,hasVertexColors:!1,compressed:!0,rawSplat:!1})});let l=0,c=0;const d=["x","y","z","scale_0","scale_1","scale_2","opacity","rot_0","rot_1","rot_2","rot_3"],h=["red","green","blue","f_dc_0","f_dc_1","f_dc_2"];for(let e=0;e<f.length;e++){const t=f[e];d.includes(t.name)&&l++,h.includes(t.name)&&c++}const m=l==d.length&&c>=3,p=a?2:m?0:1;return yield new Promise(e=>{e(Object.assign(Object.assign({},g),{mode:p,data:t.buffer,sh:t.sh,shDegree:t.shDegree,faces:i,hasVertexColors:!!c,compressed:!1,rawSplat:!1}))})}))}}Lu._DefaultLoadingOptions={keepInRam:!1,flipY:!1,needsRotationScaleTextures:!1,spzLibraryUrl:"object"==typeof WebAssembly?"https://unpkg.com/@adobe/spz@0.2.2/dist/spz.js":void 0};let Pu=!1;function Bu(){Pu||(Pu=!0,t.RegisterSceneLoaderPlugin(new Lu))}Bu();var Nu={__proto__:null,RegisterSPLATFileLoader:Bu,SPLATFileLoader:Lu};function ku(){t.RegisterSceneLoaderPlugin(Object.assign(Object.assign({},f),{createPlugin:e=>b(this,void 0,void 0,function*(){const{BVHFileLoader:t}=yield Promise.resolve().then(function(){return y});return new t(e[f.name])})})),t.RegisterSceneLoaderPlugin(Object.assign(Object.assign({},Nt),{createPlugin:e=>b(this,void 0,void 0,function*(){const{FBXFileLoader:t}=yield Promise.resolve().then(function(){return Zt});return new t(e[Nt.name])})})),t.RegisterSceneLoaderPlugin(Object.assign(Object.assign({},on),{createPlugin:e=>b(this,void 0,void 0,function*(){const{GLTFFileLoader:t}=yield Promise.resolve().then(function(){return Rs});return new t(e[on.name])})})),function(){ns("EXT_lights_image_based"),ts("EXT_lights_image_based",!0,e=>b(this,void 0,void 0,function*(){const{EXT_lights_image_based:t}=yield Promise.resolve().then(function(){return $s});return new t(e)})),ns("EXT_mesh_gpu_instancing"),ts("EXT_mesh_gpu_instancing",!0,e=>b(this,void 0,void 0,function*(){const{EXT_mesh_gpu_instancing:t}=yield Promise.resolve().then(function(){return js});return new t(e)})),ns("EXT_meshopt_compression"),ts("EXT_meshopt_compression",!0,e=>b(this,void 0,void 0,function*(){const{EXT_meshopt_compression:t}=yield Promise.resolve().then(function(){return Js});return new t(e)})),ns("EXT_texture_avif"),ts("EXT_texture_avif",!0,e=>b(this,void 0,void 0,function*(){const{EXT_texture_avif:t}=yield Promise.resolve().then(function(){return uo});return new t(e)})),ns("EXT_texture_webp"),ts("EXT_texture_webp",!0,e=>b(this,void 0,void 0,function*(){const{EXT_texture_webp:t}=yield Promise.resolve().then(function(){return oo});return new t(e)})),ns("ExtrasAsMetadata"),ts("ExtrasAsMetadata",!1,e=>b(this,void 0,void 0,function*(){const{ExtrasAsMetadata:t}=yield Promise.resolve().then(function(){return Vl});return new t(e)})),ns("KHR_animation_pointer"),ts("KHR_animation_pointer",!0,e=>b(this,void 0,void 0,function*(){const{KHR_animation_pointer:t}=yield Promise.resolve().then(function(){return xa});return new t(e)})),ns("KHR_draco_mesh_compression"),ts("KHR_draco_mesh_compression",!0,e=>b(this,void 0,void 0,function*(){const{KHR_draco_mesh_compression:t}=yield Promise.resolve().then(function(){return bo});return new t(e)})),ns("KHR_gaussian_splatting"),ts("KHR_gaussian_splatting",!0,e=>b(this,void 0,void 0,function*(){const{KHR_gaussian_splatting:t}=yield Promise.resolve().then(function(){return So});return new t(e)})),ns("KHR_interactivity"),ts("KHR_interactivity",!0,e=>b(this,void 0,void 0,function*(){const{KHR_interactivity:t}=yield Promise.resolve().then(function(){return yl});return new t(e)})),ns("KHR_lights_punctual"),ts("KHR_lights_punctual",!0,e=>b(this,void 0,void 0,function*(){const{KHR_lights:t}=yield Promise.resolve().then(function(){return Lo});return new t(e)})),ns("EXT_lights_area"),ts("EXT_lights_area",!0,e=>b(this,void 0,void 0,function*(){const{EXT_lights_area:t}=yield Promise.resolve().then(function(){return Do});return new t(e)})),ns("EXT_lights_ies"),ts("EXT_lights_ies",!0,e=>b(this,void 0,void 0,function*(){const{EXT_lights_ies:t}=yield Promise.resolve().then(function(){return po});return new t(e)})),ns("KHR_materials_anisotropy"),ts("KHR_materials_anisotropy",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_anisotropy:t}=yield Promise.resolve().then(function(){return fr});return new t(e)})),ns("KHR_materials_clearcoat"),ts("KHR_materials_clearcoat",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_clearcoat:t}=yield Promise.resolve().then(function(){return Jo});return new t(e)})),ns("KHR_materials_diffuse_roughness"),ts("KHR_materials_diffuse_roughness",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_diffuse_roughness:t}=yield Promise.resolve().then(function(){return Ti});return new t(e)})),ns("KHR_materials_diffuse_transmission"),ts("KHR_materials_diffuse_transmission",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_diffuse_transmission:t}=yield Promise.resolve().then(function(){return ni});return new t(e)})),ns("KHR_materials_dispersion"),ts("KHR_materials_dispersion",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_dispersion:t}=yield Promise.resolve().then(function(){return gi});return new t(e)})),ns("KHR_materials_emissive_strength"),ts("KHR_materials_emissive_strength",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_emissive_strength:t}=yield Promise.resolve().then(function(){return vr});return new t(e)})),ns("KHR_materials_ior"),ts("KHR_materials_ior",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_ior:t}=yield Promise.resolve().then(function(){return Gr});return new t(e)})),ns("KHR_materials_iridescence"),ts("KHR_materials_iridescence",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_iridescence:t}=yield Promise.resolve().then(function(){return ur});return new t(e)})),ns("KHR_materials_pbrSpecularGlossiness"),ts("KHR_materials_pbrSpecularGlossiness",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_pbrSpecularGlossiness:t}=yield Promise.resolve().then(function(){return $o});return new t(e)})),ns("KHR_materials_sheen"),ts("KHR_materials_sheen",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_sheen:t}=yield Promise.resolve().then(function(){return Mr});return new t(e)})),ns("KHR_materials_specular"),ts("KHR_materials_specular",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_specular:t}=yield Promise.resolve().then(function(){return Pr});return new t(e)})),ns("KHR_materials_transmission"),ts("KHR_materials_transmission",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_transmission:t}=yield Promise.resolve().then(function(){return Qr});return new t(e)})),ns("KHR_materials_unlit"),ts("KHR_materials_unlit",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_unlit:t}=yield Promise.resolve().then(function(){return jo});return new t(e)})),ns("KHR_materials_variants"),ts("KHR_materials_variants",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_variants:t}=yield Promise.resolve().then(function(){return Ur});return new t(e)})),ns("KHR_materials_volume"),ts("KHR_materials_volume",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_volume:t}=yield Promise.resolve().then(function(){return ai});return new t(e)})),ns("KHR_mesh_quantization"),ts("KHR_mesh_quantization",!0,e=>b(this,void 0,void 0,function*(){const{KHR_mesh_quantization:t}=yield Promise.resolve().then(function(){return Ri});return new t(e)})),ns("KHR_texture_basisu"),ts("KHR_texture_basisu",!0,e=>b(this,void 0,void 0,function*(){const{KHR_texture_basisu:t}=yield Promise.resolve().then(function(){return Ii});return new t(e)})),ns("KHR_texture_transform"),ts("KHR_texture_transform",!0,e=>b(this,void 0,void 0,function*(){const{KHR_texture_transform:t}=yield Promise.resolve().then(function(){return ki});return new t(e)})),ns("KHR_xmp_json_ld"),ts("KHR_xmp_json_ld",!0,e=>b(this,void 0,void 0,function*(){const{KHR_xmp_json_ld:t}=yield Promise.resolve().then(function(){return Ki});return new t(e)})),ns("MSFT_audio_emitter"),ts("MSFT_audio_emitter",!0,e=>b(this,void 0,void 0,function*(){const{MSFT_audio_emitter:t}=yield Promise.resolve().then(function(){return Ca});return new t(e)})),ns("MSFT_lod"),ts("MSFT_lod",!0,e=>b(this,void 0,void 0,function*(){const{MSFT_lod:t}=yield Promise.resolve().then(function(){return Ea});return new t(e)})),ns("MSFT_minecraftMesh"),ts("MSFT_minecraftMesh",!0,e=>b(this,void 0,void 0,function*(){const{MSFT_minecraftMesh:t}=yield Promise.resolve().then(function(){return Na});return new t(e)})),ns("MSFT_sRGBFactors"),ts("MSFT_sRGBFactors",!0,e=>b(this,void 0,void 0,function*(){const{MSFT_sRGBFactors:t}=yield Promise.resolve().then(function(){return Ha});return new t(e)})),ns("KHR_node_visibility"),ts("KHR_node_visibility",!0,e=>b(this,void 0,void 0,function*(){const{KHR_node_visibility:t}=yield Promise.resolve().then(function(){return Al});return new t(e)})),ns("KHR_node_hoverability"),ts("KHR_node_hoverability",!0,e=>b(this,void 0,void 0,function*(){const{KHR_node_hoverability:t}=yield Promise.resolve().then(function(){return Bl});return new t(e)})),ns("KHR_node_selectability"),ts("KHR_node_selectability",!0,e=>b(this,void 0,void 0,function*(){const{KHR_node_selectability:t}=yield Promise.resolve().then(function(){return Sl});return new t(e)})),ns("KHR_materials_coat"),ts("KHR_materials_coat",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_coat:t}=yield Promise.resolve().then(function(){return or});return new t(e)})),ns("KHR_materials_fuzz"),ts("KHR_materials_fuzz",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_fuzz:t}=yield Promise.resolve().then(function(){return Or});return new t(e)})),ns("KHR_materials_volume_scatter"),ts("KHR_materials_volume_scatter",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_volume_scatter:t}=yield Promise.resolve().then(function(){return hi});return new t(e)}))}(),t.RegisterSceneLoaderPlugin(Object.assign(Object.assign({},zl),{createPlugin:e=>b(this,void 0,void 0,function*(){const{OBJFileLoader:t}=yield Promise.resolve().then(function(){return Ql});return new t(e[zl.name])})})),t.RegisterSceneLoaderPlugin(Object.assign(Object.assign({},ru),{createPlugin:e=>b(this,void 0,void 0,function*(){const{SPLATFileLoader:t}=yield Promise.resolve().then(function(){return Nu});return new t(e[ru.name])})})),t.RegisterSceneLoaderPlugin(Object.assign(Object.assign({},Jl),{createPlugin:()=>b(this,void 0,void 0,function*(){const{STLFileLoader:e}=yield Promise.resolve().then(function(){return su});return new e})}))}var Du={__proto__:null,registerBuiltInLoaders:ku};const Gu="undefined"!=typeof global?global:"undefined"!=typeof window?window:void 0;if(void 0!==Gu)for(const e in v)Gu.BABYLON[e]||(Gu.BABYLON[e]=v[e]);const Vu="undefined"!=typeof global?global:"undefined"!=typeof window?window:void 0;if(void 0!==Vu){Vu.BABYLON=Vu.BABYLON||{};for(const e in Du)Vu.BABYLON[e]=Du[e]}const Hu="undefined"!=typeof global?global:"undefined"!=typeof window?window:void 0;if(void 0!==Hu){Hu.BABYLON=Hu.BABYLON||{};for(const e in wn)Hu.BABYLON[e]=wn[e];for(const e in nn)Hu.BABYLON[e]=nn[e]}const Ku="undefined"!=typeof global?global:"undefined"!=typeof window?window:void 0;if(void 0!==Ku){Ku.BABYLON=Ku.BABYLON||{},Ku.BABYLON.GLTF1=Ku.BABYLON.GLTF1||{};for(const e in Zn)Ku.BABYLON.GLTF1[e]=Zn[e]}const $u=Object.assign({},$l),Uu=Object.assign(Object.assign({},{__proto__:null}),{Extensions:$u}),qu=Object.assign(Object.assign({},Ul),{Loader:Uu}),Wu="undefined"!=typeof global?global:"undefined"!=typeof window?window:void 0;if(void 0!==Wu){Wu.BABYLON=Wu.BABYLON||{};const e=Wu.BABYLON;e.GLTF2=e.GLTF2||{},e.GLTF2.Loader=e.GLTF2.Loader||{},e.GLTF2.Loader.Extensions=e.GLTF2.Loader.Extensions||{};const t=["Loader"];for(const n in $u)e.GLTF2.Loader.Extensions[n]=$u[n],t.push(n);for(const n in Uu)"Extensions"!==n&&(e.GLTF2.Loader[n]=Uu[n],t.push(n));for(const n in qu)t.indexOf(n)>-1||(e.GLTF2[n]=qu[n])}const zu="undefined"!=typeof global?global:"undefined"!=typeof window?window:void 0;if(void 0!==zu)for(const e in Zl)zu.BABYLON[e]||(zu.BABYLON[e]=Zl[e]);const ju="undefined"!=typeof global?global:"undefined"!=typeof window?window:void 0;if(void 0!==ju)for(const e in ou)ju.BABYLON[e]||(ju.BABYLON[e]=ou[e]);e.AddGaussianSplattingStreamPart=function(e,t,n,s,o={}){return new Ou(t,n,s,e.getScene(),Object.assign(Object.assign({},o),{hostCompound:e}))},e.AddGaussianSplattingStreamPartAsync=function(e,t,n,s){return b(this,arguments,void 0,function*(e,t,n,s,o={}){const r=new Ou(t,n,s,e.getScene(),Object.assign(Object.assign({},o),{hostCompound:e}));try{yield r.whenPartReadyAsync()}catch(e){throw r.dispose(),e}const i=r.streamingPartProxy;if(!i)throw r.dispose(),new Error("GaussianSplattingStream: streaming part was not reserved.");return i})},e.BVHFileLoader=p,e.FBXFileLoader=kt,e.FBXFileLoaderMetadata=Nt,e.GLTF1=Zn,e.GLTF2=qu,e.GLTFFileLoader=mn,e.GLTFLoaderDefaultOptions=dn,e.GLTFValidation=tn,e.GaussianSplattingStream=Ou,e.MTLFileLoader=ql,e.OBJFileLoader=jl,e.ReadBvh=m,e.RegisterBVHFileLoader=g,e.RegisterGLTFFileLoader=pn,e.RegisterOBJFileLoader=Yl,e.RegisterSPLATFileLoader=Bu,e.RegisterSTLFileLoader=nu,e.SPLATFileLoader=Lu,e.STLFileLoader=eu,e.SolidParser=Wl,e.registerBuiltInLoaders=ku});
|
|
1
|
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("babylonjs")):"function"==typeof define&&define.amd?define(["exports","babylonjs"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).BABYLON=e.BABYLON||{},e.BABYLON)}(this,function(e,t){"use strict";const n="Xposition",s="Yposition",o="Zposition",r="Xrotation",i="Yrotation",a="Zrotation";class l{constructor(e){this.loopMode=t.Animation.ANIMATIONLOOPMODE_CYCLE,this.list=[],this.root=u(),this.numFrames=0,this.frameRate=0,this.skeleton=e}}function u(){return{name:"",type:"",offset:new t.Vector3,channels:[],children:[],frames:[],parent:null}}function c(e,l,u){const d=function(e){const n=e.offset.x,s=e.offset.y,o=e.offset.z;return t.Matrix.Translation(n,s,o)}(e),h=new t.Bone(e.name,u.skeleton,l,d),m=function(e,l){if(0===e.frames.length)return[];const u=[],c=e.channels.some(e=>e===n||e===s||e===o),d=e.channels.some(e=>e===r||e===i||e===a),h=new t.Animation(`${e.name}_pos`,"position",l.frameRate,t.Animation.ANIMATIONTYPE_VECTOR3,l.loopMode),m=new t.Animation(`${e.name}_rot`,"rotationQuaternion",l.frameRate,t.Animation.ANIMATIONTYPE_QUATERNION,l.loopMode),f=[],p=[];for(let t=0;t<e.frames.length;t++){const n=e.frames[t];c&&n.position&&f.push({frame:n.frame,value:n.position.clone()}),d&&p.push({frame:n.frame,value:n.rotation.clone()})}return f.length>0&&(h.setKeys(f),u.push(h)),p.length>0&&(m.setKeys(p),u.push(m)),u}(e,u);for(const e of m)e.getKeys()&&e.getKeys().length>0&&h.animations.push(e);for(const t of e.children)c(t,h,u)}function d(e,l,u,c){if("ENDSITE"===u.type)return;const h={frame:0,position:new t.Vector3,rotation:new t.Quaternion};h.frame=l,h.position=new t.Vector3,h.rotation=new t.Quaternion,u.frames.push(h);let m=t.Matrix.Identity();for(let l=0;l<u.channels.length;++l){const d=u.channels[l],f=e[c.i++];if(!f)continue;const p=parseFloat(f.trim());if(d.endsWith("position"))switch(d){case n:h.position.x=p;break;case s:h.position.y=p;break;case o:h.position.z=p}else if(d.endsWith("rotation")){const e=t.Tools.ToRadians(p);let n;switch(d){case r:n=t.Matrix.RotationX(e);break;case i:n=t.Matrix.RotationY(e);break;case a:n=t.Matrix.RotationZ(e)}m=n.multiply(m)}}t.Quaternion.FromRotationMatrixToRef(m,h.rotation);for(const t of u.children)d(e,l,t,c)}function h(e,n,s,o){var r,i,a,l;const c=u();c.parent=s,o.list.push(c);let d=n.trim().split(/\s+/);if("END"===d[0].toUpperCase()&&"SITE"===d[1].toUpperCase()?(c.type="ENDSITE",c.name="ENDSITE"):(c.name=d[1],c.type=d[0].toUpperCase()),"{"!=(null===(r=e.shift())||void 0===r?void 0:r.trim()))throw new Error("Expected opening { after type & name");const m=null===(i=e.shift())||void 0===i?void 0:i.trim().split(/\s+/);if(!m)throw new Error("Unexpected end of file: missing OFFSET");if(d=m,"OFFSET"!=d[0].toUpperCase())throw new Error("Expected OFFSET, but got: "+d[0]);if(4!=d.length)throw new Error("OFFSET: Invalid number of values");const f=new t.Vector3(parseFloat(d[1]),parseFloat(d[2]),parseFloat(d[3]));if(isNaN(f.x)||isNaN(f.y)||isNaN(f.z))throw new Error("OFFSET: Invalid values");if(c.offset=f,"ENDSITE"!=c.type){if(d=null===(a=e.shift())||void 0===a?void 0:a.trim().split(/\s+/),!d)throw new Error("Unexpected end of file: missing CHANNELS");if("CHANNELS"!=d[0].toUpperCase())throw new Error("Expected CHANNELS definition");const t=parseInt(d[1]);c.channels=d.splice(2,t),c.children=[]}for(;e.length>0;){const t=null===(l=e.shift())||void 0===l?void 0:l.trim();if("}"===t)return c;t&&c.children.push(h(e,t,c,o))}throw new Error("Unexpected end of file: missing closing brace")}function m(e,n,s,o){const r=e.split("\n"),{loopMode:i}=o;n._blockEntityCollection=!!s;const a=new t.Skeleton("","",n);a._parentContainer=s,n._blockEntityCollection=!1;const u=new l(a);u.loopMode=i;const m=r.shift();if(!m||"HIERARCHY"!==m.trim().toUpperCase())throw new Error("HIERARCHY expected");const f=r.shift();if(!f)throw new Error("Unexpected end of file after HIERARCHY");const p=h(r,f.trim(),null,u),_=r.shift();if(!_||"MOTION"!==_.trim().toUpperCase())throw new Error("MOTION expected");const g=r.shift();if(!g)throw new Error("Unexpected end of file before frame count");const y=g.trim().split(/[\s]+/);if(y.length<2)throw new Error("Invalid frame count line");const v=parseInt(y[1]);if(isNaN(v))throw new Error("Failed to read number of frames.");u.numFrames=v;const b=r.shift();if(!b)throw new Error("Unexpected end of file before frame time");const x=b.trim().split(/[\s]+/);if(x.length<3)throw new Error("Invalid frame time line");const T=parseFloat(x[2]);if(isNaN(T))throw new Error("Failed to read frame time.");if(T<=0)throw new Error("Failed to read frame time. Invalid value "+T);u.frameRate=1/T;for(let e=0;e<v;++e){const t=r.shift();t&&d(t.trim().split(/[\s]+/)||[],e,p,{i:0})}return u.root=p,c(u.root,null,u),u.skeleton.returnToRest(),u.skeleton}const f={name:"bvh",extensions:{".bvh":{isBinary:!1}}};class p{constructor(e){this.name=f.name,this.extensions=f.extensions,this._loadingOptions=Object.assign(Object.assign({},p._DefaultLoadingOptions),null!=e?e:{})}static get _DefaultLoadingOptions(){return{loopMode:t.Animation.ANIMATIONLOOPMODE_CYCLE}}createPlugin(e){return new p(e[f.name])}canDirectLoad(e){return this.isBvhHeader(e)}isBvhHeader(e){return"HIERARCHY"==e.split("\n")[0]}isNotBvhHeader(e){return!this.isBvhHeader(e)}importMeshAsync(e,t,n){if("string"!=typeof n)return Promise.reject("BVH loader expects string data.");if(this.isNotBvhHeader(n))return Promise.reject("BVH loader expects HIERARCHY header.");try{const e=m(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"string"!=typeof t?Promise.reject("BVH loader expects string data."):this.isNotBvhHeader(t)?Promise.reject("BVH loader expects HIERARCHY header."):this.importMeshAsync(null,e,t).then(()=>{})}loadAssetContainerAsync(e,n){if("string"!=typeof n)return Promise.reject("BVH loader expects string data.");if(this.isNotBvhHeader(n))return Promise.reject("BVH loader expects HIERARCHY header.");const s=new t.AssetContainer(e);try{const t=m(n,e,s,this._loadingOptions);return s.skeletons.push(t),Promise.resolve(s)}catch(e){return Promise.reject(e)}}}let _=!1;function g(){_||(_=!0,t.RegisterSceneLoaderPlugin(new p))}g();var y={__proto__:null,BVHFileLoader:p,RegisterBVHFileLoader:g},v={__proto__:null,BVHFileLoader:p,ReadBvh:m,RegisterBVHFileLoader:g};function b(e,t,n,s){return new(n||(n=Promise))(function(o,r){function i(e){try{l(s.next(e))}catch(e){r(e)}}function a(e){try{l(s.throw(e))}catch(e){r(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(i,a)}l((s=s.apply(e,t||[])).next())})}Object.create,Object.create,"function"==typeof SuppressedError&&SuppressedError;const x=[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],T=[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],A=[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],M=[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],w=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];class C{constructor(e,t,n){this.input=e,this.byteOffset=t,this.endOffset=n,this.bitBuffer=0,this.bitCount=0}readBits(e){this.ensureBits(e);const t=this.bitBuffer&(1<<e)-1;return this.bitBuffer>>>=e,this.bitCount-=e,t}readBit(){if(0===this.bitCount){if(this.byteOffset>=this.endOffset)throw new Error("zlib: unexpected end of input");this.bitBuffer=this.input[this.byteOffset++],this.bitCount=8}const e=1&this.bitBuffer;return this.bitBuffer>>>=1,this.bitCount--,e}alignToByte(){this.bitBuffer=0,this.bitCount=0}readUint16LE(){if(this.ensureByteAligned(),this.byteOffset+2>this.endOffset)throw new Error("zlib: unexpected end of input");const 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 new Error("zlib: unexpected end of input");return this.input[this.byteOffset++]}ensureByteAligned(){if(0!==this.bitCount)throw new Error("deflate: expected byte alignment")}ensureBits(e){for(;this.bitCount<e;){if(this.byteOffset>=this.endOffset)throw new Error("zlib: unexpected end of input");this.bitBuffer|=this.input[this.byteOffset++]<<this.bitCount,this.bitCount+=8}}}class R{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 new Error("zlib: output length mismatch");const t=255&e;this.bytes[this.offset++]=t,this.adlerA+=t,this.adlerB+=this.adlerA,this.adlerA%=65521,this.adlerB%=65521}copy(e,t){if(e<=0||e>this.offset)throw new 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 new Error("zlib: output length mismatch")}adler32(){return(this.adlerB<<16|this.adlerA)>>>0}}class S{constructor(e,t={}){const n=new Array(16).fill(0);let s=0,o=0;for(const t of e){if(!Number.isInteger(t)||t<0||t>15)throw new Error("deflate: invalid huffman code lengths");t>0&&(n[t]++,s++,o=Math.max(o,t))}if(0===s){if(t.allowEmpty)return this.symbolsByLength=[],void(this.maxCodeLength=0);throw new Error("deflate: invalid huffman code lengths")}let r=1;for(let e=1;e<=15;e++)if(r=(r<<1)-n[e],r<0)throw new Error("deflate: invalid huffman code lengths");if(0!==r&&1!==s)throw new Error("deflate: invalid huffman code lengths");const i=new Array(16).fill(0);let a=0;for(let e=1;e<=15;e++)a=a+n[e-1]<<1,i[e]=a;this.symbolsByLength=Array.from({length:16},(e,t)=>{if(0===n[t])return;const s=new Int16Array(1<<t);return s.fill(-1),s});for(let t=0;t<e.length;t++){const n=e[t];0!==n&&(this.symbolsByLength[n][i[n]++]=t)}this.maxCodeLength=o}decode(e){var t,n;if(0===this.maxCodeLength)throw new Error("deflate: invalid huffman code");let s=0;for(let o=1;o<=this.maxCodeLength;o++){s=s<<1|e.readBit();const r=null!==(n=null===(t=this.symbolsByLength[o])||void 0===t?void 0:t[s])&&void 0!==n?n:-1;if(r>=0)return r}throw new Error("deflate: invalid huffman code")}}let O,F;function E(){if(!O){const e=new 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;O=new S(e)}return O}function I(){return F||(F=new S(new Array(32).fill(5))),F}function L(e,t){e.alignToByte();const n=e.readUint16LE();if(65535&(n^~e.readUint16LE()))throw new Error("deflate: invalid stored block length");for(let s=0;s<n;s++)t.writeByte(e.readByte())}function P(e,t,n,s){for(;;){const o=n.decode(e);if(o<256){t.writeByte(o);continue}if(256===o)return;if(o>285)throw new Error("deflate: invalid literal/length symbol");const r=o-257,i=x[r]+e.readBits(T[r]),a=s.decode(e);if(a>29)throw new Error("deflate: invalid distance symbol");const l=A[a]+e.readBits(M[a]);t.copy(l,i)}}function B(e){const t=e.readBits(5)+257,n=e.readBits(5)+1,s=e.readBits(4)+4,o=new Array(19).fill(0);for(let t=0;t<s;t++)o[w[t]]=e.readBits(3);const r=function(e,t,n){const s=[];for(;s.length<n;){const o=t.decode(e);if(o<=15){s.push(o);continue}let r,i;switch(o){case 16:if(0===s.length)throw new Error("deflate: invalid code length repeat");i=s[s.length-1],r=e.readBits(2)+3;break;case 17:i=0,r=e.readBits(3)+3;break;case 18:i=0,r=e.readBits(7)+11;break;default:throw new Error("deflate: invalid code length symbol")}if(s.length+r>n)throw new Error("deflate: invalid code length repeat");for(let e=0;e<r;e++)s.push(i)}return s}(e,new S(o),t+n),i=r.slice(0,t),a=r.slice(t);if(0===i[256])throw new Error("deflate: missing end-of-block code");return{literalLengthTree:new S(i),distanceTree:new S(a,{allowEmpty:!0})}}function N(e,t,n,s,o){let r,i,a,l;if(s?(G(t,n,25,o,"FBX node header"),r=V(e,n),i=V(e,n+8),a=V(e,n+16),l=25):(G(t,n,13,o,"FBX node header"),r=e.getUint32(n,!0),i=e.getUint32(n+4,!0),a=e.getUint32(n+8,!0),l=13),0===r)return null;if(r<=n||r>o)throw new Error(`Invalid FBX node end offset ${r} at offset ${n}`);const u=t[n+l-1];G(t,n+l,u,r,"FBX node name");const c=K(t,n+l,u);let d=n+l+u;const h=d+a;if(h>r)throw new Error(`Invalid FBX property list length for node '${c}' at offset ${n}`);const m=[];for(let n=0;n<i;n++){const n=k(e,t,d,h);m.push(n.property),d=n.nextOffset}if(d!==h)throw new Error(`Invalid FBX property list length for node '${c}' at offset ${n}`);const f=[];if(d<r)for(;d<r;){const n=N(e,t,d,s,r);if(null===n)break;if(n.endOffset<=d||n.endOffset>r)throw new Error(`Invalid FBX child node end offset ${n.endOffset} at offset ${d}`);f.push(n.node),d=n.endOffset}return{node:{name:c,properties:m,children:f},endOffset:r}}function k(e,t,n,s){G(t,n,1,s,"FBX property type");const o=String.fromCharCode(t[n]);switch(n+=1,o){case"C":return G(t,n,1,s,"FBX boolean property"),{property:{type:"boolean",value:0!==t[n]},nextOffset:n+1};case"Y":return G(t,n,2,s,"FBX int16 property"),{property:{type:"int16",value:e.getInt16(n,!0)},nextOffset:n+2};case"I":return G(t,n,4,s,"FBX int32 property"),{property:{type:"int32",value:e.getInt32(n,!0)},nextOffset:n+4};case"F":return G(t,n,4,s,"FBX float32 property"),{property:{type:"float32",value:e.getFloat32(n,!0)},nextOffset:n+4};case"D":return G(t,n,8,s,"FBX float64 property"),{property:{type:"float64",value:e.getFloat64(n,!0)},nextOffset:n+8};case"L":return G(t,n,8,s,"FBX int64 property"),{property:{type:"int64",value:H(e,n)},nextOffset:n+8};case"S":{G(t,n,4,s,"FBX string property length");const o=e.getUint32(n,!0);G(t,n+4,o,s,"FBX string property data");const r=function(e,t,n){return new TextDecoder("utf-8").decode(e.subarray(t,t+n))}(t,n+4,o);return{property:{type:"string",value:r},nextOffset:n+4+o}}case"R":{G(t,n,4,s,"FBX raw property length");const o=e.getUint32(n,!0);return G(t,n+4,o,s,"FBX raw property data"),{property:{type:"raw",value:t.slice(n+4,n+4+o)},nextOffset:n+4+o}}case"f":return D(e,t,n,"float32[]",4,s);case"d":return D(e,t,n,"float64[]",8,s);case"i":return D(e,t,n,"int32[]",4,s);case"l":return D(e,t,n,"int64[]",8,s);case"b":return D(e,t,n,"boolean[]",1,s);default:throw new Error(`Unknown FBX property type: '${o}' at offset ${n-1}`)}}function D(e,t,n,s,o,r){G(t,n,12,r,`FBX array property header for ${s}`);const i=e.getUint32(n,!0),a=e.getUint32(n+4,!0),l=e.getUint32(n+8,!0),u=i*o;let c;if(G(t,n+=12,l,r,`FBX array property data for ${s}`),1===a)c=function(e,t){if(!Number.isInteger(t)||t<0)throw new Error("zlib: invalid expected length");if(e.byteLength<6)throw new Error("zlib: unexpected end of input");const n=e[0],s=e[1];if(8!=(15&n)||n>>4>7||((n<<8)+s)%31!=0)throw new Error("zlib: invalid header");if(32&s)throw new Error("zlib: preset dictionary not supported");const o=new C(e,2,e.byteLength-4),r=new R(t);let i=!1;for(;!i;)switch(i=1===o.readBits(1),o.readBits(2)){case 0:L(o,r);break;case 1:P(o,r,E(),I());break;case 2:{const{literalLengthTree:e,distanceTree:t}=B(o);P(o,r,e,t);break}default:throw new Error("deflate: invalid block type")}if(o.byteOffset<e.byteLength-4)throw new Error("zlib: trailing deflate data");r.finish();const a=(e[e.byteLength-4]<<24|e[e.byteLength-3]<<16|e[e.byteLength-2]<<8|e[e.byteLength-1])>>>0;if(r.adler32()!==a)throw new Error("zlib: adler32 mismatch");return r.bytes}(t.subarray(n,n+l),u);else{if(0!==a)throw new Error(`Unsupported FBX array encoding: ${a}`);if(l!==u)throw new Error(`Invalid FBX array byte length for ${s}`);c=t.slice(n,n+l)}const d=c.buffer.slice(c.byteOffset,c.byteOffset+c.byteLength);let h;switch(s){case"float32[]":h=new Float32Array(d);break;case"float64[]":h=new Float64Array(d);break;case"int32[]":h=new Int32Array(d);break;case"boolean[]":h=c;break;case"int64[]":h=function(e){const 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]=H(t,8*e);return n}(c);break;default:throw new Error(`Unexpected array type: ${s}`)}return{property:{type:s,value:h},nextOffset:n+l}}function G(e,t,n,s,o){if(t<0||n<0||t+n>s||t+n>e.byteLength)throw new Error(`${o}: unexpected end of input`)}function V(e,t){const n=e.getUint32(t,!0);return 4294967296*e.getUint32(t+4,!0)+n}function H(e,t){const n=e.getUint32(t,!0);return 4294967296*e.getInt32(t+4,!0)+n}function K(e,t,n){let s="";for(let o=0;o<n;o++)s+=String.fromCharCode(e[t+o]);return s}function $(e){const t=new q(e),n=function(e){const t=e.match(/;\s*FBX\s+(\d+)\.(\d+)\.(\d+)/);if(!t)throw new Error("Cannot determine FBX version from ASCII header");return 1e3*parseInt(t[1])+100*parseInt(t[2])+parseInt(t[3])}(e),s=[];for(;!t.isEOF()&&(t.skipWhitespaceAndComments(),!t.isEOF());){const e=W(t);e&&s.push(e)}return{version:n,nodes:s}}var U;!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"}(U||(U={}));let q=class{constructor(e){this.text=e,this.pos=0,this.len=e.length}isEOF(){return this.skipWhitespaceAndComments(),this.pos>=this.len}peek(){const 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};const 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 new Error(`Unexpected character '${e}' at position ${this.pos}`)}}expect(e){const t=this.next();if(t.type!==e)throw new Error(`Expected token type ${e} but got ${t.type} ('${t.value}') at pos ${t.pos}`);return t}isNextNodeStart(){const 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]||"\t"===this.text[this.pos]);)this.pos++;const 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;){const e=this.text[this.pos];if(" "===e||"\t"===e||"\r"===e||"\n"===e)this.pos++;else{if(";"!==e)break;for(;this.pos<this.len&&"\n"!==this.text[this.pos];)this.pos++}}}readString(){const 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]):t+=this.text[this.pos],this.pos++;return this.pos<this.len&&this.pos++,{type:2,value:t,pos:e}}readNumber(){const e=this.pos;for("-"!==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.isDigit(this.text[this.pos]);)this.pos++;if(this.pos<this.len&&("e"===this.text[this.pos]||"E"===this.text[this.pos]))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++;return{type:1,value:this.text.substring(e,this.pos),pos:e}}readIdentifier(){const e=this.pos;for(;this.pos<this.len&&this.isIdentChar(this.text[this.pos]);)this.pos++;return{type:0,value:this.text.substring(e,this.pos),pos:e}}isDigit(e){return e>="0"&&e<="9"}isNumberStart(e){return!!this.isDigit(e)||("-"===e||"+"===e)&&this.pos+1<this.len&&(this.isDigit(this.text[this.pos+1])||"."===this.text[this.pos+1])}isIdentStart(e){return e>="a"&&e<="z"||e>="A"&&e<="Z"||"_"===e}isIdentChar(e){return this.isIdentStart(e)||this.isDigit(e)||"|"===e}};function W(e){const t=e.peek();if(4===t.type||8===t.type)return null;const n=e.next();if(0!==n.type)throw new Error(`Expected identifier for node name, got '${n.value}' at pos ${n.pos}`);const s=n.value;e.expect(5);const o=[],r=[];let i=e.peek();if(7===i.type){e.next();const t=e.expect(1),n=parseInt(t.value);e.expect(3);const i=e.next();if(0===i.type&&"a"===i.value){e.expect(5);const t=function(e,t){const n=[];for(;;){const t=e.peek();if(4===t.type||8===t.type)break;if(6!==t.type){if(1!==t.type)break;{const t=e.next();n.push(Number(t.value))}}else e.next()}if(n.length!==t)throw new Error(`ASCII FBX array declared ${t} values but parsed ${n.length}`);return n}(e,n);o.push({type:"float64[]",value:new Float64Array(t)})}return e.expect(4),{name:s,properties:o,children:r}}for(i=e.peek();3!==i.type&&4!==i.type&&8!==i.type;){if(1===i.type){const t=e.next(),n=z(t.value);!Number.isInteger(n)||t.value.includes(".")||t.value.includes("e")||t.value.includes("E")?o.push({type:"float64",value:n}):o.push({type:j(n)?"int32":"int64",value:n})}else if(2===i.type){const t=e.next();o.push({type:"string",value:t.value})}else if(0===i.type){if(e.isNextNodeStart())break;const t=e.next();o.push({type:"string",value:t.value})}else{if(6!==i.type)break;e.next()}i=e.peek()}if(i=e.peek(),3===i.type){for(e.next();i=e.peek(),4!==i.type&&8!==i.type;){const t=W(e);if(!t)break;r.push(t)}e.expect(4)}return{name:s,properties:o,children:r}}function z(e){return Number(e)}function j(e){return e>=-2147483648&&e<=2147483647}function X(e,t){return e.children.find(e=>e.name===t)}function Y(e,t){return e.nodes.find(e=>e.name===t)}function Q(e,t){if(t<e.properties.length)return e.properties[t].value}function Z(e){const t=e.indexOf("\0");t>=0&&(e=e.substring(0,t));const n=e.indexOf("::");return n>=0&&(e=e.substring(n+2)),e}function J(e,t,n){var s;const o=null!==(s=e.childrenOf.get(t))&&void 0!==s?s:[],r=[];for(const t of o){const s=e.objects.get(t.id);!s||n&&s.name!==n||r.push({id:t.id,node:s,propertyName:t.propertyName})}return r}function ee(e){return function(e){if("number"==typeof e){if(!Number.isSafeInteger(e))throw new Error(`Unsafe FBX object ID ${e.toString()}: object IDs must be safe integers.`);return e}}(e)}function te(e,t){const n=ee(e);if(void 0!==n)return n;if("string"!=typeof e)return;const s=Z(e);return"Scene"===s?0:t.get(s)}function ne(e,t,n,s,o,r,i,a,l){e.push({type:o,childId:r,parentId:i,propertyName:a}),t.has(i)||t.set(i,[]),t.get(i).push({id:r,propertyName:a}),n.get(r)&&s.push({reason:"duplicate-parent",message:"FBX object has multiple parents; preserving the existing last-parent behavior.",connectionIndex:l,type:o,childId:r,parentId:i,propertyName:a}),n.set(r,{id:i,propertyName:a})}function se(e,t){var n,s;const o=Z(null!==(n=Q(e,0))&&void 0!==n?n:e.name),r=null!==(s=Q(e,1))&&void 0!==s?s:"";return Object.assign(Object.assign({},e),{properties:[{type:"int64",value:t},{type:"string",value:o},{type:"string",value:r}]})}function oe(e,t){var n;return{name:"Geometry",properties:[{type:"int64",value:t},{type:"string",value:Z(null!==(n=Q(e,0))&&void 0!==n?n:"Geometry")},{type:"string",value:"Mesh"}],children:e.children}}function re(e,t){var n,s,o;const r=Z(null!==(n=Q(e,1))&&void 0!==n?n:"Geometry"),i=X(e,"Vertices");if(!i)throw new Error(`Geometry '${r}' has no Vertices node`);const a=fe(_e(i)),l=X(e,"PolygonVertexIndex");if(!l)throw new Error(`Geometry '${r}' has no PolygonVertexIndex node`);const u=[],c=function(e){const t=[];let n=[],s=0;for(let o=0;o<e.length;o++){const r=e[o];r<0?(n.push(-(r+1)),t.push({indices:n,startIndex:s}),n=[],s=o+1):n.push(r)}return t}(pe(_e(l))),d=function(e,t,n){const s=[];for(let o=0;o<e.length;o++){const r=e[o];s.push(...ie(r,o,t,n))}return s}(c,a,u),h=function(e){const t=[];for(let n=0;n<e.length;n++){const s=e[n];for(let e=0;e<s.indices.length;e++)t.push({polyIndex:n,vertexInPoly:e,controlPointIndex:s.indices[e],globalIndex:s.startIndex+e})}return t}(c),m=X(e,"LayerElementNormal");let f=null;m&&(f=he(m,"Normals","NormalsIndex",h,a.length,3,u));const p=e.children.filter(e=>"LayerElementUV"===e.name),_=[];for(const e of p){const t=X(e,"Name"),n=t&&null!==(s=Q(t,0))&&void 0!==s?s:`UVSet${_.length}`,o=he(e,"UV","UVIndex",h,a.length,2,u);o&&_.push({name:n,data:o})}const g=_.length>0?_[0].data:null,y=X(e,"LayerElementColor");let v=null;if(y){const e=he(y,"Colors","ColorIndex",h,a.length,4,u);if(e){v=new Float32Array(e.length);for(let t=0;t<e.length;t++)v[t]=e[t]}}const b=X(e,"LayerElementTangent"),x=X(e,"LayerElementBinormal"),T=x?he(x,"Binormals","BinormalsIndex",h,a.length,3,u):null,A=b?function(e,t,n,s,o,r){const i=function(e,t,n,s,o,r){var i,a,l,u;const c=X(e,"Tangents");if(!c)return 3;const d=fe(_e(c)),h=null!==(a=Q(null!==(i=X(e,"MappingInformationType"))&&void 0!==i?i:{name:"",properties:[],children:[]},0))&&void 0!==a?a:"",m=null!==(u=Q(null!==(l=X(e,"ReferenceInformationType"))&&void 0!==l?l:{name:"",properties:[],children:[]},0))&&void 0!==u?u:"",f=X(e,"TangentsIndex"),p=f?pe(_e(f)):null,_="IndexToDirect"===m&&p?Math.max(...Array.from(p),0)+1:"ByControlPoint"===h||"ByVertice"===h?o:"AllSame"===h?1:s.length;if(_>0&&d.length%_===0){const e=d.length/_;if(3===e||4===e)return e}return r.push({type:"layer-data-too-short",message:`Could not infer stride for layer '${e.name}', defaulting to 3.`,layerName:e.name}),3}(e,0,0,t,n,r),a=he(e,"Tangents","TangentsIndex",t,0,i,r);if(!a)return null;const l=new Float64Array(4*t.length);for(let e=0;e<t.length;e++){const t=e*i,n=4*e;l[n]=a[t],l[n+1]=a[t+1],l[n+2]=a[t+2],l[n+3]=i>=4?a[t+3]:me(e,l,s,o)}return l}(b,h,a.length/3,f,T,u):null,M=X(e,"LayerElementMaterial");let w=null;M&&(w=function(e,t){var n,s;const o=X(e,"MappingInformationType"),r=X(e,"ReferenceInformationType");if(!o||!r)return null;const i=null!==(n=Q(o,0))&&void 0!==n?n:"",a=null!==(s=Q(r,0))&&void 0!==s?s:"";if("AllSame"===i){const n=X(e,"Materials"),s=n?pe(_e(n)):null,o=s&&s.length>0?s[0]:0,r=new Int32Array(t);return 0!==o&&r.fill(o),r}if("ByPolygon"===i){const t=X(e,"Materials");if(!t)return null;const n=pe(_e(t));if("Direct"===a||"IndexToDirect"===a)return n}return null}(M,c.length));const C=function(e,t,n,s,o,r,i,a,l){const u=n.length,c=new Float64Array(3*u),d=new Uint32Array(u);for(let t=0;t<n.length;t++){const s=n[t].controlPointIndex;c[3*t]=e[3*s],c[3*t+1]=e[3*s+1],c[3*t+2]=e[3*s+2],d[t]=s}const h=3*t.length,m=new Uint32Array(h);for(let e=0;e<t.length;e++)m[3*e]=t[e].vertices[0],m[3*e+1]=t[e].vertices[1],m[3*e+2]=t[e].vertices[2];return{positions:c,indices:m,normals:s,uvs:o,uvSets:r,colors:i,tangents:a,binormals:l,controlPointIndices:d}}(a,d,h,f,g,_,v,A,T);let R=null;if(w){let e=!0;const t=w[0];for(let n=1;n<w.length;n++)if(w[n]!==t){e=!1;break}if(!e||0!==t){const e=C.indices.length/3;R=new Int32Array(e);for(let e=0;e<d.length;e++)R[e]=null!==(o=w[d[e].polyIndex])&&void 0!==o?o:0}}return{id:t,name:r,positions:C.positions,indices:C.indices,normals:C.normals,uvs:C.uvs,uvSets:C.uvSets,colors:C.colors,tangents:C.tangents,binormals:C.binormals,controlPointIndices:C.controlPointIndices,materialIndices:R,diagnostics:u}}function ie(e,t,n,s){if(e.indices.length<3)return s.push({type:"degenerate-polygon",message:`Polygon ${t} has fewer than three vertices.`,polygonIndex:t}),[];if(3===e.indices.length)return[{vertices:[e.startIndex,e.startIndex+1,e.startIndex+2],polyIndex:t}];const o=function(e,t){const n=function(e,t){let n=0,s=0,o=0;for(let r=0;r<e.indices.length;r++){const i=3*e.indices[r],a=3*e.indices[(r+1)%e.indices.length],l=t[i],u=t[i+1],c=t[i+2],d=t[a],h=t[a+1],m=t[a+2];n+=(u-h)*(c+m),s+=(c-m)*(l+d),o+=(l-d)*(u+h)}return[n,s,o]}(e,t),s=Math.abs(n[0]),o=Math.abs(n[1]),r=Math.abs(n[2]);if(s+o+r<1e-12)return null;const i=s>o&&s>r?0:o>r?1:2;return e.indices.map(e=>{const s=t[3*e],o=t[3*e+1],r=t[3*e+2];return 0===i?n[0]>=0?[o,r]:[r,o]:1===i?n[1]>=0?[r,s]:[s,r]:n[2]>=0?[s,o]:[o,s]})}(e,n);if(!o)return s.push({type:"degenerate-polygon",message:`Polygon ${t} has a near-zero normal; using fan triangulation.`,polygonIndex:t}),ae(e,t);const r=function(e){let t=0;for(let n=0;n<e.length;n++){const s=e[n],o=e[(n+1)%e.length];t+=s[0]*o[1]-o[0]*s[1]}return t/2}(o);if(Math.abs(r)<1e-12)return s.push({type:"degenerate-polygon",message:`Polygon ${t} projects to near-zero area; using fan triangulation.`,polygonIndex:t}),ae(e,t);const i=r>0,a=e.indices.map((e,t)=>t),l=[];let u=0;for(;a.length>3&&u++<e.indices.length*e.indices.length;){let n=!1;for(let s=0;s<a.length;s++){const r=a[(s+a.length-1)%a.length],u=a[s],c=a[(s+1)%a.length];if(le(o[r],o[u],o[c],i)&&!ue(o,a,r,u,c)){l.push({vertices:[e.startIndex+r,e.startIndex+u,e.startIndex+c],polyIndex:t}),a.splice(s,1),n=!0;break}}if(!n)return s.push({type:"triangulation-fallback",message:`Polygon ${t} could not be fully ear-clipped; using fan triangulation.`,polygonIndex:t}),ae(e,t)}return l.push({vertices:[e.startIndex+a[0],e.startIndex+a[1],e.startIndex+a[2]],polyIndex:t}),l}function ae(e,t){const n=[];for(let s=1;s<e.indices.length-1;s++)n.push({vertices:[e.startIndex,e.startIndex+s,e.startIndex+s+1],polyIndex:t});return n}function le(e,t,n,s){const o=(t[0]-e[0])*(n[1]-e[1])-(t[1]-e[1])*(n[0]-e[0]);return s?o>1e-12:o<-1e-12}function ue(e,t,n,s,o){for(const r of t)if(r!==n&&r!==s&&r!==o&&ce(e[r],e[n],e[s],e[o]))return!0;return!1}function ce(e,t,n,s){const o=Math.abs(de(t,n,s)),r=Math.abs(de(e,t,n)),i=Math.abs(de(e,n,s)),a=Math.abs(de(e,s,t));return Math.abs(o-(r+i+a))<1e-10}function de(e,t,n){return(t[0]-e[0])*(n[1]-e[1])-(t[1]-e[1])*(n[0]-e[0])}function he(e,t,n,s,o,r,i){var a,l;const u=X(e,"MappingInformationType"),c=X(e,"ReferenceInformationType");if(!u||!c)return null;const d=null!==(a=Q(u,0))&&void 0!==a?a:"",h=null!==(l=Q(c,0))&&void 0!==l?l:"",m=X(e,t);if(!m)return null;const f=fe(_e(m));let p=null;if("IndexToDirect"===h){const t=X(e,n);t&&(p=pe(_e(t)))}const _=new Float64Array(s.length*r);for(let t=0;t<s.length;t++){const n=s[t];let o;o="ByPolygonVertex"===d?"IndexToDirect"===h&&p?p[n.globalIndex]:n.globalIndex:"ByControlPoint"===d||"ByVertice"===d?"IndexToDirect"===h&&p?p[n.controlPointIndex]:n.controlPointIndex:"ByPolygon"===d?"IndexToDirect"===h&&p?p[n.polyIndex]:n.polyIndex:"AllSame"===d?0:n.globalIndex;for(let n=0;n<r;n++){const s=o*r+n;o<0||s>=f.length?(i.push({type:s>=f.length?"layer-data-too-short":"layer-index-out-of-bounds",message:`Layer '${e.name}' references unavailable element ${o}.`,layerName:e.name,index:o}),_[t*r+n]=0):_[t*r+n]=f[s]}}return _}function me(e,t,n,s){if(!n||!s)return 1;const o=4*e,r=3*e,i=n[r],a=n[r+1],l=n[r+2],u=t[o],c=t[o+1],d=t[o+2];return(a*d-l*c)*s[r]+(l*u-i*d)*s[r+1]+(i*c-a*u)*s[r+2]<0?-1:1}function fe(e){if(e instanceof Float64Array)return e;if(e instanceof Float32Array)return new Float64Array(e);if(e instanceof Int32Array)return new Float64Array(e);if(Array.isArray(e)){const t=new Float64Array(e.length);for(let n=0;n<e.length;n++)t[n]=Number(e[n]);return t}throw new Error(`Cannot convert ${typeof e} to Float64Array`)}function pe(e){if(e instanceof Int32Array)return e;if(e instanceof Float64Array){const 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){const 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)){const t=new Int32Array(e.length);for(let n=0;n<e.length;n++)t[n]=Math.round(Number(e[n]));return t}throw new Error(`Cannot convert ${typeof e} to Int32Array`)}function _e(e){return 1===e.properties.length?e.properties[0].value:e.properties.map(e=>e.value)}function ge(e,t,n){const s=e.get(t);if(s)return n?s.get(n):s.values().next().value}function ye(e,t,n,s=0){var o;return null===(o=xe(e,t,n))||void 0===o?void 0:o[s]}function ve(e,t,n,s){var o;return null!==(o=Te(ye(e,t,n)))&&void 0!==o?o:s}function be(e,t,n,s){const o=xe(e,t,n);if(!o)return s;const r=Te(o[0]),i=Te(o[1]),a=Te(o[2]);return void 0!==r&&void 0!==i&&void 0!==a?[r,i,a]:s}function xe(e,t,n){var s,o;return null!==(s=function(e,t){const n=[X(e,"Properties70"),X(e,"Properties60")].filter(e=>void 0!==e);for(const e of n)for(const n of e.children)if(("P"===n.name||"Property"===n.name)&&Q(n,0)===t)return n.properties.slice("Property"===n.name?3:4).map(e=>e.value)}(e,n))&&void 0!==s?s:null===(o=null==t?void 0:t.properties.get(n))||void 0===o?void 0:o.values}function Te(e){if("number"==typeof e)return e}function Ae(e,t,n){var s;const o=new Map,r=X(n,"Properties70");for(const e of null!==(s=null==r?void 0:r.children)&&void 0!==s?s:[]){if("P"!==e.name)continue;const t=Me(e);t&&o.set(t.name,t)}return{objectType:e,templateName:t,properties:o}}function Me(e){var t,n,s;const o=Q(e,0);return o?{name:o,propertyType:null!==(t=Q(e,1))&&void 0!==t?t:"",label:null!==(n=Q(e,2))&&void 0!==n?n:"",flags:null!==(s=Q(e,3))&&void 0!==s?s:"",values:e.properties.slice(4).map(e=>e.value)}:null}function we(e,t,n,s){var o,r,i,a;const l=Z(null!==(o=Q(e,1))&&void 0!==o?o:"Material"),u=function(e,t){var n,s;if(!t)return;const o=X(e,"ShadingModel"),r=o?Q(o,0):void 0;return"phong"===(null==r?void 0:r.toLowerCase())?null!==(n=ge(t,"Material","FbxSurfacePhong"))&&void 0!==n?n:ge(t,"Material"):"lambert"===(null==r?void 0:r.toLowerCase())&&null!==(s=ge(t,"Material","FbxSurfaceLambert"))&&void 0!==s?s:ge(t,"Material")}(e,s),c=X(e,"ShadingModel"),d="phong"===(c?null!==(r=Q(c,0))&&void 0!==r?r:"Lambert":null!==(i=ye(e,u,"ShadingModel"))&&void 0!==i?i:"Lambert").toLowerCase()?"Phong":"Lambert",h=function(e,t){var n,s,o,r,i;const a={};return a.diffuseColor=null!==(n=Ce(e,t,"DiffuseColor"))&&void 0!==n?n:Ce(e,t,"Diffuse"),a.diffuseFactor=Re(e,t,"DiffuseFactor"),a.ambientColor=null!==(s=Ce(e,t,"AmbientColor"))&&void 0!==s?s:Ce(e,t,"Ambient"),a.ambientFactor=Re(e,t,"AmbientFactor"),a.specularColor=null!==(o=Ce(e,t,"SpecularColor"))&&void 0!==o?o:Ce(e,t,"Specular"),a.specularFactor=Re(e,t,"SpecularFactor"),a.shininess=null!==(r=Re(e,t,"Shininess"))&&void 0!==r?r:Re(e,t,"ShininessExponent"),a.emissiveColor=null!==(i=Ce(e,t,"EmissiveColor"))&&void 0!==i?i:Ce(e,t,"Emissive"),a.emissiveFactor=Re(e,t,"EmissiveFactor"),a.opacity=Re(e,t,"Opacity"),a.transparencyFactor=Re(e,t,"TransparencyFactor"),a}(e,u),m=function(e,t,n){var s,o,r,i,a;const l=[],u=J(t,e,"Texture");for(const{id:e,node:c,propertyName:d}of u){const u=X(c,"FileName"),h=X(c,"RelativeFilename"),m=u&&null!==(s=Q(u,0))&&void 0!==s?s:"",f=h&&null!==(o=Q(h,0))&&void 0!==o?o:"";let p,_;const g=null!==(r=Re(c,n,"UVRotation"))&&void 0!==r?r:Re(c,n,"Rotation");let y;p=null!==(i=Se(c,n,"UVTranslation"))&&void 0!==i?i:Se(c,n,"Translation"),_=null!==(a=Se(c,n,"UVScaling"))&&void 0!==a?a:Se(c,n,"Scaling");const v=ye(c,n,"UVSet");v&&v.length>0&&(y=v),null!=p||(p=Fe(c,"ModelUVTranslation")),null!=_||(_=Fe(c,"ModelUVScaling"));let b=null;const x=J(t,e,"Video");for(const{node:e}of x){const t=X(e,"Content");if(t&&t.properties.length>0){const e=t.properties[0].value;e instanceof Uint8Array&&e.length>0?b=e:e instanceof ArrayBuffer&&e.byteLength>0&&(b=new Uint8Array(e))}}l.push({propertyName:null!=d?d:"DiffuseColor",fileName:m,relativeFileName:f,id:e,embeddedData:b,uvTranslation:p,uvScaling:_,uvRotation:g,uvSetName:y})}return l}(t,n,s?null!==(a=ge(s,"Texture","FbxFileTexture"))&&void 0!==a?a:ge(s,"Texture"):void 0);return{id:t,name:l,type:d,properties:h,textures:m}}function Ce(e,t,n){const s=xe(e,t,n);if(!s||s.length<3)return;const o=Oe(s[0]),r=Oe(s[1]),i=Oe(s[2]);return void 0!==o&&void 0!==r&&void 0!==i?[o,r,i]:void 0}function Re(e,t,n){return Oe(ye(e,t,n))}function Se(e,t,n){const s=xe(e,t,n);if(!s)return;const o=Oe(s[0]),r=Oe(s[1]);return void 0!==o&&void 0!==r?[o,r]:void 0}function Oe(e){if("number"==typeof e)return e}function Fe(e,t){var n,s;const o=X(e,t);if(!o)return;const r=Oe(null===(n=o.properties[0])||void 0===n?void 0:n.value),i=Oe(null===(s=o.properties[1])||void 0===s?void 0:s.value);return void 0!==r&&void 0!==i?[r,i]:void 0}function Ee(e,t,n){var s;const o=n.parentOf.get(e);if(!o)return null;const r=o.id,i=n.objects.get(r);if(!i||"Geometry"!==i.name)return null;const a=n.parentOf.get(r),l=a?n.objects.get(a.id):void 0,u="Model"===(null==l?void 0:l.name)?a.id:void 0,c=J(n,e,"Deformer");if(0===c.length)return null;const d=new Map;for(const{id:e,node:t}of c){if("Cluster"!==Q(t,2))continue;const s=J(n,e,"Model");s.length>0&&d.set(s[0].id,{clusterId:e,clusterNode:t})}const h=function(e,t){var n,s;const o=t.parentOf.get(e),r=o?t.objects.get(o.id):void 0,i="Model"===(null==r?void 0:r.name)?o.id:void 0;if(void 0===i)return new Map;for(const[,e]of Array.from(t.objects)){if("Pose"!==e.name||"BindPose"!==Q(e,2))continue;const t=new Map;for(const o of e.children){if("PoseNode"!==o.name)continue;const e=X(o,"Node"),r=X(o,"Matrix"),i=null===(n=null==e?void 0:e.properties[0])||void 0===n?void 0:n.value,a=null===(s=null==r?void 0:r.properties[0])||void 0===s?void 0:s.value;if("number"!=typeof i)continue;const l=Ge(a);16===(null==l?void 0:l.length)&&t.set(i,l)}if(t.has(i))return t}return new Map}(r,n),m=[],f=function(e,t,n,s){var o,r,i,a,l;const u=[],c=new Set,d=function(e,t){const n=new Set(Array.from(e.keys()));for(const s of Array.from(e.keys())){let e=Ie(s,t);for(;void 0!==e;){const s=t.objects.get(e);if(!s||"Model"!==s.name)break;n.add(e),e=Ie(e,t)}}return n}(e,n),h=function(e,t){const n=new Map;for(const s of Array.from(e)){let o=Ie(s,t);for(;void 0!==o;){if(e.has(o)){n.set(s,o);break}o=Ie(o,t)}}return n}(d,n),m=function(e,t){const n=new Map;for(const s of Array.from(e)){const e=t.get(s);void 0!==e&&(n.has(e)||n.set(e,[]),n.get(e).push(s))}return n}(d,h),f=Array.from(d).filter(e=>!h.has(e)).map(e=>({modelId:e,parentIndex:-1}));for(;f.length>0;){const{modelId:d,parentIndex:h}=f.shift();if(c.has(d))continue;c.add(d);const p=n.objects.get(d);if(!p)continue;const _=u.length,g=e.get(d),y=Pe(p),{bindPoseMatrix:v,transformLinkMatrix:b,transformAssociateModelMatrix:x,clusterMode:T}=g?Be(g.clusterNode):{bindPoseMatrix:null,transformLinkMatrix:null,transformAssociateModelMatrix:null,clusterMode:"Unknown"},A=Ne(d,Z(null!==(o=Q(p,1))&&void 0!==o?o:`Bone${_}`),void 0!==g,T,v,b,x,null!==(r=t.get(d))&&void 0!==r?r:null);s.push(...A),u.push({modelId:d,name:Z(null!==(i=Q(p,1))&&void 0!==i?i:`Bone${_}`),index:_,parentIndex:h,isCluster:void 0!==g,translation:y.translation,rotation:y.rotation,preRotation:y.preRotation,postRotation:y.postRotation,rotationPivot:y.rotationPivot,scalingPivot:y.scalingPivot,rotationOffset:y.rotationOffset,scalingOffset:y.scalingOffset,scale:y.scale,rotationOrder:y.rotationOrder,inheritType:y.inheritType,clusterMode:T,bindPoseMatrix:v,transformLinkMatrix:b,transformAssociateModelMatrix:x,modelBindPoseMatrix:null!==(a=t.get(d))&&void 0!==a?a:null,diagnostics:A});for(const e of null!==(l=m.get(d))&&void 0!==l?l:[])c.has(e)||f.push({modelId:e,parentIndex:_})}return u}(d,h,n,m);if(0===f.length)return null;const{boneIndices:p,boneWeights:_}=function(e,t){var n,s,o;let r=0;for(const s of e){const e=t.get(s.modelId);if(!e)continue;const o=X(e.clusterNode,"Indexes");if(!o)continue;const i=De(null===(n=o.properties[0])||void 0===n?void 0:n.value);if(i)for(let e=0;e<i.length;e++)i[e]>r&&(r=i[e])}const i=r+1,a=new Array(i),l=new Array(i);for(let e=0;e<i;e++)a[e]=[],l[e]=[];for(const n of e){const e=t.get(n.modelId);if(!e)continue;const r=X(e.clusterNode,"Indexes"),i=X(e.clusterNode,"Weights");if(!r||!i)continue;const u=De(null===(s=r.properties[0])||void 0===s?void 0:s.value),c=Ge(null===(o=i.properties[0])||void 0===o?void 0:o.value);if(u&&c)for(let e=0;e<u.length;e++){const t=u[e];a[t].push(n.index),l[t].push(c[e])}}for(let e=0;e<i;e++){if(0===a[e].length)continue;const t=a[e].map((t,n)=>({index:t,weight:l[e][n]}));t.sort((e,t)=>t.weight-e.weight);const n=t.slice(0,8);a[e]=n.map(e=>e.index),l[e]=n.map(e=>e.weight)}for(let e=0;e<i;e++){const t=l[e].reduce((e,t)=>e+t,0);if(t>0)for(let n=0;n<l[e].length;n++)l[e][n]/=t}return{boneIndices:a,boneWeights:l}}(f,d);return{id:e,geometryId:r,meshBindPoseMatrix:void 0!==u&&null!==(s=h.get(u))&&void 0!==s?s:null,bones:f,boneIndices:p,boneWeights:_,diagnostics:m}}function Ie(e,t){const n=t.connections.find(n=>{var s;return"OO"===n.type&&n.childId===e&&"Model"===(null===(s=t.objects.get(n.parentId))||void 0===s?void 0:s.name)});return null==n?void 0:n.parentId}function Le(e){const t=Q(e,2);return"Root"===t||"LimbNode"===t}function Pe(e){var t,n,s,o,r,i,a,l,u,c,d,h,m,f,p,_,g,y,v,b,x,T,A,M,w,C,R,S,O,F,E,I,L,P,B,N,k,D,G,V,H,K,$,U,q,W,z,j,Y,Z,J,ee,te,ne,se,oe,re,ie;const ae=[0,0,0],le=[0,0,0],ue=[0,0,0],ce=[0,0,0],de=[0,0,0],he=[0,0,0],me=[0,0,0],fe=[0,0,0],pe=[1,1,1];let _e=0,ge=1;const ye=X(e,"Properties70");if(!ye)return{translation:ae,rotation:le,preRotation:ue,postRotation:ce,rotationPivot:de,scalingPivot:he,rotationOffset:me,scalingOffset:fe,scale:pe,rotationOrder:_e,inheritType:ge};for(const e of ye.children){if("P"!==e.name)continue;const X=Q(e,0);if(X)switch(X){case"Lcl Translation":ae[0]=null!==(n=ke(null===(t=e.properties[4])||void 0===t?void 0:t.value))&&void 0!==n?n:0,ae[1]=null!==(o=ke(null===(s=e.properties[5])||void 0===s?void 0:s.value))&&void 0!==o?o:0,ae[2]=null!==(i=ke(null===(r=e.properties[6])||void 0===r?void 0:r.value))&&void 0!==i?i:0;break;case"Lcl Rotation":le[0]=null!==(l=ke(null===(a=e.properties[4])||void 0===a?void 0:a.value))&&void 0!==l?l:0,le[1]=null!==(c=ke(null===(u=e.properties[5])||void 0===u?void 0:u.value))&&void 0!==c?c:0,le[2]=null!==(h=ke(null===(d=e.properties[6])||void 0===d?void 0:d.value))&&void 0!==h?h:0;break;case"PreRotation":ue[0]=null!==(f=ke(null===(m=e.properties[4])||void 0===m?void 0:m.value))&&void 0!==f?f:0,ue[1]=null!==(_=ke(null===(p=e.properties[5])||void 0===p?void 0:p.value))&&void 0!==_?_:0,ue[2]=null!==(y=ke(null===(g=e.properties[6])||void 0===g?void 0:g.value))&&void 0!==y?y:0;break;case"PostRotation":ce[0]=null!==(b=ke(null===(v=e.properties[4])||void 0===v?void 0:v.value))&&void 0!==b?b:0,ce[1]=null!==(T=ke(null===(x=e.properties[5])||void 0===x?void 0:x.value))&&void 0!==T?T:0,ce[2]=null!==(M=ke(null===(A=e.properties[6])||void 0===A?void 0:A.value))&&void 0!==M?M:0;break;case"RotationPivot":de[0]=null!==(C=ke(null===(w=e.properties[4])||void 0===w?void 0:w.value))&&void 0!==C?C:0,de[1]=null!==(S=ke(null===(R=e.properties[5])||void 0===R?void 0:R.value))&&void 0!==S?S:0,de[2]=null!==(F=ke(null===(O=e.properties[6])||void 0===O?void 0:O.value))&&void 0!==F?F:0;break;case"ScalingPivot":he[0]=null!==(I=ke(null===(E=e.properties[4])||void 0===E?void 0:E.value))&&void 0!==I?I:0,he[1]=null!==(P=ke(null===(L=e.properties[5])||void 0===L?void 0:L.value))&&void 0!==P?P:0,he[2]=null!==(N=ke(null===(B=e.properties[6])||void 0===B?void 0:B.value))&&void 0!==N?N:0;break;case"RotationOffset":me[0]=null!==(D=ke(null===(k=e.properties[4])||void 0===k?void 0:k.value))&&void 0!==D?D:0,me[1]=null!==(V=ke(null===(G=e.properties[5])||void 0===G?void 0:G.value))&&void 0!==V?V:0,me[2]=null!==(K=ke(null===(H=e.properties[6])||void 0===H?void 0:H.value))&&void 0!==K?K:0;break;case"ScalingOffset":fe[0]=null!==(U=ke(null===($=e.properties[4])||void 0===$?void 0:$.value))&&void 0!==U?U:0,fe[1]=null!==(W=ke(null===(q=e.properties[5])||void 0===q?void 0:q.value))&&void 0!==W?W:0,fe[2]=null!==(j=ke(null===(z=e.properties[6])||void 0===z?void 0:z.value))&&void 0!==j?j:0;break;case"Lcl Scaling":pe[0]=null!==(Z=ke(null===(Y=e.properties[4])||void 0===Y?void 0:Y.value))&&void 0!==Z?Z:1,pe[1]=null!==(ee=ke(null===(J=e.properties[5])||void 0===J?void 0:J.value))&&void 0!==ee?ee:1,pe[2]=null!==(ne=ke(null===(te=e.properties[6])||void 0===te?void 0:te.value))&&void 0!==ne?ne:1;break;case"RotationOrder":_e=null!==(oe=ke(null===(se=e.properties[4])||void 0===se?void 0:se.value))&&void 0!==oe?oe:0;break;case"InheritType":ge=null!==(ie=ke(null===(re=e.properties[4])||void 0===re?void 0:re.value))&&void 0!==ie?ie:1}}return{translation:ae,rotation:le,preRotation:ue,postRotation:ce,rotationPivot:de,scalingPivot:he,rotationOffset:me,scalingOffset:fe,scale:pe,rotationOrder:_e,inheritType:ge}}function Be(e){let t=null,n=null,s=null,o="Normalize";const r=X(e,"Transform");if(r&&r.properties[0]){const e=r.properties[0].value;e instanceof Float64Array&&16===e.length?t=e:e instanceof Float32Array&&16===e.length&&(t=new Float64Array(e))}const i=X(e,"TransformLink");if(i&&i.properties[0]){const e=i.properties[0].value;e instanceof Float64Array&&16===e.length?n=e:e instanceof Float32Array&&16===e.length&&(n=new Float64Array(e))}const a=X(e,"TransformAssociateModel");if(a&&a.properties[0]){const e=a.properties[0].value;e instanceof Float64Array&&16===e.length?s=e:e instanceof Float32Array&&16===e.length&&(s=new Float64Array(e))}const l=X(e,"Mode"),u=l?Q(l,0):void 0;return"Normalize"===u||"Additive"===u||"TotalOne"===u?o=u:u&&(o="Unknown"),{bindPoseMatrix:t,transformLinkMatrix:n,transformAssociateModelMatrix:s,clusterMode:o}}function Ne(e,t,n,s,o,r,i,a){if(!n)return[];const l=[];return"Additive"!==s&&"TotalOne"!==s||l.push({type:"cluster-mode-runtime-unsupported",message:`Cluster mode '${s}' is preserved but not applied by Babylon linear blend skinning.`,boneModelId:e,boneName:t,clusterMode:s}),o||l.push({type:"missing-cluster-transform",message:"Cluster is missing Transform matrix; falling back to rest/bind-pose data.",boneModelId:e,boneName:t,clusterMode:s}),r||l.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:s}),a||l.push({type:"missing-bind-pose-matrix",message:"No BindPose matrix was found for this bone model.",boneModelId:e,boneName:t,clusterMode:s}),i&&l.push({type:"associate-model-present",message:"TransformAssociateModel is preserved for future associate-model skinning semantics.",boneModelId:e,boneName:t,clusterMode:s}),l}function ke(e){if("number"==typeof e)return e}function De(e){if(e instanceof Int32Array)return e;if(e instanceof Float64Array){const t=new Int32Array(e.length);for(let n=0;n<e.length;n++)t[n]=Math.round(e[n]);return t}return null}function Ge(e){return e instanceof Float64Array?e:e instanceof Float32Array?new Float64Array(e):null}function Ve(e,t){var n;const s=null!==(n=function(e,t){if(0===e.length)return;const n=e.map(e=>He(e,t)),s=new Set(n[0]);for(const e of n.slice(1))for(const t of Array.from(s))e.includes(t)||s.delete(t);return n[0].find(e=>s.has(e))}(e,t))&&void 0!==n?n:e[0];let o=s,r=Ke(o,t);for(;void 0!==r;){const e=t.objects.get(r);if(!e||"Model"!==e.name||!Le(e))break;o=r,r=Ke(r,t)}return o}function He(e,t){const n=[];let s=e;for(;void 0!==s;){const e=t.objects.get(s);if(!e||"Model"!==e.name)break;n.push(s),s=Ke(s,t)}return n}function Ke(e,t){const n=t.connections.find(n=>{var s;return"OO"===n.type&&n.childId===e&&"Model"===(null===(s=t.objects.get(n.parentId))||void 0===s?void 0:s.name)});return null==n?void 0:n.parentId}function $e(e){var t,n,s;return null!==(s=null!==(n=null!==(t=e.find(e=>e.isCluster&&e.transformLinkMatrix))&&void 0!==t?t:e.find(e=>e.isCluster))&&void 0!==n?n:e.find(e=>e.modelBindPoseMatrix))&&void 0!==s?s:e[0]}function Ue(e,t,n){if(e.length!==t.length)return!1;for(let s=0;s<e.length;s++)if(Math.abs(e[s]-t[s])>n)return!1;return!0}function qe(e,t){var n;const s=t.objects.get(e);if(!s||"Model"!==s.name)return null;const o=Pe(s);return{modelId:e,name:Z(null!==(n=Q(s,1))&&void 0!==n?n:`Bone${e.toString()}`),index:-1,parentIndex:-1,isCluster:!1,translation:o.translation,rotation:o.rotation,preRotation:o.preRotation,postRotation:o.postRotation,rotationPivot:o.rotationPivot,scalingPivot:o.scalingPivot,rotationOffset:o.rotationOffset,scalingOffset:o.scalingOffset,scale:o.scale,rotationOrder:o.rotationOrder,inheritType:o.inheritType,clusterMode:"Unknown",bindPoseMatrix:null,transformLinkMatrix:null,transformAssociateModelMatrix:null,modelBindPoseMatrix:null,diagnostics:[]}}function We(e,t){return e<t?-1:e>t?1:0}function ze(e,t,n){var s,o;return(null!==(s=n.get(e))&&void 0!==s?s:Number.MAX_SAFE_INTEGER)-(null!==(o=n.get(t))&&void 0!==o?o:Number.MAX_SAFE_INTEGER)||We(e,t)}const je=46186158e3,Xe=1/23,Ye=1e-5,Qe=[24,25,30,48,50,60,100,120];function Ze(e,t,n){var s,o,r,i;const a=Z(null!==(s=Q(t,1))&&void 0!==s?s:"Animation"),l=function(e){var t,n,s,o;const r=X(e,"Properties70");if(!r)return null;let i=0,a=null;for(const e of r.children){if("P"!==e.name)continue;const r=Q(e,0);"LocalStart"===r||"ReferenceStart"===r?i=null!==(n=lt(null===(t=e.properties[4])||void 0===t?void 0:t.value))&&void 0!==n?n:i:"LocalStop"!==r&&"ReferenceStop"!==r||(a=null!==(o=lt(null===(s=e.properties[4])||void 0===s?void 0:s.value))&&void 0!==o?o:a)}return null!==a?{start:i,stop:a}:null}(t),u=J(n,e,"AnimationLayer");if(0===u.length)return null;const c=[],d=[],h=[],m=[];let f=1/0,p=0;for(const{id:e,node:t}of u){const s=Z(null!==(o=Q(t,1))&&void 0!==o?o:"Layer");let a=100,l=0;const u=X(t,"Properties70");if(u)for(const e of u.children){if("P"!==e.name)continue;const t=Q(e,0);if("Weight"===t){const t=null===(r=e.properties[4])||void 0===r?void 0:r.value;"number"==typeof t&&(a=t)}else if("BlendMode"===t){const t=null===(i=e.properties[4])||void 0===i?void 0:i.value;"number"==typeof t&&(l=t)}}const _=J(n,e,"AnimationCurveNode"),g=[],y=[],v=[];for(const{id:e,node:t}of _){const o=Je(e,t,n);if(!o){const o=et(e,t,n);if(o){tt(o.curves,e=>{e<f&&(f=e),e>p&&(p=e)}),y.push(o),d.push(o);const t={type:"unsupported-curve-node",message:`AnimationCurveNode '${o.type}' is preserved as diagnostic data but not evaluated at runtime.`,layerName:s,curveNodeId:e,curveNodeType:o.type,targetId:o.targetId,propertyName:o.propertyName};v.push(t),m.push(t)}continue}for(const e of o.curves)for(const t of e.keys)t.time<f&&(f=t.time),t.time>p&&(p=t.time);g.push(o),c.push(o)}h.push({name:s,weight:a,normalizedWeight:a/100,blendMode:l,curveNodes:g,unsupportedCurveNodes:y,diagnostics:v})}if(0===c.length&&0===d.length)return null;h.length>1&&m.push({type:"multiple-animation-layers",message:"Multiple animation layers are preserved, but runtime blending is not yet evaluated."});for(const e of h){if(0!==e.blendMode){const t={type:"unsupported-layer-blend-mode",message:`Animation layer blend mode ${e.blendMode} is preserved but not yet blended at runtime.`,layerName:e.name};e.diagnostics.push(t),m.push(t)}if(100!==e.weight){const t={type:"partial-layer-weight",message:`Animation layer weight ${e.weight} is preserved but not yet applied at runtime.`,layerName:e.name};e.diagnostics.push(t),m.push(t)}}const _=f>0&&isFinite(f)?f:0;if(_>0){for(const e of c)for(const t of e.curves)for(const e of t.keys)e.time-=_;for(const e of d)for(const t of e.curves)for(const e of t.keys)e.time-=_;p-=_}const g=l?Math.max(l.start-_,0):0,y=l?Math.max(l.stop-_,g):0,v=y>g,b=v?g:0,x=v?y:p;return{name:a,startTime:b,stopTime:x,duration:Math.max(x-b,0),curveNodes:c,layers:h,unsupportedCurveNodes:d,diagnostics:m}}function Je(e,t,n){var s;const o=Z(null!==(s=Q(t,1))&&void 0!==s?s:"");if("T"===o||"R"===o||"S"===o){const t=function(e,t){for(const n of t.connections)if(n.childId===e&&"OP"===n.type){const e=t.objects.get(n.parentId);if(e&&"Model"===e.name)return n.parentId}return null}(e,n);if(null===t)return null;const s=nt(e,n);return 0===s.length?null:{type:o,targetModelId:t,curves:s}}if("DeformPercent"===o){const t=function(e,t){for(const n of t.connections)if(n.childId===e&&"OP"===n.type){const e=t.objects.get(n.parentId);if(e&&"Deformer"===e.name&&"BlendShapeChannel"===Q(e,2))return n.parentId}for(const n of t.connections)if(n.childId===e&&"OO"===n.type){const e=t.objects.get(n.parentId);if(e&&"Deformer"===e.name&&"BlendShapeChannel"===Q(e,2))return n.parentId}return null}(e,n);if(null===t)return null;const s=nt(e,n);return 0===s.length?null:{type:"DeformPercent",targetModelId:t,curves:s}}return null}function et(e,t,n){var s;const o=Z(null!==(s=Q(t,1))&&void 0!==s?s:""),r=nt(e,n),i=function(e){var t,n;const s={},o=X(e,"Properties70");for(const e of null!==(t=null==o?void 0:o.children)&&void 0!==t?t:[]){if("P"!==e.name)continue;const t=Q(e,0);if(!(null==t?void 0:t.startsWith("d|")))continue;const o=ut(null===(n=e.properties[4])||void 0===n?void 0:n.value);null!==o&&(s[t]=o)}return s}(t);if(0===r.length&&0===Object.keys(i).length)return null;let a,l=null;for(const t of n.connections)if(t.childId===e&&"OP"===t.type){l=t.parentId,a=t.propertyName;break}return{type:o,id:e,targetId:l,propertyName:a,curveCount:r.length,curves:r,defaultValues:i}}function tt(e,t){for(const n of e)for(const e of n.keys)t(e.time)}function nt(e,t){var n;const s=[];for(const o of t.connections)if(o.parentId===e&&"OP"===o.type){const e=t.objects.get(o.childId);if(!e||"AnimationCurve"!==e.name)continue;const r=null!==(n=o.propertyName)&&void 0!==n?n:"d|X",i=st(e);if(i.length>0){const t=ot(e,i);s.push({channel:r,keys:t?rt(i):i,isSampled:t})}}if(0===s.length){const n=J(t,e,"AnimationCurve"),o=["d|X","d|Y","d|Z"];for(let e=0;e<n.length&&e<3;e++){const t=st(n[e].node);if(t.length>0){const r=ot(n[e].node,t);s.push({channel:o[e],keys:r?rt(t):t,isSampled:r})}}}return s}function st(e){var t,n,s,o,r,i,a,l,u;const c=X(e,"KeyTime"),d=X(e,"KeyValueFloat");if(!c||!d)return[];const h=(g=null===(t=c.properties[0])||void 0===t?void 0:t.value)instanceof Float64Array?g:null,m=ct(null===(n=d.properties[0])||void 0===n?void 0:n.value),f=at(null===(o=null===(s=X(e,"KeyAttrFlags"))||void 0===s?void 0:s.properties[0])||void 0===o?void 0:o.value),p=ct(null===(i=null===(r=X(e,"KeyAttrDataFloat"))||void 0===r?void 0:r.properties[0])||void 0===i?void 0:i.value),_=at(null===(l=null===(a=X(e,"KeyAttrRefCount"))||void 0===a?void 0:a.properties[0])||void 0===l?void 0:l.value);var g;if(!h||!m)return[];if(h.length!==m.length)return[];const y=function(e,t,n){if(!t||0===t.length)return new Array(e).fill(-1);if(n&&n.length>0){let t=0;for(const e of n)t+=e;if(t===e){const e=[];for(let t=0;t<n.length;t++){const s=n[t];for(let n=0;n<s;n++)e.push(t)}return e}}return t.length===e?Array.from({length:e},(e,t)=>t):1===t.length?new Array(e).fill(0):Array.from({length:e},(e,n)=>Math.min(n,t.length-1))}(h.length,f,_),v=[];for(let e=0;e<h.length;e++){const t=y[e],n=t>=0&&null!==(u=null==f?void 0:f[t])&&void 0!==u?u:0,s=4*t;v.push({time:Number(h[e])/je,value:m[e],interpolation:dt(n),constantMode:256&n?"next":"standard",rightSlope:ht(p,s),nextLeftSlope:ht(p,s+1)})}return v}function ot(e,t){var n;return"FbxMayaSample Curve"===Z(null!==(n=Q(e,1))&&void 0!==n?n:"")||function(e){if(e.length<8)return!1;const t=[];for(let n=1;n<e.length;n++){const s=e[n].time-e[n-1].time;if(!(s>0))return!1;t.push(s)}const n=t.reduce((e,t)=>e+t,0)/t.length;if(n>Xe)return!1;const s=Math.max(1e-6,.05*n);if(t.some(e=>Math.abs(e-n)>s))return!1;const o=1/n;return!!Qe.some(e=>Math.abs(o-e)<=Math.max(.25,.02*e))&&!function(e){let t=!1,n=!0,s=!0,o=Number.POSITIVE_INFINITY,r=Number.NEGATIVE_INFINITY,i=0;for(const t of e)o=Math.min(o,t.value),r=Math.max(r,t.value);for(let o=0;o<e.length-1;o++){const r=e[o],a=e[o+1];if("cubic"!==r.interpolation)continue;t=!0;const l=a.time-r.time;if(!(l>0))continue;const u=(a.value-r.value)/l,c=r.rightSlope,d=r.nextLeftSlope;if(void 0!==c&&void 0!==d){(Math.abs(c)>Ye||Math.abs(d)>Ye)&&(s=!1);for(const e of[.25,.5,.75]){const t=mt(r.value,a.value,c,d,l,e),n=r.value+e*l*u;i=Math.max(i,Math.abs(t-n))}}else n=!1}if(!t||!n||s)return!1;const a=r-o;return i>Math.max(1e-4,.01*a)}(e)}(t)}function rt(e){return e.map(e=>({time:e.time,value:e.value,interpolation:"linear"}))}function it(e,t){var n,s;if(!e||0===e.keys.length)return null;const o=e.keys;if(t<=o[0].time)return o[0].value;if(t>=o[o.length-1].time)return o[o.length-1].value;for(let r=0;r<o.length-1;r++){const i=o[r],a=o[r+1];if(t<i.time||t>a.time)continue;if(a.time===i.time)return i.value;if("constant"===i.interpolation)return"next"===i.constantMode?a.value:i.value;const l=a.time-i.time,u=(t-i.time)/l;if("cubic"===i.interpolation&&!e.isSampled){const e=(a.value-i.value)/l,t=null!==(n=i.rightSlope)&&void 0!==n?n:e,o=null!==(s=i.nextLeftSlope)&&void 0!==s?s:e;return mt(i.value,a.value,t,o,l,u)}return i.value+u*(a.value-i.value)}return o[o.length-1].value}function at(e){if(e instanceof Int32Array)return e;if(e instanceof Float32Array||e instanceof Float64Array){const t=new Int32Array(e.length);for(let n=0;n<e.length;n++)t[n]=e[n];return t}return null}function lt(e){return"number"==typeof e?e/je:null}function ut(e){return"number"==typeof e?e:null}function ct(e){if(e instanceof Float32Array)return e;if(e instanceof Float64Array){const t=new Float32Array(e.length);for(let n=0;n<e.length;n++)t[n]=e[n];return t}return null}function dt(e){return 8&e?"cubic":4&e?"linear":2&e?"constant":"linear"}function ht(e,t){if(!e||t<0||t>=e.length)return;const n=e[t];return Number.isFinite(n)?n:void 0}function mt(e,t,n,s,o,r){const i=r*r,a=i*r;return(2*a-3*i+1)*e+(a-2*i+r)*o*n+(-2*a+3*i)*t+(a-i)*o*s}function ft(e,t,n){var s,o;const r=n.parentOf.get(e);if(!r)return null;const i=n.objects.get(r.id);if(!i||"Geometry"!==i.name)return null;const a=r.id,l=[],u=J(n,e,"Deformer");for(const{id:e,node:t}of u){if("BlendShapeChannel"!==Q(t,2))continue;const r=Z(null!==(s=Q(t,1))&&void 0!==s?s:"MorphTarget");let i=0;const a=X(t,"Properties70");if(a)for(const e of a.children)if("P"===e.name&&"DeformPercent"===Q(e,0)){const t=null===(o=e.properties[4])||void 0===o?void 0:o.value;"number"==typeof t&&(i=t)}const u=pt(t),c=[],d=J(n,e,"Geometry");for(const{node:e}of d){if("Shape"!==Q(e,2))continue;const t=yt(e);t&&c.push(t)}if(c.length>0){const t=[],n=_t(u,c,e,r,t);l.push({name:r,id:e,deformPercent:i,shapes:gt(c,n),fullWeights:n?[...n].sort((e,t)=>e-t):null,diagnostics:t})}}return 0===l.length?null:{id:e,geometryId:a,channels:l}}function pt(e){var t;const n=X(e,"FullWeights"),s=null===(t=null==n?void 0:n.properties[0])||void 0===t?void 0:t.value;return s&&(s instanceof Float64Array||s instanceof Float32Array||s instanceof Int32Array)?Array.from(s,e=>Number(e)):null}function _t(e,t,n,s,o){return e?e.length!==t.length?(1===t.length||o.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:s}),null):e:(t.length>1&&o.push({type:"missing-full-weights",message:"Blend shape channel has multiple shapes but no FullWeights; using the first shape for compatibility.",channelId:n,channelName:s}),null)}function gt(e,t){return t&&t.length===e.length?e.map((e,n)=>({shape:e,weight:t[n]})).sort((e,t)=>e.weight-t.weight).map(e=>e.shape):e.length>1?[e[0]]:e}function yt(e){var t,n,s;const o=X(e,"Indexes"),r=X(e,"Vertices");if(!o||!r)return null;const i=null===(t=o.properties[0])||void 0===t?void 0:t.value,a=null===(n=r.properties[0])||void 0===n?void 0:n.value;if(!i||!a)return null;const l=function(e){if(e instanceof Uint32Array)return e;if(e instanceof Int32Array||e instanceof Float32Array||e instanceof Float64Array){const t=new Uint32Array(e.length);for(let n=0;n<e.length;n++)t[n]=e[n];return t}return null}(i);if(!l)return null;let u;if(a instanceof Float64Array)u=a;else{if(!(a instanceof Float32Array))return null;u=new Float64Array(a)}let c=null;const d=X(e,"Normals");if(d){const e=null===(s=d.properties[0])||void 0===s?void 0:s.value;e instanceof Float64Array?c=e:e instanceof Float32Array&&(c=new Float64Array(e))}return{indices:l,vertices:u,normals:c}}const vt=new Set(["Character","CharacterPose","ControlSet","ControlSetPlug","SelectionSet","CollectionExclusive"]);function bt(e){return"Skin"===e||"Cluster"===e||"BlendShape"===e||"BlendShapeChannel"===e}function xt(e,t,n,s,o){var r,i,a,l;return{type:s,message:o,objectId:t,objectName:Z(null!==(r=Q(n,1))&&void 0!==r?r:n.name),nodeName:n.name,subType:null!==(i=Q(n,2))&&void 0!==i?i:"",parentCount:e.connections.filter(e=>e.childId===t).length,childCount:null!==(l=null===(a=e.childrenOf.get(t))||void 0===a?void 0:a.length)&&void 0!==l?l:0}}function Tt(e){const t=function(e){var t,n;const s=new Map,o=[],r=new Map,i=new Map,a=[],l=[],u=[],c=new Map,d=new Map;let h=-1;const m=e=>{let t=c.get(e);return void 0===t&&(t=h--,c.set(e,t)),t},f=(e,t)=>{let n=d.get(e);n||(n=new Map,d.set(e,n));let s=n.get(t);return void 0===s&&(s=h--,n.set(t,s)),s},p=Y(e,"Objects");if(p)for(const e of p.children){const t=e.properties[0];if(t){const n=ee(t.value);if(void 0!==n)s.set(n,e),o.push({id:n,node:e,source:"Objects",synthetic:!1});else if("string"==typeof t.value){const n=Z(t.value),l=m(n),c=se(e,l);if(s.set(l,c),o.push({id:l,node:c,source:"Objects",legacyName:n,synthetic:!1}),"Model"===e.name&&"Mesh"===Q(e,1)){const t=f("Geometry",n),c=oe(e,t);s.set(t,c),o.push({id:t,node:c,source:"legacySyntheticGeometry",legacyName:n,synthetic:!0}),ne(a,r,i,u,"OO",t,l)}}}}const _=Y(e,"Connections");if(_)for(const e of _.children){if("C"!==e.name&&"Connect"!==e.name)continue;const o=l.length,d=Q(e,0),h=null===(t=e.properties[1])||void 0===t?void 0:t.value,m=null===(n=e.properties[2])||void 0===n?void 0:n.value,f={source:e.name,rawType:d,accepted:!1};if(l.push(f),"OO"!==d&&"OP"!==d){const e=void 0===h?void 0:te(h,c),t=void 0===m?void 0:te(m,c);u.push({reason:"unsupported-connection-type",message:`Unsupported FBX connection type '${null!=d?d:""}' was not added to the graph.`,connectionIndex:o,type:d,childId:e,parentId:t});continue}if(void 0===h||void 0===m){u.push({reason:"missing-connection-endpoint",message:"FBX connection is missing a child or parent endpoint.",connectionIndex:o,type:d});continue}const p=te(h,c),_=te(m,c);if(void 0===p||void 0===_){u.push({reason:"unresolved-legacy-endpoint",message:"FBX connection references a legacy string endpoint that is not present in the object table.",connectionIndex:o,type:d});continue}const g="OP"===d&&e.properties.length>3?Q(e,3):void 0;f.childId=p,f.parentId=_,f.propertyName=g,p===_&&u.push({reason:"self-loop",message:"FBX connection references the same object as child and parent.",connectionIndex:o,type:d,childId:p,parentId:_,propertyName:g}),s.has(p)||u.push({reason:"unresolved-object-reference",message:"FBX connection child ID is not present in the object table.",connectionIndex:o,type:d,childId:p,parentId:_,propertyName:g}),0===_||s.has(_)||u.push({reason:"unresolved-object-reference",message:"FBX connection parent ID is not present in the object table.",connectionIndex:o,type:d,childId:p,parentId:_,propertyName:g}),ne(a,r,i,u,d,p,_,g,o),f.accepted=!0}return{objects:s,objectEntries:o,childrenOf:r,parentOf:i,connections:a,connectionEntries:l,diagnostics:u}}(e),n=function(e){const t=new Map,n=Y(e,"Definitions");if(!n)return t;for(const e of n.children){if("ObjectType"!==e.name)continue;const n=Q(e,0);if(n)for(const s of e.children){if("PropertyTemplate"!==s.name)continue;const e=Q(s,0);if(!e)continue;const o=Ae(n,e,s);let r=t.get(n);r||(r=new Map,t.set(n,r)),r.set(e,o)}}return t}(e),s=function(e){var t;const n={upAxis:1,upAxisSign:1,frontAxis:2,frontAxisSign:1,coordAxis:0,coordAxisSign:1,unitScaleFactor:1},s=Y(e,"GlobalSettings");if(!s)return n;const o=s.children.find(e=>"Properties70"===e.name);if(!o)return n;for(const e of o.children){if("P"!==e.name)continue;const s=Q(e,0),o=Rt(null===(t=e.properties[4])||void 0===t?void 0:t.value);if(s&&void 0!==o)switch(s){case"UpAxis":n.upAxis=o;break;case"UpAxisSign":n.upAxisSign=o;break;case"FrontAxis":n.frontAxis=o;break;case"FrontAxisSign":n.frontAxisSign=o;break;case"CoordAxis":n.coordAxis=o;break;case"CoordAxisSign":n.coordAxisSign=o;break;case"UnitScaleFactor":n.unitScaleFactor=o}}return n}(e),o=[];for(const[e,s]of Array.from(t.objects))"Material"===s.name&&o.push(we(s,e,t,n));const r=[];for(const[e,n]of Array.from(t.objects))"Geometry"===n.name&&"Mesh"===Q(n,2)&&r.push(re(n,e));const i=function(e){const t=[];for(const[n,s]of Array.from(e.objects))if("Deformer"===s.name&&"Skin"===Q(s,2)){const s=Ee(n,0,e);s&&t.push(s)}return t}(t),a=function(e,t){if(0===t.length)return[];const n=new Map;for(const s of t){const t=s.bones.filter(e=>e.isCluster).map(e=>e.modelId);if(0===t.length)continue;const o=Ve(t,e),r=n.get(o);r?r.push(s):n.set(o,[s])}return Array.from(n.entries()).sort(([e],[t])=>We(e,t)).map(([t,n])=>function(e,t,n){var s,o;const r=new Set,i=new Set,a=new Map,l=new Map;for(const e of t)for(const t of e.bones){l.has(t.modelId)||l.set(t.modelId,l.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(const e of He(t.modelId,n))i.add(e)}}const u=function(e){const t=[];for(const[n,s]of Array.from(e)){const e=s.filter(e=>e.isCluster&&e.transformLinkMatrix).map(e=>e.transformLinkMatrix);if(e.length<2)continue;const o=e[0];e.some(e=>!Ue(o,e,1e-5))&&t.push(`Model ${n.toString()} has differing Cluster.TransformLink matrices across skins`)}return t}(a),c=new Map;for(const[e,t]of Array.from(a))c.set(e,$e(t));const d=function(e,t){const n=new Map;for(const s of Array.from(e)){const o=Ke(s,t);void 0!==o&&e.has(o)&&n.set(s,o)}return n}(i,n),h=function(e,t,n){var s;const o=new Map;for(const n of Array.from(e)){const e=t.get(n);if(void 0===e)continue;let s=o.get(e);s||(s=[],o.set(e,s)),s.push(n)}for(const e of Array.from(o.values()))e.sort((e,t)=>ze(e,t,n));const r=[],i=[...Array.from(e).filter(e=>!t.has(e)).sort((e,t)=>ze(e,t,n))];for(;i.length>0;){const e=i.shift();r.push(e),i.push(...null!==(s=o.get(e))&&void 0!==s?s:[])}return r}(i,d,l),m=[],f=new Map;for(const e of h){const t=null!==(s=c.get(e))&&void 0!==s?s:qe(e,n);if(!t)continue;const i=d.get(e),a=void 0===i?-1:null!==(o=f.get(i))&&void 0!==o?o:-1,l=m.length,u=Object.assign(Object.assign({},t),{index:l,parentIndex:a,isCluster:r.has(e)});m.push(u),f.set(e,l)}const p=t.map(t=>function(e,t,n){const s=e.bones.map(e=>{const s=n.get(e.modelId);if(void 0===s&&e.isCluster)throw new Error(`FBX rig resolver: cluster bone ${e.name} is missing from resolved rig ${t}`);return null!=s?s:-1});return{skinId:e.id,geometryId:e.geometryId,rigId:t,skinBoneIndexToRigBoneIndex:s,clusterModelIds:new Set(e.bones.filter(e=>e.isCluster).map(e=>e.modelId))}}(t,`rig_${e.toString()}`,f));return{id:`rig_${e.toString()}`,rootModelIds:m.filter(e=>e.parentIndex<0).map(e=>e.modelId),bones:m,modelIdToBoneIndex:f,clusterModelIds:r,skinBindings:p,warnings:u}}(t,n,e))}(t,i),l=function(e){const t=[];for(const[n,s]of Array.from(e.objects))if("Deformer"===s.name&&"BlendShape"===Q(s,2)){const s=ft(n,0,e);s&&t.push(s)}return t}(t),u=function(e){const t=[];for(const[n,s]of Array.from(e.objects))if("AnimationStack"===s.name){const o=Ze(n,s,e);o&&t.push(o)}return t}(t),c=function(e,t){var n,s,o,r;const i=[],a=null!==(n=ge(t,"NodeAttribute","FbxCamera"))&&void 0!==n?n:ge(t,"NodeAttribute");for(const[t,n]of Array.from(e.objects)){if("NodeAttribute"!==n.name)continue;if("Camera"!==Q(n,2))continue;const l=e.parentOf.get(t);if(!l)continue;const u=e.objects.get(l.id);if(!u||"Model"!==u.name)continue;const c=Z(null!==(s=Q(u,1))&&void 0!==s?s:"Camera"),d=ve(n,a,"NearPlane",.1),h=ve(n,a,"FarPlane",1e4),m=Ot(n,a),f=1===ve(n,a,"CameraProjectionType",0)||1===ve(n,a,"ProjectionType",0)?"orthographic":"perspective",p=Rt(ye(n,a,"FocalLength")),_=null!==(o=Rt(ye(n,a,"FilmWidth")))&&void 0!==o?o:Rt(ye(n,a,"ApertureWidth")),g=null!==(r=Rt(ye(n,a,"FilmHeight")))&&void 0!==r?r:Rt(ye(n,a,"ApertureHeight")),y=Rt(ye(n,a,"OrthoZoom")),v=Rt(ye(n,a,"Roll")),b=Ft(n,a,m,p,g),x=[];"orthographic"===f&&void 0===y&&x.push("Orthographic camera has no OrthoZoom; runtime orthographic bounds use a fallback."),void 0!==p&&void 0===g&&void 0===ye(n,a,"FieldOfView")&&x.push("FocalLength is present without FilmHeight; default field of view fallback may be used."),i.push({modelId:l.id,name:c,fieldOfView:b,nearPlane:d,farPlane:h,aspectRatio:m,projectionType:f,focalLength:p,filmWidth:_,filmHeight:g,orthoZoom:y,roll:v,unknownProperties:Et(n,wt),diagnostics:x})}return i}(t,n),d=function(e,t){var n,s,o,r,i;const a=[],l=null!==(n=ge(t,"NodeAttribute","FbxLight"))&&void 0!==n?n:ge(t,"NodeAttribute");for(const[t,n]of Array.from(e.objects)){if("NodeAttribute"!==n.name)continue;if("Light"!==Q(n,2))continue;const u=e.parentOf.get(t);if(!u)continue;const c=e.objects.get(u.id);if(!c||"Model"!==c.name)continue;const d=Z(null!==(s=Q(c,1))&&void 0!==s?s:"Light"),h=ve(n,l,"LightType",0),m=be(n,l,"Color",[1,1,1]),f=ve(n,l,"Intensity",100)/100,p=null!==(o=Rt(ye(n,l,"OuterAngle")))&&void 0!==o?o:Rt(ye(n,l,"ConeAngle")),_=Rt(ye(n,l,"InnerAngle")),g=null!=p?p:45,y=ve(n,l,"DecayType",2),v=Rt(ye(n,l,"DecayStart")),b=St(ye(n,l,"EnableNearAttenuation")),x=St(ye(n,l,"EnableFarAttenuation")),T=null!==(i=null!==(r=St(ye(n,l,"CastShadow")))&&void 0!==r?r:St(ye(c,void 0,"CastShadow")))&&void 0!==i?i:St(ye(c,void 0,"Shadow")),A=[];2!==y&&A.push(`DecayType ${y} is preserved as metadata; Babylon falloff is not remapped in this pass.`),void 0!==v&&A.push("DecayStart is preserved as metadata and is not mapped to Babylon light range."),a.push({modelId:u.id,name:d,lightType:h,color:m,intensity:f,coneAngle:g,decayType:y,innerAngle:_,outerAngle:p,decayStart:v,enableNearAttenuation:b,enableFarAttenuation:x,castShadows:T,unknownProperties:Et(n,Ct),diagnostics:A})}return a}(t,n),h=function(e){var t,n;const s=e.diagnostics.map(t=>({type:"connection-graph",message:t.message,objectId:t.childId,subType:t.reason,parentCount:void 0===t.childId?void 0:e.connections.filter(e=>e.childId===t.childId).length}));for(const[o,r]of Array.from(e.objects)){const i=null!==(t=Q(r,2))&&void 0!==t?t:"";"Constraint"!==r.name?vt.has(r.name)?s.push(xt(e,o,r,"unsupported-helper",`${r.name} helper data is preserved as diagnostic data but not evaluated at runtime.`)):"LayeredTexture"!==r.name?"Pose"!==r.name||"BindPose"===i?"Deformer"!==r.name||bt(i)?"NodeAttribute"===r.name&&i&&"Camera"!==i&&"Light"!==i&&s.push(xt(e,o,r,"unsupported-node-attribute",`NodeAttribute subtype '${i}' is preserved as diagnostic data but not converted to a Babylon object.`)):s.push(xt(e,o,r,"unsupported-deformer",`Deformer subtype '${i}' is preserved as diagnostic data but not evaluated at runtime.`)):s.push(xt(e,o,r,"unsupported-pose",`Pose subtype '${i}' is preserved as diagnostic data but not evaluated at runtime.`)):s.push(xt(e,o,r,"unsupported-layered-texture","LayeredTexture is preserved as diagnostic data; runtime texture layer blending is not implemented.")):s.push(xt(e,o,r,"unsupported-constraint",`Constraint '${i||Z(null!==(n=Q(r,1))&&void 0!==n?n:"")}' is preserved as diagnostic data but not evaluated at runtime.`))}return s}(t),m=function(e,t,n,s){var o;const r=new Map;for(const e of t)r.set(e.id,e);const i=new Map;for(const e of n)i.set(e.id,e);const a=null!==(o=e.childrenOf.get(0))&&void 0!==o?o:[],l=[];for(const{id:t}of a){const n=e.objects.get(t);n&&"Model"===n.name&&l.push(At(t,n,e,r,i,s))}return l}(t,r,o,n);return Object.assign({rootModels:m,geometries:r,materials:o,skins:i,rigs:a,blendShapes:l,animations:u,cameras:c,lights:d,diagnostics:h},s)}function At(e,t,n,s,o,r){var i,a,l;const u=Z(null!==(i=Q(t,1))&&void 0!==i?i:"Model"),c=null!==(a=Q(t,2))&&void 0!==a?a:"Null",d=J(n,e,"Geometry"),h=d.length>0?s.get(d[0].id):void 0,m=J(n,e,"Material"),f=[];for(const{id:e}of m){const t=o.get(e);t&&f.push(t)}const p=function(e,t){const n=be(e,t,"Lcl Translation",[0,0,0]),s=be(e,t,"Lcl Rotation",[0,0,0]),o=be(e,t,"Lcl Scaling",[1,1,1]),r=be(e,t,"PreRotation",[0,0,0]),i=be(e,t,"PostRotation",[0,0,0]),a=be(e,t,"RotationPivot",[0,0,0]),l=be(e,t,"ScalingPivot",[0,0,0]),u=be(e,t,"RotationOffset",[0,0,0]),c=be(e,t,"ScalingOffset",[0,0,0]),d=be(e,t,"GeometricTranslation",[0,0,0]),h=be(e,t,"GeometricRotation",[0,0,0]),m=be(e,t,"GeometricScaling",[1,1,1]),f=ve(e,t,"RotationOrder",0),p=ve(e,t,"InheritType",1);return{translation:n,rotation:s,scale:o,preRotation:r,postRotation:i,rotationPivot:a,scalingPivot:l,rotationOffset:u,scalingOffset:c,geometricTranslation:d,geometricRotation:h,geometricScaling:m,rotationOrder:f,inheritType:p,diagnostics:1!==p&&2!==p?[`InheritType ${p} is parsed and preserved; runtime parent-scale inheritance remains gated to avoid changing existing visual behavior without a fixture-specific baseline.`]:[]}}(t,null!==(l=ge(r,"Model","FbxNode"))&&void 0!==l?l:ge(r,"Model")),_=J(n,e,"Model"),g=[];for(const{id:e,node:t}of _)g.push(At(e,t,n,s,o,r));const y=t.children.find(e=>"Culling"===e.name),v=!!y&&"CullingOff"===Q(y,0),b=function(e){var t;const n=X(e,"Properties70");if(!n)return;const s={};let o=!1;for(const e of n.children){if("P"!==e.name)continue;const n=Q(e,0);if(!n||Mt.has(n))continue;const r=null===(t=e.properties[4])||void 0===t?void 0:t.value;void 0!==r&&("string"==typeof r||"number"==typeof r||"boolean"==typeof r)&&(s[n]=r,o=!0)}return o?s:void 0}(t);return Object.assign({id:e,name:u,subType:c,geometry:h,materials:f,children:g,cullingOff:v,customProperties:b},p)}const Mt=new Set(["Lcl Translation","Lcl Rotation","Lcl Scaling","PreRotation","PostRotation","RotationPivot","ScalingPivot","RotationOffset","ScalingOffset","RotationOrder","GeometricTranslation","GeometricRotation","GeometricScaling","Visibility","InheritType","ScalingMax","DefaultAttributeIndex","currentUVSet","lockInfluenceWeights"]),wt=new Set(["FieldOfView","FieldOfViewX","FieldOfViewY","NearPlane","FarPlane","AspectWidth","AspectHeight","FilmAspectRatio","FocalLength","FilmWidth","FilmHeight","ApertureWidth","ApertureHeight","CameraProjectionType","ProjectionType","OrthoZoom","Roll","ApertureMode"]),Ct=new Set(["LightType","Color","Intensity","InnerAngle","OuterAngle","ConeAngle","DecayType","DecayStart","EnableNearAttenuation","EnableFarAttenuation","CastShadow","Shadow"]);function Rt(e){if("number"==typeof e)return e}function St(e){return"boolean"==typeof e?e:"number"==typeof e?0!==e:void 0}function Ot(e,t){const n=Rt(ye(e,t,"FilmAspectRatio"));if(void 0!==n&&n>0)return n;const s=Rt(ye(e,t,"AspectWidth")),o=Rt(ye(e,t,"AspectHeight"));return void 0!==s&&void 0!==o&&s>0&&o>0?s/o:0}function Ft(e,t,n,s,o){var r;const i=null!==(r=Rt(ye(e,t,"FieldOfViewY")))&&void 0!==r?r:Rt(ye(e,t,"FieldOfView"));if(void 0!==i)return i;const a=Rt(ye(e,t,"FieldOfViewX"));return void 0!==a?n>0?It(2*Math.atan(Math.tan(a*Math.PI/180/2)/n)):a:void 0!==s&&s>0&&void 0!==o&&o>0?It(2*Math.atan(25.4*o/(2*s))):45}function Et(e,t){var n;const s=new Set;for(const o of["Properties70","Properties60"]){const r=X(e,o);for(const e of null!==(n=null==r?void 0:r.children)&&void 0!==n?n:[]){if("P"!==e.name&&"Property"!==e.name)continue;const n=Q(e,0);n&&!t.has(n)&&s.add(n)}}return Array.from(s).sort()}function It(e){return 180*e/Math.PI}function Lt(e,n,s){const o=t.Matrix.RotationX(e),r=t.Matrix.RotationY(n),i=t.Matrix.RotationZ(s);return o.multiply(r).multiply(i)}function Pt(e,n,s,o){const r=t.Matrix.RotationX(e),i=t.Matrix.RotationY(n),a=t.Matrix.RotationZ(s);switch(o){case 0:default:return r.multiply(i).multiply(a);case 1:return r.multiply(a).multiply(i);case 2:return i.multiply(a).multiply(r);case 3:return i.multiply(r).multiply(a);case 4:return a.multiply(r).multiply(i);case 5:return a.multiply(i).multiply(r)}}function Bt(e,n){const s=Math.PI/180,o=t.Matrix.Scaling(n[0],n[1],n[2]),r=Lt(e[0]*s,e[1]*s,e[2]*s);return o.multiply(r)}const Nt={name:"fbx",extensions:{".fbx":{isBinary:!0}}};class kt{constructor(e={}){var t;this.name=Nt.name,this.extensions=Nt.extensions,this._bindRestBones=new WeakSet,this._sourceBonesBySkeleton=new WeakMap,this._scaleCompensationHelpersBySkeleton=new WeakMap,this._options={normalMapCoordinateSystem:null!==(t=e.normalMapCoordinateSystem)&&void 0!==t?t:"y-up"}}createPlugin(e){return new kt(e[Nt.name])}importMeshAsync(e,t,n,s,o,r){return b(this,void 0,void 0,function*(){const o=Tt(this._parse(n));return this._buildScene(o,t,s,e)})}loadAsync(e,t,n,s,o){return b(this,void 0,void 0,function*(){const s=Tt(this._parse(t));this._buildScene(s,e,n,null)})}loadAssetContainerAsync(e,n,s,o,r){return b(this,void 0,void 0,function*(){const o=Tt(this._parse(n)),r=new t.AssetContainer(e),i=this._buildScene(o,e,s,null);for(const e of i.meshes)r.meshes.push(e);for(const e of i.skeletons)r.skeletons.push(e);for(const e of i.animationGroups)r.animationGroups.push(e);for(const e of i.transformNodes)r.transformNodes.push(e);for(const e of i.lights)r.lights.push(e);for(const e of i.cameras)r.cameras.push(e);for(const e of i.materials)this._addMaterialToContainer(e,r);for(const e of i.textures)this._addTextureToContainer(e,r);for(const e of i.meshes)this._addMaterialToContainer(e.material,r);return this._setAssetContainer(r),r.removeAllFromScene(),r})}_parse(e){if(e instanceof ArrayBuffer)return this._parseFromArrayBuffer(e);if(ArrayBuffer.isView(e)){const t=e,n=t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength);return this._parseFromArrayBuffer(n)}if("string"==typeof e)return $(e);throw new Error("FBXFileLoader: unsupported data type")}_parseFromArrayBuffer(e){const t=new Uint8Array(e,0,Math.min(21,e.byteLength));if(String.fromCharCode(...t).startsWith("Kaydara FBX Binary"))return function(e){const t=new DataView(e),n=new Uint8Array(e);if("Kaydara FBX Binary \0"!==K(n,0,21))throw new Error("Not a valid binary FBX file");if(e.byteLength<27)throw new Error("Truncated binary FBX header");const s=t.getUint32(23,!0),o=s>=7500,r=[];let i=27;for(;i<e.byteLength;){const s=N(t,n,i,o,e.byteLength);if(null===s)break;r.push(s.node),i=s.endOffset}return{version:s,nodes:r}}(e);const n=new TextDecoder("utf-8").decode(e);if(n.trimStart().startsWith("; FBX"))return $(n);throw new Error("FBXFileLoader: unrecognized FBX format")}_buildScene(e,n,s,o){var r;const i=this._buildNameFilter(o),a=new Map;for(const t of e.materials){const e=this._createMaterial(t,n,s);a.set(t.id,e)}const l=[],u=new Map,c=new Map,d=new Map,h=new Map,m=new Map;for(const t of e.skins)m.set(t.id,t);for(const t of e.rigs){const e=this._createSkeleton(t.id,t.bones,n);l.push(e),u.set(t.id,e);for(const n of t.skinBindings){const t=m.get(n.skinId);t&&(c.set(n.geometryId,e),d.set(n.geometryId,t),h.set(n.geometryId,n))}}const f=new Map,p=e=>{for(const t of e)f.set(t.id,t),p(t.children)};p(e.rootModels);const _=kt._collectCullingConflictMaterialIds(e.rootModels),g=new Map,y=new t.TransformNode("__fbx_root__",n);n.useRightHandedSystem||(y.rotation.y=Math.PI,y.scaling.z=-1);const v=[],b=[y];let x=y;const T=kt._computeFBXAxisConversionMatrix(e);T.equals(t.Matrix.Identity())||(x=new t.TransformNode("__fbx_axis_conversion__",n),x.parent=y,kt._applyMatrixToTransform(x,T),b.push(x));const A=new Map,M=t.Matrix.Identity();for(const t of e.rootModels)this._buildModel(t,n,x,x,M,a,i,v,b,c,d,h,A,_,g);this._linkSkeletonsToTransformNodes(e.rigs,u,A,b,n);for(const n of e.rigs){const e=u.get(n.id);if(!e)continue;const s=null!==(r=v.find(t=>t.skeleton===e))&&void 0!==r?r:null,o=null!=s?s:y,i=new Set;for(const t of e.bones){const e=t.getTransformNode();e&&i.add(e)}for(const r of n.bones){if(!r.isCluster)continue;const n=A.get(r.modelId),a=this._getSourceBone(e,r.index);if(n&&a)for(const r of[...n.getChildren()]){const n=r;if(!i.has(n)){const r=n.computeWorldMatrix(!0).clone(),i=kt._getBoneReferenceWorldMatrix(e,a,o,s),l=new t.Matrix;i.invertToRef(l);const u=r.multiply(l);n.parent=null,n.attachToBone(a,o),kt._applyMatrixToTransform(n,u)}}}}e.blendShapes.length>0&&this._applyBlendShapes(e.blendShapes,v,n);const w=[];for(const t of e.animations){const s=this._createAnimationGroup(t,e.rigs,u,n,A,f,v);s&&w.push(s)}const C=[];for(const t of e.cameras){const e=this._createCamera(t,A,n);e&&C.push(e)}const R=[];for(const t of e.lights){const e=this._createLight(t,A,n);e&&R.push(e)}return{meshes:v,particleSystems:[],skeletons:l,animationGroups:w,transformNodes:b,geometries:[],lights:R,spriteManagers:[],materials:Array.from(a.values()),textures:Array.from(new Set(Array.from(a.values()).flatMap(e=>e.getActiveTextures()))),cameras:C}}_addMaterialToContainer(e,n){if(e){if(e instanceof t.MultiMaterial){n.multiMaterials.includes(e)||n.multiMaterials.push(e);for(const t of e.subMaterials)this._addMaterialToContainer(t,n)}else n.materials.includes(e)||n.materials.push(e);for(const t of e.getActiveTextures())this._addTextureToContainer(t,n)}}_addTextureToContainer(e,t){t.textures.includes(e)||t.textures.push(e)}_setAssetContainer(e){for(const t of e.meshes)t._parentContainer=e;for(const t of e.transformNodes)t._parentContainer=e;for(const t of e.skeletons)t._parentContainer=e;for(const t of e.animationGroups)t._parentContainer=e;for(const t of e.lights)t._parentContainer=e;for(const t of e.cameras)t._parentContainer=e;for(const t of e.materials)t._parentContainer=e;for(const t of e.multiMaterials)t._parentContainer=e;for(const t of e.textures)t._parentContainer=e}static _computeFBXAxisConversionMatrix(e){const n=[[0,0,0],[0,0,0],[0,0,0]],s=(e,t,s)=>{if(e<0||e>2)return;const o=[0,0,0];o[s]=t>=0?1:-1,n[e]=o};return s(e.coordAxis,e.coordAxisSign,0),s(e.upAxis,e.upAxisSign,1),s(e.frontAxis,e.frontAxisSign,2),n.some(e=>e.every(e=>0===e))?t.Matrix.Identity():t.Matrix.FromValues(n[0][0],n[0][1],n[0][2],0,n[1][0],n[1][1],n[1][2],0,n[2][0],n[2][1],n[2][2],0,0,0,0,1)}_buildModel(e,n,s,o,r,i,a,l,u,c,d,h,m,f,p){var _,g;const y=kt._computeFBXModelLocalMatrix(e).multiply(r);if(!e.geometry||"Mesh"!==e.subType||a&&!a(e.name)){if(e.geometry&&"Mesh"===e.subType&&a&&!kt._modelSubtreeMatchesNameFilter(e,a))return;const r=new t.TransformNode(e.name,n);s&&(r.parent=s),kt._applyFBXTransform(r,e),u.push(r),m.set(e.id,r),kt._applyModelMetadata(r,e);for(const t of e.children)this._buildModel(t,n,r,o,y,i,a,l,u,c,d,h,m,f,p)}else{const r=c.get(e.geometry.id),v=d.get(e.geometry.id),b=h.get(e.geometry.id);r&&v&&(r.needInitialSkinMatrix=!0);const x=this._createMesh(e,e.geometry,n,r,v,b);if(r&&v){const e=v.meshBindPoseMatrix?t.Matrix.FromArray(v.meshBindPoseMatrix):y;x.parent=o,kt._applyMatrixToTransform(x,e),x.computeWorldMatrix(!0),x.updatePoseMatrix(t.Matrix.Invert(e)),x.alwaysSelectAsActiveMesh=!0}else s&&(x.parent=s),kt._applyFBXTransform(x,e);if(e.materials.length>1&&(null===(_=e.geometry)||void 0===_?void 0:_.materialIndices))this._applyMultiMaterial(x,e,i,n,f,p);else if(e.materials.length>0){const t=i.get(e.materials[0].id);t&&(x.material=kt._getModelMaterial(t,e,p,f.has(e.materials[0].id)))}(null===(g=e.geometry)||void 0===g?void 0:g.colors)&&this._useUnmodulatedVertexColorMaterials(x,n),this._applyMaterialUVSetCoordinates(x.material,e.geometry),l.push(x),m.set(e.id,x),kt._applyModelMetadata(x,e);for(const t of e.children)this._buildModel(t,n,x,o,y,i,a,l,u,c,d,h,m,f,p)}}_linkSkeletonsToTransformNodes(e,n,s,o,r){for(const i of e){const e=n.get(i.id);if(e)for(const n of i.bones){const i=this._getSourceBone(e,n.index),a=s.get(n.modelId);if(!i||!a)continue;const l=this._getScaleCompensationHelper(e,n.index);if(l){const e=new t.TransformNode(l.name,r);e.parent=a.parent,a.parent=e,kt._applyMatrixToTransform(e,l.getLocalMatrix()),kt._applyMatrixToTransform(a,i.getLocalMatrix()),l.linkTransformNode(e),o.push(e)}else kt._applyMatrixToTransform(a,i.getLocalMatrix());i.linkTransformNode(a)}}}static _modelSubtreeMatchesNameFilter(e,t){for(const n of e.children){if(n.geometry&&"Mesh"===n.subType&&t(n.name))return!0;if(kt._modelSubtreeMatchesNameFilter(n,t))return!0}return!1}static _applyModelMetadata(e,t){var n;(t.customProperties||0!==t.diagnostics.length)&&(e.metadata=Object.assign(Object.assign(Object.assign({},null!==(n=e.metadata)&&void 0!==n?n:{}),t.customProperties?{fbxCustomProperties:t.customProperties}:{}),t.diagnostics.length>0?{fbxDiagnostics:t.diagnostics}:{}))}_createMesh(e,n,s,o,r,i){var a;const l=new t.Mesh(e.name,s);l.sideOrientation=s.useRightHandedSystem?t.Material.CounterClockWiseSideOrientation:t.Material.ClockWiseSideOrientation;const u=new t.VertexData,c=Dt(n.positions),d=e.geometricTranslation,h=e.geometricRotation,m=e.geometricScaling,f=kt._computeFBXGeometricMatrix(d,h,m),p=kt._computeFBXGeometricDeltaMatrix(h,m),_=kt._computeFBXGeometricNormalMatrix(h,m),g=!f.equals(t.Matrix.Identity()),y=!p.equals(t.Matrix.Identity()),v=!_.equals(t.Matrix.Identity());if(g)for(let e=0;e<c.length;e+=3){const n=t.Vector3.TransformCoordinates(new t.Vector3(c[e],c[e+1],c[e+2]),f);c[e]=n.x,c[e+1]=n.y,c[e+2]=n.z}let b;if(u.positions=c,u.indices=Array.from(n.indices),n.normals){if(b=Dt(n.normals),v)for(let e=0;e<b.length;e+=3){const n=t.Vector3.TransformNormal(new t.Vector3(b[e],b[e+1],b[e+2]),_);n.lengthSquared()>0&&n.normalize(),b[e]=n.x,b[e+1]=n.y,b[e+2]=n.z}u.normals=b}if(n.uvs&&(u.uvs=Dt(n.uvs)),n.uvSets.length>1&&(u.uvs2=Dt(n.uvSets[1].data)),n.uvSets.length>2&&(u.uvs3=Dt(n.uvSets[2].data)),n.uvSets.length>3&&(u.uvs4=Dt(n.uvSets[3].data)),n.uvSets.length>4&&(u.uvs5=Dt(n.uvSets[4].data)),n.uvSets.length>5&&(u.uvs6=Dt(n.uvSets[5].data)),n.tangents){const e=Dt(n.tangents);if(v)for(let n=0;n<e.length;n+=4){const s=t.Vector3.TransformNormal(new t.Vector3(e[n],e[n+1],e[n+2]),_);s.lengthSquared()>0&&s.normalize(),e[n]=s.x,e[n+1]=s.y,e[n+2]=s.z}!function(e,t){if(1!==t)for(let n=3;n<e.length;n+=4)e[n]*=t}(e,this._getNormalMapTangentHandednessScale()),u.tangents=e}else b&&u.uvs&&(u.tangents=function(e,t,n,s,o=1,r=null,i=null){var a,l,u,c,d,h;const m=e.length/3,f=new Map,p=new Array(m).fill(null);for(let o=0;o+2<s.length;o+=3){const a=i?i[o/3]:0,l=s[o],u=s[o+1],c=s[o+2],d=3*l,h=3*u,m=3*c,_=2*l,g=2*u,y=2*c,v=e[h]-e[d],b=e[m]-e[d],x=e[h+1]-e[d+1],T=e[m+1]-e[d+1],A=e[h+2]-e[d+2],M=e[m+2]-e[d+2],w=n[g]-n[_],C=n[y]-n[_],R=n[g+1]-n[_+1],S=n[y+1]-n[_+1],O=w*S-C*R;if(Math.abs(O)<1e-8)continue;const F=1/O,E=(S*v-R*b)*F,I=(S*x-R*T)*F,L=(S*A-R*M)*F,P=(w*b-C*v)*F,B=(w*T-C*x)*F,N=(w*M-C*A)*F;Gt(l,u,c,E,I,L,P,B,N,e,t,n,r,a,f,p),Gt(u,c,l,E,I,L,P,B,N,e,t,n,r,a,f,p),Gt(c,l,u,E,I,L,P,B,N,e,t,n,r,a,f,p)}const _=new Float32Array(4*m);for(let e=0;e<m;e++){const n=3*e,s=4*e,[r,i,m]=Vt(t[n],t[n+1],t[n+2]),g=p[e]?f.get(p[e]):void 0,y=null!==(a=null==g?void 0:g.tx)&&void 0!==a?a:0,v=null!==(l=null==g?void 0:g.ty)&&void 0!==l?l:0,b=null!==(u=null==g?void 0:g.tz)&&void 0!==u?u:0,x=r*y+i*v+m*b;let T=y-r*x,A=v-i*x,M=b-m*x;const w=Math.hypot(T,A,M);w>1e-8?(T/=w,A/=w,M/=w):[T,A,M]=Kt(r,i,m);const C=null!==(c=null==g?void 0:g.bx)&&void 0!==c?c:0,R=null!==(d=null==g?void 0:g.by)&&void 0!==d?d:0,S=null!==(h=null==g?void 0:g.bz)&&void 0!==h?h:0,O=i*M-m*A,F=m*T-r*M,E=r*A-i*T,I=Math.hypot(C,R,S)>1e-8&&O*C+F*R+E*S<0?-1:1;_[s]=T,_[s+1]=A,_[s+2]=M,_[s+3]=I*o}return _}(c,b,u.uvs,n.indices,this._getNormalMapTangentHandednessScale(),n.controlPointIndices,n.materialIndices));if(n.colors){const 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;u.colors=e,l.hasVertexAlpha=!1}if(o&&r){const{matricesIndices:e,matricesWeights:t,matricesIndicesExtra:s,matricesWeightsExtra:o,numBoneInfluencers:a}=this._buildSkinningData(n,r,i);u.matricesIndices=e,u.matricesWeights=t,s&&o&&(u.matricesIndicesExtra=s,u.matricesWeightsExtra=o),l.numBoneInfluencers=a}return u.applyToMesh(l),l.metadata=Object.assign(Object.assign({},null!==(a=l.metadata)&&void 0!==a?a:{}),{fbxGeometryId:n.id,fbxControlPointIndices:n.controlPointIndices,fbxGeometryDeltaMatrix:y?p:null,fbxGeometryNormalMatrix:v?_:null,fbxPreRotMatrix:y?p:null}),o&&(l.skeleton=o),l}_applyMultiMaterial(e,n,s,o,r,i){const a=n.geometry.materialIndices,l=e.getIndices();if(!l)return;const u=l.length/3,c=new Map;for(let e=0;e<u;e++){const t=e<a.length?a[e]:0;let n=c.get(t);n||(n=[],c.set(t,n)),n.push(e)}const d=Array.from(c.keys()).sort((e,t)=>e-t),h=[],m=[];for(const e of d){const t=c.get(e),n=h.length;for(const e of t)h.push(l[3*e],l[3*e+1],l[3*e+2]);m.push({start:n,count:3*t.length,matIdx:e})}e.setIndices(h);const f=new t.MultiMaterial(n.name+"_multi",o);for(const e of m){const t=n.materials[e.matIdx];if(t){const e=s.get(t.id);e?f.subMaterials.push(kt._getModelMaterial(e,n,i,r.has(t.id))):f.subMaterials.push(null)}else f.subMaterials.push(null)}e.material=f,e.subMeshes=[];const p=e.getTotalVertices();for(let n=0;n<m.length;n++){const s=m[n];new t.SubMesh(n,0,p,s.start,s.count,e)}}static _collectCullingConflictMaterialIds(e){const t=new Map,n=e=>{var s;for(const n of e.materials){const o=null!==(s=t.get(n.id))&&void 0!==s?s:{cullingOff:!1,cullingOn:!1};e.cullingOff?o.cullingOff=!0:o.cullingOn=!0,t.set(n.id,o)}for(const t of e.children)n(t)};for(const t of e)n(t);const s=new Set;for(const[e,n]of Array.from(t))n.cullingOff&&n.cullingOn&&s.add(e);return s}static _getModelMaterial(e,t,n,s=!0){if(!t.cullingOff||!e.backFaceCulling)return e;if(!s)return e.backFaceCulling=!1,e;const o=null==n?void 0:n.get(e);if(o)return o;const r=e.clone(`${e.name}_CullingOff`);return r.backFaceCulling=!1,null==n||n.set(e,r),r}_applyMaterialUVSetCoordinates(e,n){if(e)if(e instanceof t.MultiMaterial)for(const s of e.subMaterials)s instanceof t.StandardMaterial&&this._applyStandardMaterialUVSetCoordinates(s,n);else e instanceof t.StandardMaterial&&this._applyStandardMaterialUVSetCoordinates(e,n)}_applyStandardMaterialUVSetCoordinates(e,t){var n;for(const s of[e.diffuseTexture,e.bumpTexture,e.emissiveTexture,e.ambientTexture,e.specularTexture,e.opacityTexture,e.reflectionTexture]){if(!s)continue;const e=null===(n=s.metadata)||void 0===n?void 0:n.fbxUVSetName;if(!e)continue;const o=t.uvSets.findIndex(t=>t.name===e);o>=0&&(s.coordinatesIndex=o)}}_useUnmodulatedVertexColorMaterials(e,n){const s=e.material;if(s)if(s instanceof t.StandardMaterial){if(!s.diffuseTexture){const n=s.clone(`${s.name}_VertexColor`);n.diffuseColor=new t.Color3(1,1,1),e.material=n}}else if(s instanceof t.MultiMaterial){const o=new t.MultiMaterial(`${s.name}_VertexColor`,n);o.subMaterials=s.subMaterials.map(e=>{if(e instanceof t.StandardMaterial&&!e.diffuseTexture){const n=e.clone(`${e.name}_VertexColor`);return n.diffuseColor=new t.Color3(1,1,1),n}return e}),e.material=o}}_buildSkinningData(e,t,n){var s,o,r;const i=e.positions.length/3,a=new Float32Array(4*i),l=new Float32Array(4*i);let u=null,c=null,d=0;if(e.controlPointIndices){for(let n=0;n<i;n++){const o=e.controlPointIndices[n],r=null!==(s=t.boneIndices[o])&&void 0!==s?s:[];d=Math.max(d,Math.min(r.length,8))}d>4&&(u=new Float32Array(4*i),c=new Float32Array(4*i));for(let s=0;s<i;s++){const i=e.controlPointIndices[s],d=null!==(o=t.boneIndices[i])&&void 0!==o?o:[],h=null!==(r=t.boneWeights[i])&&void 0!==r?r:[];for(let e=0;e<8;e++){const t=e<4?a:u,o=e<4?l:c;if(!t||!o)continue;const r=4*s+e%4;if(e<d.length){const s=d[e],o=n?n.skinBoneIndexToRigBoneIndex[s]:s;if(void 0===o||o<0)throw new Error(`FBXFileLoader: missing rig bone mapping for skin bone index ${s}`);t[r]=o}else t[r]=0;o[r]=e<h.length?h[e]:0}}}return{matricesIndices:a,matricesWeights:l,matricesIndicesExtra:u,matricesWeightsExtra:c,numBoneInfluencers:Math.max(d,1)}}_createMaterial(e,n,s){var o,r,i,a,l;const u=new t.StandardMaterial(e.name,n),c=e.properties,d=(...t)=>e.textures.some(e=>t.includes(e.propertyName));if("Lambert"===e.type&&(u.specularColor=t.Color3.Black()),c.diffuseColor){const e=d("DiffuseColor","Diffuse")?1:null!==(o=c.diffuseFactor)&&void 0!==o?o:1;u.diffuseColor=new t.Color3(c.diffuseColor[0]*e,c.diffuseColor[1]*e,c.diffuseColor[2]*e)}if(c.ambientColor){const e=d("AmbientColor","Ambient")?1:null!==(r=c.ambientFactor)&&void 0!==r?r:1;u.ambientColor=new t.Color3(c.ambientColor[0]*e,c.ambientColor[1]*e,c.ambientColor[2]*e)}if("Phong"===e.type&&c.specularColor){const e=d("SpecularColor","Specular","Shininess","ShininessExponent")?1:null!==(i=c.specularFactor)&&void 0!==i?i:1;u.specularColor=new t.Color3(c.specularColor[0]*e,c.specularColor[1]*e,c.specularColor[2]*e)}if(c.emissiveColor){const e=d("EmissiveColor","Emissive")?1:null!==(a=c.emissiveFactor)&&void 0!==a?a:1;u.emissiveColor=new t.Color3(c.emissiveColor[0]*e,c.emissiveColor[1]*e,c.emissiveColor[2]*e)}void 0!==c.opacity?u.alpha=c.opacity:void 0!==c.transparencyFactor&&(u.alpha=1-c.transparencyFactor),u.alpha<1&&(u.transparencyMode=t.Material.MATERIAL_ALPHABLEND),void 0!==c.shininess&&(u.specularPower=c.shininess);for(const o of e.textures){if(!kt._isSupportedMaterialTextureSlot(o.propertyName))continue;const e=kt._createTexture(o,n,s,kt._isNormalMapTextureSlot(o.propertyName));if(e){switch(o.propertyName){case"DiffuseColor":u.diffuseTexture=e,u.diffuseColor=new t.Color3(1,1,1);break;case"NormalMap":case"NormalMapTexture":case"normalCamera":case"Bump":case"BumpFactor":u.bumpTexture=e,this._configureNormalTexture(e,u);break;case"EmissiveColor":u.emissiveTexture=e;break;case"AmbientColor":u.ambientTexture=e;break;case"SpecularColor":u.specularTexture=e;break;case"TransparencyFactor":case"TransparentColor":u.opacityTexture=e,u.transparencyMode=t.Material.MATERIAL_ALPHATESTANDBLEND;break;case"ReflectionColor":case"ReflectionFactor":u.reflectionTexture=e}o.uvTranslation&&(e.uOffset=o.uvTranslation[0],e.vOffset=o.uvTranslation[1]),o.uvScaling&&(e.uScale=o.uvScaling[0],e.vScale=o.uvScaling[1]),void 0!==o.uvRotation&&(e.wAng=o.uvRotation*(Math.PI/180)),void 0!==o.uvSetIndex&&(e.coordinatesIndex=o.uvSetIndex),o.uvSetName&&(e.metadata=Object.assign(Object.assign({},null!==(l=e.metadata)&&void 0!==l?l:{}),{fbxUVSetName:o.uvSetName}))}}return u}_configureNormalTexture(e,t){e.gammaSpace=!1,t.invertNormalMapX=!1,t.invertNormalMapY="y-down"===this._options.normalMapCoordinateSystem}_getNormalMapTangentHandednessScale(){return"y-down"===this._options.normalMapCoordinateSystem?-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(e,n,s,o){const r=kt._getTextureSourceName(e),i=kt._getTextureCreationOptions(r,o,e.embeddedData);if(e.embeddedData){const s=new t.Texture(null,n,i),o=null!=r?r:`embeddedTexture_${e.id.toString()}`;return s.updateURL(`data:fbx-embedded-texture/${encodeURIComponent(o)}`,new Uint8Array(e.embeddedData),void 0,i.forcedExtension),s.name=o,s}const a=kt._getExternalTextureUrls(e,s),l=a.shift();return l?kt._createExternalTexture(l,a,n,i):null}static _createExternalTexture(e,n,s,o){n.push(...kt._buildTextureFallbackUrls(e));let r=0;const i=new t.Texture(e,s,Object.assign(Object.assign({},o),{onError:()=>{const e=n[r++];e&&i.getScene()&&i.updateURL(e,null,void 0,kt._getForcedExtension(e))}}));return i}static _buildTextureFallbackUrls(e){const t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\")),n=e.lastIndexOf(".");if(n<=t)return[];const s=e.slice(0,n),o=e.slice(n+1).toLowerCase();return["png","jpg","jpeg","webp","bmp","tga"].filter(e=>e!==o).map(e=>`${s}.${e}`)}static _getTextureCreationOptions(e,t,n){const s=n?e?kt._getMimeType(e):"image/png":void 0;return{buffer:n?new Uint8Array(n):void 0,forcedExtension:e?kt._getForcedExtension(e,s):n?".png":void 0,gammaSpace:!t,mimeType:s}}static _getExternalTextureUrls(e,t){const n=[e.relativeFileName,e.fileName].filter(e=>!!e),s=[];for(const e of n){const n=e.replace(/\\/g,"/");kt._isSafeRelativeTexturePath(n)&&s.push(t+n);const o=kt._getTextureSourceNameFromPath(n);o&&s.push(t+o)}return Array.from(new Set(s))}static _getTextureSourceName(e){const t=e.relativeFileName||e.fileName;if(!t)return null;const n=t.replace(/\\/g,"/");return kt._getTextureSourceNameFromPath(n)}static _getTextureSourceNameFromPath(e){var t;return null!==(t=e.split("/").pop())&&void 0!==t?t:e}static _isSafeRelativeTexturePath(e){return!(/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(e)||e.startsWith("/")||e.startsWith("//")||e.split("/").some(e=>".."===e))}static _getForcedExtension(e,t){const n=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\")),s=e.lastIndexOf(".");if(s>n)return e.slice(s).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(e){const n=t.GetMimeType(e);if(n)return n;switch(kt._getForcedExtension(e)){case".tga":return"image/x-tga";case".bmp":return"image/bmp";case".gif":return"image/gif";default:return"image/png"}}_applyBlendShapes(e,n,s){var o,r,i,a,l,u,c,d;for(const h of e){const e=n.find(e=>{var t;return(null===(t=e.metadata)||void 0===t?void 0:t.fbxGeometryId)===h.geometryId});if(!e)continue;const m=new t.MorphTargetManager(s);m.optimizeInfluencers=!1;const f=null!==(a=null!==(r=null===(o=e.metadata)||void 0===o?void 0:o.fbxGeometryDeltaMatrix)&&void 0!==r?r:null===(i=e.metadata)||void 0===i?void 0:i.fbxPreRotMatrix)&&void 0!==a?a:null,p=null!==(u=null===(l=e.metadata)||void 0===l?void 0:l.fbxGeometryNormalMatrix)&&void 0!==u?u:f;for(const n of h.channels){const o=null===(c=e.metadata)||void 0===c?void 0:c.fbxControlPointIndices;if(!o)continue;const r=e.getVerticesData("position"),i=e.getVerticesData("normal");if(!r)continue;const a=Ut(n.deformPercent,n.fullWeights,n.shapes.length),l=[];for(let e=0;e<n.shapes.length;e++){const u=n.shapes[e];if(!u)continue;const c=$t(u,o,r,i,f,p);if(!c)continue;const h=n.fullWeights&&n.shapes.length>1?`${n.name}_${n.fullWeights[e]}`:n.name,_=new t.MorphTarget(h,null!==(d=a[e])&&void 0!==d?d:0,s);_.setPositions(c.positions),c.normals&&_.setNormals(c.normals),l.push(m.numTargets),m.addTarget(_)}0!==l.length&&(e.metadata||(e.metadata={}),e.metadata.fbxBlendShapeChannelIds||(e.metadata.fbxBlendShapeChannelIds=new Map),e.metadata.fbxBlendShapeChannelIds.set(n.id,l[0]),e.metadata.fbxBlendShapeChannelTargets||(e.metadata.fbxBlendShapeChannelTargets=new Map),e.metadata.fbxBlendShapeChannelTargets.set(n.id,{targetIndices:l,fullWeights:n.fullWeights}))}m.numTargets>0&&(m.numMaxInfluencers=m.numTargets,e.morphTargetManager=m)}}_createCamera(e,n,s){var o;const r=n.get(e.modelId),i=r?r.computeWorldMatrix(!0):t.Matrix.Identity(),a=t.Vector3.TransformCoordinates(t.Vector3.Zero(),i),l=new t.FreeCamera(e.name,a,s);if(l.fov=e.fieldOfView*(Math.PI/180),l.minZ=e.nearPlane,l.maxZ=e.farPlane,l.metadata=Object.assign(Object.assign({},null!==(o=l.metadata)&&void 0!==o?o:{}),{fbxCamera:{projectionType:e.projectionType,focalLength:e.focalLength,filmWidth:e.filmWidth,filmHeight:e.filmHeight,orthoZoom:e.orthoZoom,roll:e.roll,aspectRatio:e.aspectRatio,unknownProperties:e.unknownProperties,diagnostics:e.diagnostics}}),"orthographic"===e.projectionType){const n=e.orthoZoom&&e.orthoZoom>0?e.orthoZoom:1,s=e.aspectRatio>0?e.aspectRatio:1;l.mode=t.Camera.ORTHOGRAPHIC_CAMERA,l.orthoTop=n/2,l.orthoBottom=-n/2,l.orthoRight=n*s/2,l.orthoLeft=-n*s/2}const u=t.Vector3.TransformCoordinates(new t.Vector3(1,0,0),i);return l.setTarget(u),l}_createLight(e,n,s){var o;const r=n.get(e.modelId),i=r?r.computeWorldMatrix(!0):t.Matrix.Identity(),a=t.Vector3.TransformCoordinates(t.Vector3.Zero(),i),l=new t.Color3(e.color[0],e.color[1],e.color[2]),u=t.Vector3.TransformCoordinates(new t.Vector3(0,0,-1),i).subtract(a).normalize();let c;switch(e.lightType){case 1:c=new t.DirectionalLight(e.name,u,s),c.diffuse=l,c.intensity=e.intensity;break;case 2:{const n=e.coneAngle*(Math.PI/180);c=new t.SpotLight(e.name,a,u,n,2,s),c.diffuse=l,c.intensity=e.intensity;break}default:c=new t.PointLight(e.name,a,s),c.diffuse=l,c.intensity=e.intensity}return c.metadata=Object.assign(Object.assign({},null!==(o=c.metadata)&&void 0!==o?o:{}),{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,unknownProperties:e.unknownProperties,diagnostics:e.diagnostics}}),c}_createSkeleton(e,n,s){var o;const r=new t.Skeleton("Skeleton",`skeleton_${e}`,s),i=[],a=new Map,l=[],u=[],c=[];for(let e=0;e<n.length;e++){const t=n[e],s=kt._computeFBXLocalMatrix(t.translation,t.rotation,t.scale,t.preRotation,t.postRotation,t.rotationPivot,t.scalingPivot,t.rotationOffset,t.scalingOffset,t.rotationOrder);l[e]=s,c[e]=kt._computeFBXRuntimeLocalMatrix(n,s,e)}u.push(...kt._computeFBXAbsoluteMatrices(n,c));const d=n.map((e,n)=>e.transformLinkMatrix?t.Matrix.FromArray(e.transformLinkMatrix):e.modelBindPoseMatrix?t.Matrix.FromArray(e.modelBindPoseMatrix):u[n]),h=d.map((e,s)=>{const o=n[s].parentIndex;if(o<0)return e;const r=new t.Matrix;return d[o].invertToRef(r),e.multiply(r)}),m=kt._shouldUseBindMatricesAsRest(n,l,h);for(let e=0;e<n.length;e++){let s=m?h[e]:c[e],u=n[e].parentIndex>=0?i[n[e].parentIndex]:null;if(!m&&2===n[e].inheritType&&n[e].parentIndex>=0&&u){const i=kt._splitParentScaleCompensatedLocalMatrix(l[e],n[n[e].parentIndex].scale),c=new t.Bone(`${n[e].name}__fbx_scaleCompensation`,r,u,i.helperLocalMatrix,i.helperLocalMatrix.clone(),t.Matrix.Identity(),-1);c.metadata=Object.assign(Object.assign({},null!==(o=c.metadata)&&void 0!==o?o:{}),{fbxScaleCompensationForBoneIndex:e,fbxScaleCompensationForBoneName:n[e].name}),a.set(e,c),u=c,s=i.boneLocalMatrix}const d=new t.Bone(n[e].name,r,u,s,m?s.clone():null,m?s.clone():null,e);m&&n[e].isCluster&&kt._getMaxScaleRatio(l[e],h[e])>=10&&this._bindRestBones.add(d),i.push(d)}if(this._sourceBonesBySkeleton.set(r,i),this._scaleCompensationHelpersBySkeleton.set(r,a),!m){for(let e=0;e<n.length;e++)i[e].updateMatrix(h[e],!1,!1);for(const e of Array.from(a.values()))e.updateMatrix(t.Matrix.Identity(),!1,!1);for(const e of r.bones)e.getParent()||e._updateAbsoluteBindMatrices(void 0,!0)}return r}_getSourceBone(e,t){var n,s;return null!==(s=null===(n=this._sourceBonesBySkeleton.get(e))||void 0===n?void 0:n[t])&&void 0!==s?s:e.bones[t]}_getScaleCompensationHelper(e,t){var n;return null===(n=this._scaleCompensationHelpersBySkeleton.get(e))||void 0===n?void 0:n.get(t)}static _computeFBXAbsoluteMatrices(e,t){const n=[];for(let s=0;s<e.length;s++){const o=e[s].parentIndex;n[s]=o<0?t[s].clone():t[s].multiply(n[o])}return n}static _computeFBXRuntimeLocalMatrix(e,t,n,s){const o=e[n].parentIndex;if(2!==e[n].inheritType||o<0)return t;const r=null!=s?s:e[o].scale;return kt._applyParentScaleCompensation(t,r)}static _applyParentScaleCompensation(e,t){const n=kt._splitParentScaleCompensatedLocalMatrix(e,t);return n.boneLocalMatrix.multiply(n.helperLocalMatrix)}static _splitParentScaleCompensatedLocalMatrix(e,n){const s=e.getTranslation(),o=e.clone();return o.setTranslation(t.Vector3.Zero()),{boneLocalMatrix:o,helperLocalMatrix:t.Matrix.Compose(kt._getInverseScaleVector(n),t.Quaternion.Identity(),s)}}static _safeInverseScale(e){return Math.abs(e)>1e-8?1/e:1}static _getInverseScaleVector(e){return new t.Vector3(kt._safeInverseScale(e[0]),kt._safeInverseScale(e[1]),kt._safeInverseScale(e[2]))}static _shouldUseBindMatricesAsRest(e,t,n){return e.some((e,s)=>!!e.isCluster&&kt._getMaxScaleRatio(t[s],n[s])>=10)}static _getMaxScaleRatio(e,n){const s=new t.Vector3,o=new t.Quaternion,r=new t.Vector3,i=new t.Vector3,a=new t.Quaternion,l=new t.Vector3;return e.decompose(s,o,r),n.decompose(i,a,l),Math.max(kt._getScaleRatio(s.x,i.x),kt._getScaleRatio(s.y,i.y),kt._getScaleRatio(s.z,i.z))}static _getScaleRatio(e,t){const n=Math.abs(e),s=Math.abs(t);return n<1e-6||s<1e-6?n<1e-6&&s<1e-6?1:Number.POSITIVE_INFINITY:Math.max(n/s,s/n)}static _computeFBXGeometricMatrix(e,n,s){return function(e,n,s){const o=t.Matrix.Translation(e[0],e[1],e[2]);return Bt(n,s).multiply(o)}(e,n,s)}static _computeFBXGeometricDeltaMatrix(e,t){return Bt(e,t)}static _computeFBXGeometricNormalMatrix(e,n){return function(e,n){const s=Math.PI/180,o=t.Matrix.Scaling(0===n[0]?0:1/n[0],0===n[1]?0:1/n[1],0===n[2]?0:1/n[2]),r=Lt(e[0]*s,e[1]*s,e[2]*s);return o.multiply(r)}(e,n)}static _computeFBXLocalMatrix(e,n,s,o,r,i,a,l,u,c=0){return function(e){const{translation:n,rotation:s,scale:o,preRotation:r,postRotation:i,rotationPivot:a,scalingPivot:l,rotationOffset:u,scalingOffset:c,rotationOrder:d}=e,h=Math.PI/180,m=0!==a[0]||0!==a[1]||0!==a[2]||0!==l[0]||0!==l[1]||0!==l[2],f=0!==u[0]||0!==u[1]||0!==u[2]||0!==c[0]||0!==c[1]||0!==c[2],p=0!==i[0]||0!==i[1]||0!==i[2];if(!m&&!f&&!p){const e=Lt(r[0]*h,r[1]*h,r[2]*h),i=Pt(s[0]*h,s[1]*h,s[2]*h,d),a=t.Matrix.Translation(n[0],n[1],n[2]),l=i.multiply(e);return t.Matrix.Scaling(o[0],o[1],o[2]).multiply(l).multiply(a)}const _=t.Matrix.Translation(n[0],n[1],n[2]),g=t.Matrix.Translation(u[0],u[1],u[2]),y=t.Matrix.Translation(a[0],a[1],a[2]),v=t.Matrix.Translation(-a[0],-a[1],-a[2]),b=t.Matrix.Translation(c[0],c[1],c[2]),x=t.Matrix.Translation(l[0],l[1],l[2]),T=t.Matrix.Translation(-l[0],-l[1],-l[2]),A=Lt(r[0]*h,r[1]*h,r[2]*h),M=Pt(s[0]*h,s[1]*h,s[2]*h,d),w=t.Matrix.Scaling(o[0],o[1],o[2]);let C;if(p){const e=Lt(i[0]*h,i[1]*h,i[2]*h);C=new t.Matrix,e.invertToRef(C)}else C=t.Matrix.Identity();let R=T;return R=R.multiply(w),R=R.multiply(x),R=R.multiply(b),R=R.multiply(v),R=R.multiply(C),R=R.multiply(M),R=R.multiply(A),R=R.multiply(y),R=R.multiply(g),R=R.multiply(_),R}({translation:e,rotation:n,scale:s,preRotation:o,postRotation:r,rotationPivot:i,scalingPivot:a,rotationOffset:l,scalingOffset:u,rotationOrder:c})}static _applyFBXTransform(e,n){const s=kt._computeFBXModelLocalMatrix(n),o=new t.Vector3,r=new t.Quaternion,i=new t.Vector3;s.decompose(o,r,i),e.position=i,e.rotationQuaternion=r,e.scaling=o}static _computeFBXModelLocalMatrix(e){return kt._computeFBXLocalMatrix(e.translation,e.rotation,e.scale,e.preRotation,e.postRotation,e.rotationPivot,e.scalingPivot,e.rotationOffset,e.scalingOffset,e.rotationOrder)}static _getBoneReferenceWorldMatrix(e,t,n,s){return s?e.getTransformMatrices(s):e.prepare(!0),n.computeWorldMatrix(!0),t.getFinalMatrix().multiply(n.getWorldMatrix())}static _applyMatrixToTransform(e,n){const s=new t.Vector3,o=new t.Quaternion,r=new t.Vector3;n.decompose(s,o,r),e.position=r,e.rotationQuaternion=o,e.scaling=s}_createAnimationGroup(e,n,s,o,r,i,a){if(0===e.curveNodes.length)return null;const l=new t.AnimationGroup(e.name,o),u=new Map,c=(e,t)=>{var n;const s=null!==(n=t.getTransformNode())&&void 0!==n?n:t;let o=u.get(s);if(o){if(o.has(e.targetProperty))return}else o=new Set,u.set(s,o);o.add(e.targetProperty),l.addTargetedAnimation(e,s)},d=new Map;for(const e of n){const t=s.get(e.id);if(t)for(const n of e.bones){const e=this._getSourceBone(t,n.index);if(!e)continue;const s=d.get(n.modelId);s?s.push(e):d.set(n.modelId,[e])}}const h=new Map,m=new Map,f=[];for(const t of e.curveNodes)"DeformPercent"!==t.type?d.has(t.targetModelId)?(h.has(t.targetModelId)||h.set(t.targetModelId,[]),h.get(t.targetModelId).push(t)):(m.has(t.targetModelId)||m.set(t.targetModelId,[]),m.get(t.targetModelId).push(t)):f.push(t);const p=new Set;for(const t of n){const n=new Set(t.bones.filter(e=>2===e.inheritType).map(e=>e.modelId));if(0===n.size)continue;const o=s.get(t.id);if(o&&!o.bones.some(e=>this._bindRestBones.has(e))){for(const e of Array.from(n))p.add(e);for(const{bone:s,animations:r}of this._buildInheritedRigBoneAnimations(t,o,h,i,n,e.startTime,e.stopTime))for(const e of r)c(e,s)}}for(const[t,n]of Array.from(h)){if(p.has(t))continue;const s=d.get(t),o=i.get(t);if(s&&0!==s.length&&o)for(const t of s){const s=this._buildBoneAnimations(n,t.name,o,e.startTime,e.stopTime,this._bindRestBones.has(t)?t.getBindMatrix():void 0);for(const e of s)c(e,t)}}for(const[t,n]of Array.from(m)){const s=r.get(t);if(!s)continue;const o=i.get(t);if(!o)continue;const a=this._buildNodeAnimations(n,s.name,o,e.startTime,e.stopTime);for(const e of a)l.addTargetedAnimation(e,s)}for(const n of f){const s=n.targetModelId;let o=!1;for(const r of a){if(!r.morphTargetManager||o)continue;const i=r.metadata,a=null==i?void 0:i.fbxBlendShapeChannelTargets,u=null==a?void 0:a.get(s);if(u&&n.curves.length>0){const s=30;for(let o=0;o<u.targetIndices.length;o++){const i=r.morphTargetManager.getTarget(u.targetIndices[o]);if(!i)continue;const a=new t.Animation(`${i.name}_influence`,"influence",s,t.Animation.ANIMATIONTYPE_FLOAT,t.Animation.ANIMATIONLOOPMODE_CYCLE),c=jt(n.curves[0],s,e.startTime,e.stopTime,e=>{var t;return null!==(t=Ut(e,u.fullWeights,u.targetIndices.length)[o])&&void 0!==t?t:0});a.setKeys(c),l.addTargetedAnimation(a,i)}o=!0;continue}const c=null==i?void 0:i.fbxBlendShapeChannelIds;if(!c)continue;const d=c.get(s);if(void 0===d)continue;const h=r.morphTargetManager.getTarget(d);if(h&&n.curves.length>0){const s=30,r=new t.Animation(`${h.name}_influence`,"influence",s,t.Animation.ANIMATIONTYPE_FLOAT,t.Animation.ANIMATIONLOOPMODE_CYCLE),i=jt(n.curves[0],s,e.startTime,e.stopTime,e=>e/100);r.setKeys(i),l.addTargetedAnimation(r,h),o=!0}}}return l.targetedAnimations.length>0?(l.normalize(30*e.startTime,30*e.stopTime),l):(l.dispose(),null)}_buildInheritedRigBoneAnimations(e,n,s,o,r,i,a){const l=30,u=new Set;for(let t=0;t<e.bones.length;t++)if(r.has(e.bones[t].modelId))for(let n=t;n>=0;n=e.bones[n].parentIndex)u.add(e.bones[n].modelId);const c=Wt(e.bones.filter(e=>u.has(e.modelId)).flatMap(e=>{var t;return null!==(t=s.get(e.modelId))&&void 0!==t?t:[]}),l,i,a);if(0===c.length)return[];const d=e.bones.map(()=>({posKeys:[],rotKeys:[],sclKeys:[],prevQuat:null})),h=e.bones.map(()=>({posKeys:[],rotKeys:[],sclKeys:[],prevQuat:null})),m=e.bones.map((e,s)=>{const r=this._getSourceBone(n,s),i=o.get(e.modelId);if(!r||!i||!this._bindRestBones.has(r))return null;const a=kt._computeFBXModelLocalMatrix(i),l=new t.Matrix;return a.invertToRef(l),l});for(const i of c){const a=e.bones.map((e,r)=>{var a,l;const u=o.get(e.modelId),c=null!==(a=s.get(e.modelId))&&void 0!==a?a:[];let d=u?this._sampleModelLocalMatrix(u,c,i):t.Matrix.Identity();const h=m[r];if(h){const e=this._getSourceBone(n,r);d=(null!==(l=null==e?void 0:e.getBindMatrix())&&void 0!==l?l:t.Matrix.Identity()).multiply(h).multiply(d)}return d}),u=e.bones.map(e=>{var t;const n=o.get(e.modelId),r=null!==(t=s.get(e.modelId))&&void 0!==t?t:[];return n?this._sampleModelScale(n,r,i):e.scale}),c=i*l;for(let t=0;t<a.length;t++){if(!r.has(e.bones[t].modelId))continue;const n=e.bones[t].parentIndex,s=n>=0?u[n]:e.bones[t].scale,o=kt._splitParentScaleCompensatedLocalMatrix(a[t],s);kt._pushMatrixKeys(d[t],c,o.boneLocalMatrix),kt._pushMatrixKeys(h[t],c,o.helperLocalMatrix)}}const f=[];for(let s=0;s<e.bones.length;s++){if(!r.has(e.bones[s].modelId))continue;const o=this._getSourceBone(n,s);if(!o)continue;const{posKeys:i,rotKeys:a,sclKeys:u}=d[s],c=[];if(!this._isVector3KeysConstant(i)){const e=new t.Animation(`${o.name}_position`,"position",l,t.Animation.ANIMATIONTYPE_VECTOR3,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(i),c.push(e)}if(!zt(a)){const e=new t.Animation(`${o.name}_rotation`,"rotationQuaternion",l,t.Animation.ANIMATIONTYPE_QUATERNION,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(a),c.push(e)}if(!this._isVector3KeysConstant(u)){const e=new t.Animation(`${o.name}_scaling`,"scaling",l,t.Animation.ANIMATIONTYPE_VECTOR3,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(u),c.push(e)}c.length>0&&f.push({bone:o,animations:c});const m=this._getScaleCompensationHelper(n,s);if(!m)continue;const p=[],{posKeys:_,rotKeys:g,sclKeys:y}=h[s];if(!this._isVector3KeysConstant(_)){const e=new t.Animation(`${m.name}_position`,"position",l,t.Animation.ANIMATIONTYPE_VECTOR3,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(_),p.push(e)}if(!zt(g)){const e=new t.Animation(`${m.name}_rotation`,"rotationQuaternion",l,t.Animation.ANIMATIONTYPE_QUATERNION,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(g),p.push(e)}if(!this._isVector3KeysConstant(y)){const e=new t.Animation(`${m.name}_scaling`,"scaling",l,t.Animation.ANIMATIONTYPE_VECTOR3,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(y),p.push(e)}p.length>0&&f.push({bone:m,animations:p})}return f}static _pushMatrixKeys(e,n,s){const o=new t.Vector3,r=new t.Quaternion,i=new t.Vector3;s.decompose(o,r,i),e.prevQuat&&t.Quaternion.Dot(e.prevQuat,r)<0&&r.scaleInPlace(-1),e.prevQuat=r,e.posKeys.push({frame:n,value:i}),e.rotKeys.push({frame:n,value:r}),e.sclKeys.push({frame:n,value:o})}_buildNodeAnimations(e,n,s,o,r){var i,a,l,u,c,d,h,m,f;const p=e.find(e=>"T"===e.type),_=e.find(e=>"R"===e.type),g=e.find(e=>"S"===e.type),y=Wt(e,30,o,r);if(0===y.length)return[];const v=null==p?void 0:p.curves.find(e=>"d|X"===e.channel),b=null==p?void 0:p.curves.find(e=>"d|Y"===e.channel),x=null==p?void 0:p.curves.find(e=>"d|Z"===e.channel),T=null==_?void 0:_.curves.find(e=>"d|X"===e.channel),A=null==_?void 0:_.curves.find(e=>"d|Y"===e.channel),M=null==_?void 0:_.curves.find(e=>"d|Z"===e.channel),w=null==g?void 0:g.curves.find(e=>"d|X"===e.channel),C=null==g?void 0:g.curves.find(e=>"d|Y"===e.channel),R=null==g?void 0:g.curves.find(e=>"d|Z"===e.channel),S=[],O=[],F=[];let E=null;for(const e of y){const n=30*e,o=null!==(i=it(v,e))&&void 0!==i?i:s.translation[0],r=null!==(a=it(b,e))&&void 0!==a?a:s.translation[1],p=null!==(l=it(x,e))&&void 0!==l?l:s.translation[2],_=null!==(u=it(T,e))&&void 0!==u?u:s.rotation[0],g=null!==(c=it(A,e))&&void 0!==c?c:s.rotation[1],y=null!==(d=it(M,e))&&void 0!==d?d:s.rotation[2],I=null!==(h=it(w,e))&&void 0!==h?h:s.scale[0],L=null!==(m=it(C,e))&&void 0!==m?m:s.scale[1],P=null!==(f=it(R,e))&&void 0!==f?f:s.scale[2],B=kt._computeFBXLocalMatrix([o,r,p],[_,g,y],[I,L,P],s.preRotation,s.postRotation,s.rotationPivot,s.scalingPivot,s.rotationOffset,s.scalingOffset,s.rotationOrder),N=new t.Vector3,k=new t.Quaternion,D=new t.Vector3;B.decompose(N,k,D),E&&t.Quaternion.Dot(E,k)<0&&k.scaleInPlace(-1),E=k,S.push({frame:n,value:D}),O.push({frame:n,value:k}),F.push({frame:n,value:N})}const I=[];if(!this._isVector3KeysConstant(S)){const e=new t.Animation(`${n}_position`,"position",30,t.Animation.ANIMATIONTYPE_VECTOR3,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(S),I.push(e)}if(_){const e=new t.Animation(`${n}_rotation`,"rotationQuaternion",30,t.Animation.ANIMATIONTYPE_QUATERNION,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(O),I.push(e)}if(!this._isVector3KeysConstant(F)){const e=new t.Animation(`${n}_scaling`,"scaling",30,t.Animation.ANIMATIONTYPE_VECTOR3,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(F),I.push(e)}return I}_isVector3KeysConstant(e){if(e.length<2)return!0;const t=e[0].value;for(let n=1;n<e.length;n++){const s=e[n].value;if(Math.abs(s.x-t.x)>1e-4||Math.abs(s.y-t.y)>1e-4||Math.abs(s.z-t.z)>1e-4)return!1}return!0}_sampleModelLocalMatrix(e,t,n,s){var o,r,i,a,l,u,c,d,h;const m=t.find(e=>"T"===e.type),f=t.find(e=>"R"===e.type),p=t.find(e=>"S"===e.type),_=null==m?void 0:m.curves.find(e=>"d|X"===e.channel),g=null==m?void 0:m.curves.find(e=>"d|Y"===e.channel),y=null==m?void 0:m.curves.find(e=>"d|Z"===e.channel),v=null==f?void 0:f.curves.find(e=>"d|X"===e.channel),b=null==f?void 0:f.curves.find(e=>"d|Y"===e.channel),x=null==f?void 0:f.curves.find(e=>"d|Z"===e.channel),T=null==p?void 0:p.curves.find(e=>"d|X"===e.channel),A=null==p?void 0:p.curves.find(e=>"d|Y"===e.channel),M=null==p?void 0:p.curves.find(e=>"d|Z"===e.channel);return kt._computeFBXLocalMatrix([null!==(o=it(_,n))&&void 0!==o?o:e.translation[0],null!==(r=it(g,n))&&void 0!==r?r:e.translation[1],null!==(i=it(y,n))&&void 0!==i?i:e.translation[2]],[null!==(a=it(v,n))&&void 0!==a?a:e.rotation[0],null!==(l=it(b,n))&&void 0!==l?l:e.rotation[1],null!==(u=it(x,n))&&void 0!==u?u:e.rotation[2]],null!=s?s:[null!==(c=it(T,n))&&void 0!==c?c:e.scale[0],null!==(d=it(A,n))&&void 0!==d?d:e.scale[1],null!==(h=it(M,n))&&void 0!==h?h:e.scale[2]],e.preRotation,e.postRotation,e.rotationPivot,e.scalingPivot,e.rotationOffset,e.scalingOffset,e.rotationOrder)}_sampleModelScale(e,t,n){var s,o,r;const i=t.find(e=>"S"===e.type),a=null==i?void 0:i.curves.find(e=>"d|X"===e.channel),l=null==i?void 0:i.curves.find(e=>"d|Y"===e.channel),u=null==i?void 0:i.curves.find(e=>"d|Z"===e.channel);return[null!==(s=it(a,n))&&void 0!==s?s:e.scale[0],null!==(o=it(l,n))&&void 0!==o?o:e.scale[1],null!==(r=it(u,n))&&void 0!==r?r:e.scale[2]]}_buildBoneAnimations(e,n,s,o,r,i){var a,l,u,c,d,h,m,f,p;const _=e.find(e=>"T"===e.type),g=e.find(e=>"R"===e.type),y=e.find(e=>"S"===e.type),v=Wt(e,30,o,r);if(0===v.length)return[];const b=null==_?void 0:_.curves.find(e=>"d|X"===e.channel),x=null==_?void 0:_.curves.find(e=>"d|Y"===e.channel),T=null==_?void 0:_.curves.find(e=>"d|Z"===e.channel),A=null==g?void 0:g.curves.find(e=>"d|X"===e.channel),M=null==g?void 0:g.curves.find(e=>"d|Y"===e.channel),w=null==g?void 0:g.curves.find(e=>"d|Z"===e.channel),C=null==y?void 0:y.curves.find(e=>"d|X"===e.channel),R=null==y?void 0:y.curves.find(e=>"d|Y"===e.channel),S=null==y?void 0:y.curves.find(e=>"d|Z"===e.channel),O=[],F=[],E=[];let I=null,L=null;if(i){const e=kt._computeFBXLocalMatrix(s.translation,s.rotation,s.scale,s.preRotation,s.postRotation,s.rotationPivot,s.scalingPivot,s.rotationOffset,s.scalingOffset,s.rotationOrder);L=new t.Matrix,e.invertToRef(L)}for(const e of v){const n=30*e,o=null!==(a=it(b,e))&&void 0!==a?a:s.translation[0],r=null!==(l=it(x,e))&&void 0!==l?l:s.translation[1],_=null!==(u=it(T,e))&&void 0!==u?u:s.translation[2],g=null!==(c=it(A,e))&&void 0!==c?c:s.rotation[0],y=null!==(d=it(M,e))&&void 0!==d?d:s.rotation[1],v=null!==(h=it(w,e))&&void 0!==h?h:s.rotation[2],P=null!==(m=it(C,e))&&void 0!==m?m:s.scale[0],B=null!==(f=it(R,e))&&void 0!==f?f:s.scale[1],N=null!==(p=it(S,e))&&void 0!==p?p:s.scale[2],k=kt._computeFBXLocalMatrix([o,r,_],[g,y,v],[P,B,N],s.preRotation,s.postRotation,s.rotationPivot,s.scalingPivot,s.rotationOffset,s.scalingOffset,s.rotationOrder),D=L&&i?i.multiply(L).multiply(k):k,G=new t.Vector3,V=new t.Quaternion,H=new t.Vector3;D.decompose(G,V,H),I&&t.Quaternion.Dot(I,V)<0&&V.scaleInPlace(-1),I=V,O.push({frame:n,value:H}),F.push({frame:n,value:V}),E.push({frame:n,value:G})}const P=[];if(!this._isVector3KeysConstant(O)){const e=new t.Animation(`${n}_position`,"position",30,t.Animation.ANIMATIONTYPE_VECTOR3,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(O),P.push(e)}if(g){const e=new t.Animation(`${n}_rotation`,"rotationQuaternion",30,t.Animation.ANIMATIONTYPE_QUATERNION,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(F),P.push(e)}if(!this._isVector3KeysConstant(E)){const e=new t.Animation(`${n}_scaling`,"scaling",30,t.Animation.ANIMATIONTYPE_VECTOR3,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(E),P.push(e)}return P}_buildNameFilter(e){if(!e)return null;if("string"==typeof e)return""===e?null:t=>t===e;if(0===e.length)return null;const t=new Set(e);return e=>t.has(e)}}function Dt(e){const t=new Float32Array(e.length);for(let n=0;n<e.length;n++)t[n]=e[n];return t}function Gt(e,t,n,s,o,r,i,a,l,u,c,d,h,m,f,p){var _;const g=function(e,t,n,s){const o=3*t,r=3*n,i=3*s,a=e[r]-e[o],l=e[r+1]-e[o+1],u=e[r+2]-e[o+2],c=e[i]-e[o],d=e[i+1]-e[o+1],h=e[i+2]-e[o+2],m=Math.hypot(a,l,u),f=Math.hypot(c,d,h);if(m<=1e-8||f<=1e-8)return 0;const p=(a*c+l*d+u*h)/(m*f);return Math.acos(Math.max(-1,Math.min(1,p)))}(u,e,t,n);if(g<=1e-8)return;const y=function(e,t,n,s,o,r,i,a,l,u,c,d){const h=3*e,m=3*e,f=2*e,[p,_,g]=Vt(l[m],l[m+1],l[m+2]),y=function(e,t,n,s,o,r,i,a,l){return(t*r-n*o)*i+(n*s-e*r)*a+(e*o-t*s)*l<0?-1:1}(p,_,g,t,n,s,o,r,i);return[c?`cp:${c[e]}`:`p:${Ht(a[h])},${Ht(a[h+1])},${Ht(a[h+2])}`,Ht(p),Ht(_),Ht(g),Ht(u[f]),Ht(u[f+1]),y,d].join("|")}(e,s,o,r,i,a,l,u,c,d,h,m);let v=f.get(y);v||(v={tx:0,ty:0,tz:0,bx:0,by:0,bz:0},f.set(y,v)),v.tx+=s*g,v.ty+=o*g,v.tz+=r*g,v.bx+=i*g,v.by+=a*g,v.bz+=l*g,null!==(_=p[e])&&void 0!==_||(p[e]=y)}function Vt(e,t,n){const s=Math.hypot(e,t,n);return s>1e-8?[e/s,t/s,n/s]:[0,0,1]}function Ht(e){const t=Math.round(1e6*e);return Object.is(t,-0)?0:t}function Kt(e,t,n){const s=Math.abs(e)<.9?1:0,o=1===s?0:1,r=e*s+t*o;let i=s-e*r,a=o-t*r,l=-n*r;const u=Math.hypot(i,a,l);return u<=1e-8?[1,0,0]:(i/=u,a/=u,l/=u,[i,a,l])}function $t(e,n,s,o,r,i){const a=s.length/3,l=new Float32Array(3*a),u=null!==e.normals&&null!==o?new Float32Array(3*a):null;for(let e=0;e<l.length;e++)l[e]=s[e];if(u&&o)for(let e=0;e<u.length;e++)u[e]=o[e];const c=new Map;for(let t=0;t<e.indices.length;t++)c.set(e.indices[t],t);for(let s=0;s<a;s++){const o=n[s],a=c.get(o);if(void 0===a)continue;let d=e.vertices[3*a],h=e.vertices[3*a+1],m=e.vertices[3*a+2];if(r){const e=t.Vector3.TransformNormal(new t.Vector3(d,h,m),r);d=e.x,h=e.y,m=e.z}if(l[3*s]+=d,l[3*s+1]+=h,l[3*s+2]+=m,u&&e.normals){let n=e.normals[3*a],o=e.normals[3*a+1],r=e.normals[3*a+2];if(i){const e=t.Vector3.TransformNormal(new t.Vector3(n,o,r),i);e.lengthSquared()>0&&e.normalize(),n=e.x,o=e.y,r=e.z}u[3*s]+=n,u[3*s+1]+=o,u[3*s+2]+=r}}return{positions:l,normals:u}}function Ut(e,t,n){if(n<=0)return[];if(!t||t.length!==n||1===n)return[qt(e/((null==t?void 0:t[0])&&0!==t[0]?t[0]:100))];const s=new Array(n).fill(0);if(e<=t[0])return s[0]=0===t[0]?e<=0?1:0:qt(e/t[0]),s;for(let n=1;n<t.length;n++){const o=t[n-1],r=t[n];if(e>r)continue;const i=r-o;if(Math.abs(i)<1e-6)return s[n]=1,s;const a=qt((e-o)/i);return s[n-1]=1-a,s[n]=a,s}return s[n-1]=1,s}function qt(e){return Math.max(0,Math.min(1,e))}function Wt(e,t,n,s){let o=Number.POSITIVE_INFINITY,r=Number.NEGATIVE_INFINITY;const i=new Set;for(const t of e)for(const e of t.curves)for(const t of e.keys)o=Math.min(o,t.time),r=Math.max(r,t.time),t.time>=n&&t.time<=s&&i.add(t.time);if(!Number.isFinite(o)||!Number.isFinite(r))return[];const a=s>n?n:o,l=s>n?s:r,u=new Set([a,l,...Array.from(i)]),c=Math.ceil(a*t),d=Math.floor(l*t);for(let e=c;e<=d;e++)u.add(e/t);return Array.from(u).sort((e,t)=>e-t)}function zt(e){if(e.length<2)return!0;const t=e[0].value;for(let n=1;n<e.length;n++){const s=e[n].value;if(Math.abs(s.x-t.x)>1e-4||Math.abs(s.y-t.y)>1e-4||Math.abs(s.z-t.z)>1e-4||Math.abs(s.w-t.w)>1e-4)return!1}return!0}function jt(e,t,n,s,o){var r,i,a,l,u,c;const d=function(e,t,n){var s,o,r,i;return n>t?{start:t,stop:n}:{start:null!==(o=null===(s=e.keys[0])||void 0===s?void 0:s.time)&&void 0!==o?o:0,stop:null!==(i=null===(r=e.keys[e.keys.length-1])||void 0===r?void 0:r.time)&&void 0!==i?i:0}}(e,n,s),h=e.keys.filter(e=>e.time>=d.start&&e.time<=d.stop).map(e=>({source:e,frame:e.time*t,value:o(e.value)}));h.some(e=>Math.abs(e.source.time-d.start)<1e-6)||h.unshift({source:{time:d.start,value:null!==(r=it(e,d.start))&&void 0!==r?r:0,interpolation:"linear"},frame:d.start*t,value:o(null!==(i=it(e,d.start))&&void 0!==i?i:0)}),h.some(e=>Math.abs(e.source.time-d.stop)<1e-6)||h.push({source:{time:d.stop,value:null!==(a=it(e,d.stop))&&void 0!==a?a:0,interpolation:"linear"},frame:d.stop*t,value:o(null!==(l=it(e,d.stop))&&void 0!==l?l:0)});const m=h.map(e=>({frame:e.frame,value:e.value}));for(let e=0;e<h.length-1;e++){const n=h[e].source,s=m[e+1];if("constant"===n.interpolation){m[e].interpolation=1;continue}if("cubic"!==n.interpolation)continue;const r=h[e+1].source,i=Math.max(r.time-n.time,1e-6),a=(r.value-n.value)/i;m[e].outTangent=Xt(null!==(u=n.rightSlope)&&void 0!==u?u:a,o)/t,s.inTangent=Xt(null!==(c=n.nextLeftSlope)&&void 0!==c?c:a,o)/t}return m}function Xt(e,t){return t(e)-t(0)}let Yt=!1;function Qt(){Yt||(Yt=!0,t.RegisterSceneLoaderPlugin(new kt))}Qt();var Zt={__proto__:null,FBXFileLoader:kt,RegisterFBXFileLoader:Qt};function Jt(e,t,n,s){const o={externalResourceFunction:s};return n&&(o.uri="file:"===t?n:t+n),ArrayBuffer.isView(e)?GLTFValidator.validateBytes(e,o):GLTFValidator.validateString(e,o)}function en(){const e=[];onmessage=t=>{const n=t.data;switch(n.id){case"init":importScripts(n.url);break;case"validate":Jt(n.data,n.rootUrl,n.fileName,t=>new Promise((n,s)=>{const o=e.length;e.push({resolve:n,reject:s}),postMessage({id:"getExternalResource",index:o,uri:t})})).then(e=>{postMessage({id:"validate.resolve",value:e})},e=>{postMessage({id:"validate.reject",reason:e})});break;case"getExternalResource.resolve":e[n.index].resolve(n.value);break;case"getExternalResource.reject":e[n.index].reject(n.reason)}}}class tn{static ValidateAsync(e,n,s,o){return"function"==typeof Worker?new Promise((r,i)=>{const a=`${Jt}(${en})()`,l=URL.createObjectURL(new Blob([a],{type:"application/javascript"})),u=new Worker(l),c=e=>{u.removeEventListener("error",c),u.removeEventListener("message",d),i(e)},d=e=>{const t=e.data;switch(t.id){case"getExternalResource":o(t.uri).then(e=>{u.postMessage({id:"getExternalResource.resolve",index:t.index,value:e},[e.buffer])},e=>{u.postMessage({id:"getExternalResource.reject",index:t.index,reason:e})});break;case"validate.resolve":u.removeEventListener("error",c),u.removeEventListener("message",d),tn._LastResults=t.value,r(t.value),u.terminate();break;case"validate.reject":u.removeEventListener("error",c),u.removeEventListener("message",d),i(t.reason),u.terminate()}};if(u.addEventListener("error",c),u.addEventListener("message",d),u.postMessage({id:"init",url:t.Tools.GetBabylonScriptURL(this.Configuration.url)}),ArrayBuffer.isView(e)){const t=e.slice();u.postMessage({id:"validate",data:t,rootUrl:n,fileName:s},[t.buffer])}else u.postMessage({id:"validate",data:e,rootUrl:n,fileName:s})}):(this._LoadScriptPromise||(this._LoadScriptPromise=t.Tools.LoadBabylonScriptAsync(this.Configuration.url)),this._LoadScriptPromise.then(()=>Jt(e,n,s,o)))}}tn.Configuration={url:`${t.Tools._DefaultCdnUrl}/gltf_validator.js`},tn._LastResults=null;var nn={__proto__:null,GLTFValidation:tn};const sn="Z2xURg",on={name:"gltf",extensions:{".gltf":{isBinary:!1,mimeType:"model/gltf+json"},".glb":{isBinary:!0,mimeType:"model/gltf-binary"}},canDirectLoad:e=>-1!==e.indexOf("asset")&&-1!==e.indexOf("version")||e.startsWith("data:base64,"+sn)||e.startsWith("data:;base64,"+sn)||e.startsWith("data:application/octet-stream;base64,"+sn)||e.startsWith("data:model/gltf-binary;base64,"+sn)};function rn(e,t,n){try{return Promise.resolve(new Uint8Array(e,t,n))}catch(e){return Promise.reject(e)}}var an,ln,un;e.GLTFLoaderCoordinateSystemMode=void 0,(an=e.GLTFLoaderCoordinateSystemMode||(e.GLTFLoaderCoordinateSystemMode={}))[an.AUTO=0]="AUTO",an[an.FORCE_RIGHT_HANDED=1]="FORCE_RIGHT_HANDED",e.GLTFLoaderAnimationStartMode=void 0,(ln=e.GLTFLoaderAnimationStartMode||(e.GLTFLoaderAnimationStartMode={}))[ln.NONE=0]="NONE",ln[ln.FIRST=1]="FIRST",ln[ln.ALL=2]="ALL",e.GLTFLoaderState=void 0,(un=e.GLTFLoaderState||(e.GLTFLoaderState={}))[un.LOADING=0]="LOADING",un[un.READY=1]="READY",un[un.COMPLETE=2]="COMPLETE";class cn{constructor(){this.alwaysComputeBoundingBox=!1,this.alwaysComputeSkeletonRootNode=!1,this.animationStartMode=e.GLTFLoaderAnimationStartMode.FIRST,this.compileMaterials=!1,this.compileShadowGenerators=!1,this.coordinateSystemMode=e.GLTFLoaderCoordinateSystemMode.AUTO,this.createInstances=!0,this.loadAllMaterials=!1,this.loadMorphTargets=!0,this.useMaxMorphTargetInfluencers=!0,this.loadNodeAnimations=!0,this.loadOnlyMaterials=!1,this.loadSkins=!0,this.skipMaterials=!1,this.targetFps=60,this.transparencyAsCoverage=!1,this.useClipPlane=!1,this.useGltfTextureNames=!1,this.useRangeRequests=!1,this.useSRGBBuffers=!0,this.validate=!1,this.useOpenPBR=!1,this.dontUseTransmissionHelper=!1}}const dn=new cn;class hn extends cn{constructor(){super(...arguments),this.extensionOptions={},this.preprocessUrlAsync=e=>Promise.resolve(e)}copyFrom(e){var t,n,s,o,r,i,a,l,u,c,d,h,m,f,p,_,g,y,v,b,x,T,A,M,w,C,R;e&&(this.alwaysComputeBoundingBox=null!==(t=e.alwaysComputeBoundingBox)&&void 0!==t?t:this.alwaysComputeBoundingBox,this.alwaysComputeSkeletonRootNode=null!==(n=e.alwaysComputeSkeletonRootNode)&&void 0!==n?n:this.alwaysComputeSkeletonRootNode,this.animationStartMode=null!==(s=e.animationStartMode)&&void 0!==s?s:this.animationStartMode,this.capturePerformanceCounters=null!==(o=e.capturePerformanceCounters)&&void 0!==o?o:this.capturePerformanceCounters,this.compileMaterials=null!==(r=e.compileMaterials)&&void 0!==r?r:this.compileMaterials,this.compileShadowGenerators=null!==(i=e.compileShadowGenerators)&&void 0!==i?i:this.compileShadowGenerators,this.coordinateSystemMode=null!==(a=e.coordinateSystemMode)&&void 0!==a?a:this.coordinateSystemMode,this.createInstances=null!==(l=e.createInstances)&&void 0!==l?l:this.createInstances,this.customRootNode=e.customRootNode,this.extensionOptions=null!==(u=e.extensionOptions)&&void 0!==u?u:this.extensionOptions,this.loadAllMaterials=null!==(c=e.loadAllMaterials)&&void 0!==c?c:this.loadAllMaterials,this.loadMorphTargets=null!==(d=e.loadMorphTargets)&&void 0!==d?d:this.loadMorphTargets,this.loadNodeAnimations=null!==(h=e.loadNodeAnimations)&&void 0!==h?h:this.loadNodeAnimations,this.loadOnlyMaterials=null!==(m=e.loadOnlyMaterials)&&void 0!==m?m:this.loadOnlyMaterials,this.loadSkins=null!==(f=e.loadSkins)&&void 0!==f?f:this.loadSkins,this.loggingEnabled=null!==(p=e.loggingEnabled)&&void 0!==p?p:this.loggingEnabled,this.onCameraLoaded=e.onCameraLoaded,this.onMaterialLoaded=e.onMaterialLoaded,this.onMeshLoaded=e.onMeshLoaded,this.onParsed=e.onParsed,this.onSkinLoaded=e.onSkinLoaded,this.onTextureLoaded=e.onTextureLoaded,this.onValidated=e.onValidated,this.preprocessUrlAsync=null!==(_=e.preprocessUrlAsync)&&void 0!==_?_:this.preprocessUrlAsync,this.skipMaterials=null!==(g=e.skipMaterials)&&void 0!==g?g:this.skipMaterials,this.targetFps=null!==(y=e.targetFps)&&void 0!==y?y:this.targetFps,this.transparencyAsCoverage=null!==(v=e.transparencyAsCoverage)&&void 0!==v?v:this.transparencyAsCoverage,this.useClipPlane=null!==(b=e.useClipPlane)&&void 0!==b?b:this.useClipPlane,this.useGltfTextureNames=null!==(x=e.useGltfTextureNames)&&void 0!==x?x:this.useGltfTextureNames,this.useMaxMorphTargetInfluencers=null!==(T=e.useMaxMorphTargetInfluencers)&&void 0!==T?T:this.useMaxMorphTargetInfluencers,this.useOpenPBR=null!==(A=e.useOpenPBR)&&void 0!==A?A:this.useOpenPBR,this.useRangeRequests=null!==(M=e.useRangeRequests)&&void 0!==M?M:this.useRangeRequests,this.useSRGBBuffers=null!==(w=e.useSRGBBuffers)&&void 0!==w?w:this.useSRGBBuffers,this.validate=null!==(C=e.validate)&&void 0!==C?C:this.validate,this.dontUseTransmissionHelper=null!==(R=e.dontUseTransmissionHelper)&&void 0!==R?R:this.dontUseTransmissionHelper)}}class mn extends hn{constructor(e){super(),this.onParsedObservable=new t.Observable,this.onMeshLoadedObservable=new t.Observable,this.onSkinLoadedObservable=new t.Observable,this.onTextureLoadedObservable=new t.Observable,this.onMaterialLoadedObservable=new t.Observable,this.onCameraLoadedObservable=new t.Observable,this.onCompleteObservable=new t.Observable,this.onErrorObservable=new t.Observable,this.onDisposeObservable=new t.Observable,this.onExtensionLoadedObservable=new t.Observable,this.onValidatedObservable=new t.Observable,this._loader=null,this._state=null,this._requests=new Array,this.name=on.name,this.extensions=on.extensions,this.onLoaderStateChangedObservable=new t.Observable,this._logIndentLevel=0,this._loggingEnabled=!1,this._log=this._logDisabled,this._capturePerformanceCounters=!1,this._startPerformanceCounter=this._startPerformanceCounterDisabled,this._endPerformanceCounter=this._endPerformanceCounterDisabled,this.copyFrom(Object.assign(Object.assign({},dn),e))}set onParsed(e){this._onParsedObserver&&this.onParsedObservable.remove(this._onParsedObserver),e&&(this._onParsedObserver=this.onParsedObservable.add(e))}set onMeshLoaded(e){this._onMeshLoadedObserver&&this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver),e&&(this._onMeshLoadedObserver=this.onMeshLoadedObservable.add(e))}set onSkinLoaded(e){this._onSkinLoadedObserver&&this.onSkinLoadedObservable.remove(this._onSkinLoadedObserver),e&&(this._onSkinLoadedObserver=this.onSkinLoadedObservable.add(t=>e(t.node,t.skinnedNode)))}set onTextureLoaded(e){this._onTextureLoadedObserver&&this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver),e&&(this._onTextureLoadedObserver=this.onTextureLoadedObservable.add(e))}set onMaterialLoaded(e){this._onMaterialLoadedObserver&&this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver),e&&(this._onMaterialLoadedObserver=this.onMaterialLoadedObservable.add(e))}set onCameraLoaded(e){this._onCameraLoadedObserver&&this.onCameraLoadedObservable.remove(this._onCameraLoadedObserver),e&&(this._onCameraLoadedObserver=this.onCameraLoadedObservable.add(e))}set onComplete(e){this._onCompleteObserver&&this.onCompleteObservable.remove(this._onCompleteObserver),this._onCompleteObserver=this.onCompleteObservable.add(e)}set onError(e){this._onErrorObserver&&this.onErrorObservable.remove(this._onErrorObserver),this._onErrorObserver=this.onErrorObservable.add(e)}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}set onExtensionLoaded(e){this._onExtensionLoadedObserver&&this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver),this._onExtensionLoadedObserver=this.onExtensionLoadedObservable.add(e)}get loggingEnabled(){return this._loggingEnabled}set loggingEnabled(e){this._loggingEnabled!==e&&(this._loggingEnabled=e,this._loggingEnabled?this._log=this._logEnabled:this._log=this._logDisabled)}get capturePerformanceCounters(){return this._capturePerformanceCounters}set capturePerformanceCounters(e){this._capturePerformanceCounters!==e&&(this._capturePerformanceCounters=e,this._capturePerformanceCounters?(this._startPerformanceCounter=this._startPerformanceCounterEnabled,this._endPerformanceCounter=this._endPerformanceCounterEnabled):(this._startPerformanceCounter=this._startPerformanceCounterDisabled,this._endPerformanceCounter=this._endPerformanceCounterDisabled))}set onValidated(e){this._onValidatedObserver&&this.onValidatedObservable.remove(this._onValidatedObserver),this._onValidatedObserver=this.onValidatedObservable.add(e)}dispose(){this._loader&&(this._loader.dispose(),this._loader=null);for(const e of this._requests)e.abort();this._requests.length=0,delete this._progressCallback,this.preprocessUrlAsync=e=>Promise.resolve(e),this.onMeshLoadedObservable.clear(),this.onSkinLoadedObservable.clear(),this.onTextureLoadedObservable.clear(),this.onMaterialLoadedObservable.clear(),this.onCameraLoadedObservable.clear(),this.onCompleteObservable.clear(),this.onExtensionLoadedObservable.clear(),this.onDisposeObservable.notifyObservers(void 0),this.onDisposeObservable.clear()}loadFile(e,n,s,o,r,i,a,l){if(ArrayBuffer.isView(n))return this._loadBinary(e,n,s,o,a,l),null;this._progressCallback=r;const u=n.name||t.Tools.GetFilename(n);if(i){if(this.useRangeRequests){this.validate&&t.Logger.Warn("glTF validation is not supported when range requests are enabled");const s={abort:()=>{},onCompleteObservable:new t.Observable},r={readAsync:(t,s)=>new Promise((o,r)=>{this._loadFile(e,n,e=>{o(new Uint8Array(e))},!0,e=>{r(e)},e=>{e.setRequestHeader("Range",`bytes=${t}-${t+s-1}`)})}),byteLength:0};return this._unpackBinaryAsync(new t.DataReader(r)).then(e=>{s.onCompleteObservable.notifyObservers(s),o(e)},a?e=>a(void 0,e):void 0),s}return this._loadFile(e,n,n=>{this._validate(e,new Uint8Array(n,0,n.byteLength),s,u),this._unpackBinaryAsync(new t.DataReader({readAsync:(e,t)=>rn(n,e,t),byteLength:n.byteLength})).then(e=>{o(e)},a?e=>a(void 0,e):void 0)},!0,a)}return this._loadFile(e,n,t=>{try{this._validate(e,t,s,u),o({json:this._parseJson(t)})}catch(e){a&&a()}},!1,a)}_loadBinary(e,n,s,o,r,i){this._validate(e,new Uint8Array(n.buffer,n.byteOffset,n.byteLength),s,i),this._unpackBinaryAsync(new t.DataReader({readAsync:(e,t)=>function(e,t,n){try{if(t<0||t>=e.byteLength)throw new RangeError("Offset is out of range.");if(t+n>e.byteLength)throw new RangeError("Length is out of range.");return Promise.resolve(new Uint8Array(e.buffer,e.byteOffset+t,n))}catch(e){return Promise.reject(e)}}(n,e,t),byteLength:n.byteLength})).then(e=>{o(e)},r?e=>r(void 0,e):void 0)}importMeshAsync(e,t,n,s,o,r){return Promise.resolve().then(()=>(this.onParsedObservable.notifyObservers(n),this.onParsedObservable.clear(),this._log(`Loading ${r||""}`),this._loader=this._getLoader(n),this._loader.importMeshAsync(e,t,null,n,s,o,r)))}loadAsync(e,t,n,s,o){return Promise.resolve().then(()=>(this.onParsedObservable.notifyObservers(t),this.onParsedObservable.clear(),this._log(`Loading ${o||""}`),this._loader=this._getLoader(t),this._loader.loadAsync(e,t,n,s,o)))}loadAssetContainerAsync(e,n,s,o,r){return Promise.resolve().then(()=>{this.onParsedObservable.notifyObservers(n),this.onParsedObservable.clear(),this._log(`Loading ${r||""}`),this._loader=this._getLoader(n);const i=new t.AssetContainer(e),a=[];this.onMaterialLoadedObservable.add(e=>{a.push(e)});const l=[];this.onTextureLoadedObservable.add(e=>{l.push(e)});const u=[];this.onCameraLoadedObservable.add(e=>{u.push(e)});const c=[];return this.onMeshLoadedObservable.add(e=>{e.morphTargetManager&&c.push(e.morphTargetManager)}),this._loader.importMeshAsync(null,e,i,n,s,o,r).then(e=>(Array.prototype.push.apply(i.geometries,e.geometries),Array.prototype.push.apply(i.meshes,e.meshes),Array.prototype.push.apply(i.particleSystems,e.particleSystems),Array.prototype.push.apply(i.skeletons,e.skeletons),Array.prototype.push.apply(i.animationGroups,e.animationGroups),Array.prototype.push.apply(i.materials,a),Array.prototype.push.apply(i.textures,l),Array.prototype.push.apply(i.lights,e.lights),Array.prototype.push.apply(i.transformNodes,e.transformNodes),Array.prototype.push.apply(i.cameras,u),Array.prototype.push.apply(i.morphTargetManagers,c),i))})}canDirectLoad(e){return on.canDirectLoad(e)}directLoad(e,n){if(n.startsWith("base64,"+sn)||n.startsWith(";base64,"+sn)||n.startsWith("application/octet-stream;base64,"+sn)||n.startsWith("model/gltf-binary;base64,"+sn)){const s=t.DecodeBase64UrlToBinary(n);return this._validate(e,new Uint8Array(s,0,s.byteLength)),this._unpackBinaryAsync(new t.DataReader({readAsync:(e,t)=>rn(s,e,t),byteLength:s.byteLength}))}return this._validate(e,n),Promise.resolve({json:this._parseJson(n)})}createPlugin(e){return new mn(e[on.name])}get loaderState(){return this._state}whenCompleteAsync(){return new Promise((e,t)=>{this.onCompleteObservable.addOnce(()=>{e()}),this.onErrorObservable.addOnce(e=>{t(e)})})}_setState(t){this._state!==t&&(this._state=t,this.onLoaderStateChangedObservable.notifyObservers(this._state),this._log(e.GLTFLoaderState[this._state]))}_loadFile(e,t,n,s,o,r){const i=e._loadFile(t,n,e=>{this._onProgress(e,i)},!0,s,o,r);return i.onCompleteObservable.add(()=>{i._lengthComputable=!0,i._total=i._loaded}),this._requests.push(i),i}_onProgress(e,t){if(!this._progressCallback)return;t._lengthComputable=e.lengthComputable,t._loaded=e.loaded,t._total=e.total;let n=!0,s=0,o=0;for(const e of this._requests){if(void 0===e._lengthComputable||void 0===e._loaded||void 0===e._total)return;n=n&&e._lengthComputable,s+=e._loaded,o+=e._total}this._progressCallback({lengthComputable:n,loaded:s,total:n?o:0})}_validate(e,n,s="",o=""){this.validate&&(this._startPerformanceCounter("Validate JSON"),tn.ValidateAsync(n,s,o,t=>this.preprocessUrlAsync(s+t).then(t=>e._loadFileAsync(t,void 0,!0,!0).then(e=>new Uint8Array(e,0,e.byteLength)))).then(e=>{this._endPerformanceCounter("Validate JSON"),this.onValidatedObservable.notifyObservers(e),this.onValidatedObservable.clear()},e=>{this._endPerformanceCounter("Validate JSON"),t.Tools.Warn(`Failed to validate: ${e.message}`),this.onValidatedObservable.clear()}))}_getLoader(e){const t=e.json.asset||{};this._log(`Asset version: ${t.version}`),t.minVersion&&this._log(`Asset minimum version: ${t.minVersion}`),t.generator&&this._log(`Asset generator: ${t.generator}`);const n=mn._parseVersion(t.version);if(!n)throw new Error("Invalid version: "+t.version);if(void 0!==t.minVersion){const e=mn._parseVersion(t.minVersion);if(!e)throw new Error("Invalid minimum version: "+t.minVersion);if(mn._compareVersion(e,{major:2,minor:0})>0)throw new Error("Incompatible minimum version: "+t.minVersion)}const s={1:mn._CreateGLTF1Loader,2:mn._CreateGLTF2Loader}[n.major];if(!s)throw new Error("Unsupported version: "+t.version);return s(this)}_parseJson(e){this._startPerformanceCounter("Parse JSON"),this._log(`JSON length: ${e.length}`);const t=JSON.parse(e);return this._endPerformanceCounter("Parse JSON"),t}_unpackBinaryAsync(e){return this._startPerformanceCounter("Unpack Binary"),e.loadAsync(20).then(()=>{const n=e.readUint32();if(1179937895!==n)throw new t.RuntimeError("Unexpected magic: "+n,t.ErrorCodes.GLTFLoaderUnexpectedMagicError);const s=e.readUint32();this.loggingEnabled&&this._log(`Binary version: ${s}`);const o=e.readUint32();let r;switch(this.useRangeRequests||o===e.buffer.byteLength||t.Logger.Warn(`Length in header does not match actual data length: ${o} != ${e.buffer.byteLength}`),s){case 1:r=this._unpackBinaryV1Async(e,o);break;case 2:r=this._unpackBinaryV2Async(e,o);break;default:throw new Error("Unsupported version: "+s)}return this._endPerformanceCounter("Unpack Binary"),r})}_unpackBinaryV1Async(e,t){const n=e.readUint32(),s=e.readUint32();if(0!==s)throw new Error(`Unexpected content format: ${s}`);const o=t-e.byteOffset,r={json:this._parseJson(e.readString(n)),bin:null};if(0!==o){const t=e.byteOffset;r.bin={readAsync:(n,s)=>e.buffer.readAsync(t+n,s),byteLength:o}}return Promise.resolve(r)}_unpackBinaryV2Async(e,t){const n=1313821514,s=e.readUint32();if(e.readUint32()!==n)throw new Error("First chunk format is not JSON");return e.byteOffset+s===t?e.loadAsync(s).then(()=>({json:this._parseJson(e.readString(s)),bin:null})):e.loadAsync(s+8).then(()=>{const o={json:this._parseJson(e.readString(s)),bin:null},r=()=>{const s=e.readUint32();switch(e.readUint32()){case n:throw new Error("Unexpected JSON chunk");case 5130562:{const t=e.byteOffset;o.bin={readAsync:(n,s)=>e.buffer.readAsync(t+n,s),byteLength:s},e.skipBytes(s);break}default:e.skipBytes(s)}return e.byteOffset!==t?e.loadAsync(8).then(r):Promise.resolve(o)};return r()})}static _parseVersion(e){if("1.0"===e||"1.0.1"===e)return{major:1,minor:0};const t=(e+"").match(/^(\d+)\.(\d+)/);return t?{major:parseInt(t[1]),minor:parseInt(t[2])}:null}static _compareVersion(e,t){return e.major>t.major?1:e.major<t.major?-1:e.minor>t.minor?1:e.minor<t.minor?-1:0}_logOpen(e){this._log(e),this._logIndentLevel++}_logClose(){--this._logIndentLevel}_logEnabled(e){const n=mn._logSpaces.substring(0,2*this._logIndentLevel);t.Logger.Log(`${n}${e}`)}_logDisabled(e){}_startPerformanceCounterEnabled(e){t.Tools.StartPerformanceCounter(e)}_startPerformanceCounterDisabled(e){}_endPerformanceCounterEnabled(e){t.Tools.EndPerformanceCounter(e)}_endPerformanceCounterDisabled(e){}}mn.IncrementalLoading=!0,mn.HomogeneousCoordinates=!1,mn._logSpaces=" ";let fn=!1;function pn(){fn||(fn=!0,t.RegisterSceneLoaderPlugin(new mn))}pn();var _n,gn,yn,vn,bn,xn,Tn,An,Mn,wn={__proto__:null,GLTFFileLoader:mn,get GLTFLoaderAnimationStartMode(){return e.GLTFLoaderAnimationStartMode},get GLTFLoaderCoordinateSystemMode(){return e.GLTFLoaderCoordinateSystemMode},GLTFLoaderDefaultOptions:dn,get GLTFLoaderState(){return e.GLTFLoaderState},RegisterGLTFFileLoader:pn};!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"}(_n||(_n={})),function(e){e[e.FRAGMENT=35632]="FRAGMENT",e[e.VERTEX=35633]="VERTEX"}(gn||(gn={})),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"}(yn||(yn={})),function(e){e[e.CLAMP_TO_EDGE=33071]="CLAMP_TO_EDGE",e[e.MIRRORED_REPEAT=33648]="MIRRORED_REPEAT",e[e.REPEAT=10497]="REPEAT"}(vn||(vn={})),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"}(bn||(bn={})),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"}(xn||(xn={})),function(e){e[e.FRONT=1028]="FRONT",e[e.BACK=1029]="BACK",e[e.FRONT_AND_BACK=1032]="FRONT_AND_BACK"}(Tn||(Tn={})),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"}(An||(An={}));class Cn{static SetMatrix(e,n,s,o,r){let i=null;if("MODEL"===s.semantic?i=n.getWorldMatrix():"PROJECTION"===s.semantic?i=e.getProjectionMatrix():"VIEW"===s.semantic?i=e.getViewMatrix():"MODELVIEWINVERSETRANSPOSE"===s.semantic?i=t.Matrix.Transpose(n.getWorldMatrix().multiply(e.getViewMatrix()).invert()):"MODELVIEW"===s.semantic?i=n.getWorldMatrix().multiply(e.getViewMatrix()):"MODELVIEWPROJECTION"===s.semantic?i=n.getWorldMatrix().multiply(e.getTransformMatrix()):"MODELINVERSE"===s.semantic?i=n.getWorldMatrix().invert():"VIEWINVERSE"===s.semantic?i=e.getViewMatrix().invert():"PROJECTIONINVERSE"===s.semantic?i=e.getProjectionMatrix().invert():"MODELVIEWINVERSE"===s.semantic?i=n.getWorldMatrix().multiply(e.getViewMatrix()).invert():"MODELVIEWPROJECTIONINVERSE"===s.semantic?i=n.getWorldMatrix().multiply(e.getTransformMatrix()).invert():"MODELINVERSETRANSPOSE"===s.semantic&&(i=t.Matrix.Transpose(n.getWorldMatrix().invert())),i)switch(s.type){case yn.FLOAT_MAT2:r.setMatrix2x2(o,t.Matrix.GetAsMatrix2x2(i));break;case yn.FLOAT_MAT3:r.setMatrix3x3(o,t.Matrix.GetAsMatrix3x3(i));break;case yn.FLOAT_MAT4:r.setMatrix(o,i)}}static SetUniform(e,n,s,o){switch(o){case yn.FLOAT:return e.setFloat(n,s),!0;case yn.FLOAT_VEC2:return e.setVector2(n,t.Vector2.FromArray(s)),!0;case yn.FLOAT_VEC3:return e.setVector3(n,t.Vector3.FromArray(s)),!0;case yn.FLOAT_VEC4:return e.setVector4(n,t.Vector4.FromArray(s)),!0;default:return!1}}static GetWrapMode(e){switch(e){case vn.CLAMP_TO_EDGE:return t.Texture.CLAMP_ADDRESSMODE;case vn.MIRRORED_REPEAT:return t.Texture.MIRROR_ADDRESSMODE;case vn.REPEAT:default:return t.Texture.WRAP_ADDRESSMODE}}static GetByteStrideFromType(e){switch(e.type){case"VEC2":return 2;case"VEC3":return 3;case"VEC4":case"MAT2":return 4;case"MAT3":return 9;case"MAT4":return 16;default:return 1}}static GetTextureFilterMode(e){switch(e){case bn.LINEAR:case bn.LINEAR_MIPMAP_NEAREST:case bn.LINEAR_MIPMAP_LINEAR:return t.Texture.TRILINEAR_SAMPLINGMODE;case bn.NEAREST:case bn.NEAREST_MIPMAP_NEAREST:return t.Texture.NEAREST_SAMPLINGMODE;default:return t.Texture.BILINEAR_SAMPLINGMODE}}static GetBufferFromBufferView(e,t,n,s,o){n=t.byteOffset+n;const r=e.loadedBufferViews[t.buffer];if(n+s>r.byteLength)throw new Error("Buffer access is out of range");const i=r.buffer;switch(n+=r.byteOffset,o){case _n.BYTE:return new Int8Array(i,n,s);case _n.UNSIGNED_BYTE:return new Uint8Array(i,n,s);case _n.SHORT:return new Int16Array(i,n,s);case _n.UNSIGNED_SHORT:return new Uint16Array(i,n,s);default:return new Float32Array(i,n,s)}}static GetBufferFromAccessor(e,t){const n=e.bufferViews[t.bufferView],s=t.count*Cn.GetByteStrideFromType(t);return Cn.GetBufferFromBufferView(e,n,t.byteOffset,s,t.componentType)}static DecodeBufferToText(e){let t="";const n=e.byteLength;for(let s=0;s<n;++s)t+=String.fromCharCode(e[s]);return t}static GetDefaultMaterial(e){if(!Cn._DefaultMaterial){t.Effect.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("\n"),t.Effect.ShadersStore.GLTFDefaultMaterialPixelShader=["precision highp float;","","uniform vec4 u_emission;","","void main(void)","{"," gl_FragColor = u_emission;","}"].join("\n");const n={vertex:"GLTFDefaultMaterial",fragment:"GLTFDefaultMaterial"},s={attributes:["position"],uniforms:["worldView","projection","u_emission"],samplers:new Array,needAlphaBlending:!1};Cn._DefaultMaterial=new t.ShaderMaterial("GLTFDefaultMaterial",e,n,s),Cn._DefaultMaterial.setColor4("u_emission",new t.Color4(.5,.5,.5,1))}return Cn._DefaultMaterial}}Cn._DefaultMaterial=null,function(e){e[e.IDENTIFIER=1]="IDENTIFIER",e[e.UNKNOWN=2]="UNKNOWN",e[e.END_OF_INPUT=3]="END_OF_INPUT"}(Mn||(Mn={}));class Rn{constructor(e){this._pos=0,this.currentToken=Mn.UNKNOWN,this.currentIdentifier="",this.currentString="",this.isLetterOrDigitPattern=/^[a-zA-Z0-9]+$/,this._toParse=e,this._maxPos=e.length}getNextToken(){if(this.isEnd())return Mn.END_OF_INPUT;if(this.currentString=this.read(),this.currentToken=Mn.UNKNOWN,"_"===this.currentString||this.isLetterOrDigitPattern.test(this.currentString))for(this.currentToken=Mn.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}}const Sn=["MODEL","VIEW","PROJECTION","MODELVIEW","MODELVIEWPROJECTION","JOINTMATRIX"],On=["world","view","projection","worldView","worldViewProjection","mBones"],Fn=["translation","rotation","scale"],En=["position","rotationQuaternion","scaling"],In=(e,t,n)=>{for(const s in e){const o=e[s];n[t][s]=o}},Ln=e=>{if(e)for(let t=0;t<e.length/2;t++)e[2*t+1]=1-e[2*t+1]},Pn=e=>{if("NORMAL"===e.semantic)return"normal";if("POSITION"===e.semantic)return"position";if("JOINT"===e.semantic)return"matricesIndices";if("WEIGHT"===e.semantic)return"matricesWeights";if("COLOR"===e.semantic)return"color";if(e.semantic&&-1!==e.semantic.indexOf("TEXCOORD_")){const t=Number(e.semantic.split("_")[1]);return"uv"+(0===t?"":t+1)}return null},Bn=e=>{let n;if(e.translation||e.rotation||e.scale){const s=t.Vector3.FromArray(e.scale||[1,1,1]),o=t.Quaternion.FromArray(e.rotation||[0,0,0,1]),r=t.Vector3.FromArray(e.translation||[0,0,0]);n=t.Matrix.Compose(s,o,r)}else n=t.Matrix.FromArray(e.matrix);return n},Nn=(e,n,s,o)=>{for(let e=0;e<o.bones.length;e++)if(o.bones[e].name===s)return o.bones[e];const r=e.nodes;for(const i in r){const a=r[i];if(!a.jointName)continue;const l=a.children;for(let r=0;r<l.length;r++){const u=e.nodes[l[r]];if(u.jointName&&u.jointName===s){const s=Bn(a),r=new t.Bone(a.name||"",o,Nn(e,n,a.jointName,o),s);return r.id=i,r}}}return null},kn=(e,t)=>{for(let n=0;n<e.length;n++){const s=e[n];for(let e=0;e<s.node.children.length;e++)if(s.node.children[e]===t)return s.bone}return null},Dn=(e,t)=>{const n=e.nodes;let s=n[t];if(s)return{node:s,id:t};for(const e in n)if(s=n[e],s.jointName===t)return{node:s,id:e};return null},Gn=(e,t)=>{for(let n=0;n<e.jointNames.length;n++)if(e.jointNames[n]===t)return!0;return!1},Vn=(e,n,s,o,r)=>{if(r||(e.scene._blockEntityCollection=!!e.assetContainer,(r=new t.Mesh(n.name||"",e.scene))._parentContainer=e.assetContainer,e.scene._blockEntityCollection=!1,r.id=o),!n.babylonNode)return r;const i=[];let a=null;const l=[],u=[],c=[],d=[];for(let n=0;n<s.length;n++){const o=s[n],r=e.meshes[o];if(r)for(let n=0;n<r.primitives.length;n++){const s=new t.VertexData,o=r.primitives[n];o.mode;const h=o.attributes;let m,f;for(const n in h)if(m=e.accessors[h[n]],f=Cn.GetBufferFromAccessor(e,m),"NORMAL"===n)s.normals=new Float32Array(f.length),s.normals.set(f);else if("POSITION"===n){if(mn.HomogeneousCoordinates){s.positions=new Float32Array(f.length-f.length/4);for(let e=0;e<f.length;e+=4)s.positions[e]=f[e],s.positions[e+1]=f[e+1],s.positions[e+2]=f[e+2]}else s.positions=new Float32Array(f.length),s.positions.set(f);u.push(s.positions.length)}else if(-1!==n.indexOf("TEXCOORD_")){const e=Number(n.split("_")[1]),o=t.VertexBuffer.UVKind+(0===e?"":e+1),r=new Float32Array(f.length);r.set(f),Ln(r),s.set(r,o)}else"JOINT"===n?(s.matricesIndices=new Float32Array(f.length),s.matricesIndices.set(f)):"WEIGHT"===n?(s.matricesWeights=new Float32Array(f.length),s.matricesWeights.set(f)):"COLOR"===n&&(s.colors=new Float32Array(f.length),s.colors.set(f));if(m=e.accessors[o.indices],m)f=Cn.GetBufferFromAccessor(e,m),s.indices=new Int32Array(f.length),s.indices.set(f),d.push(s.indices.length);else{const e=[];for(let t=0;t<s.positions.length/3;t++)e.push(t);s.indices=new Int32Array(e),d.push(s.indices.length)}a?a.merge(s):a=s;const p=e.scene.getMaterialById(o.material);i.push(null===p?Cn.GetDefaultMaterial(e.scene):p),l.push(0===l.length?0:l[l.length-1]+u[u.length-2]),c.push(0===c.length?0:c[c.length-1]+d[d.length-2])}}let h;e.scene._blockEntityCollection=!!e.assetContainer,i.length>1?(h=new t.MultiMaterial("multimat"+o,e.scene),h.subMaterials=i):h=new t.StandardMaterial("multimat"+o,e.scene),1===i.length&&(h=i[0]),h._parentContainer=e.assetContainer,r.material||(r.material=h),new t.Geometry(o,e.scene,a,!1,r),r.computeWorldMatrix(!0),e.scene._blockEntityCollection=!1,r.subMeshes=[];let m=0;for(let n=0;n<s.length;n++){const o=s[n],i=e.meshes[o];if(i)for(let e=0;e<i.primitives.length;e++)i.primitives[e].mode,t.SubMesh.AddToMesh(m,l[m],u[m],c[m],d[m],r,r,!0),m++}return r},Hn=(e,t,n,s)=>{e.position&&(e.position=t),(e.rotationQuaternion||e.rotation)&&(e.rotationQuaternion=n),e.scaling&&(e.scaling=s)},Kn=(e,n,s)=>{let o=null;if(e.importOnlyMeshes&&(n.skin||n.meshes)&&e.importMeshesNames&&e.importMeshesNames.length>0&&-1===e.importMeshesNames.indexOf(n.name||""))return null;if(n.skin){if(n.meshes){const r=e.skins[n.skin],i=Vn(e,n,n.meshes,s,n.babylonNode);i.skeleton=e.scene.getLastSkeletonById(n.skin),null===i.skeleton&&(i.skeleton=((e,n,s,o)=>{if(o||(o=new t.Skeleton(n.name||"","",e.scene)),!n.babylonSkeleton)return o;const r=[],i=[];((e,n,s,o)=>{for(const r in e.nodes){const i=e.nodes[r],a=r;if(!i.jointName||Gn(s,i.jointName))continue;const l=Bn(i),u=new t.Bone(i.name||"",n,null,l);u.id=a,o.push({bone:u,node:i,id:a})}for(let e=0;e<o.length;e++){const t=o[e],n=t.node.children;for(let e=0;e<n.length;e++){let s=null;for(let t=0;t<o.length;t++)if(o[t].id===n[e]){s=o[t];break}s&&(s.bone._parent=t.bone,t.bone.children.push(s.bone))}}})(e,o,n,r),o.bones=[];for(let s=0;s<n.jointNames.length;s++){const a=Dn(e,n.jointNames[s]);if(!a)continue;const l=a.node;if(!l){t.Tools.Warn("Joint named "+n.jointNames[s]+" does not exist");continue}const u=a.id,c=e.scene.getBoneById(u);if(c){o.bones.push(c);continue}let d,h=null;for(let r=0;r<s;r++){const s=Dn(e,n.jointNames[r]);if(!s)continue;const i=s.node;if(!i){t.Tools.Warn("Joint named "+n.jointNames[r]+" does not exist when looking for parent");continue}const a=i.children;if(a){d=!1;for(let t=0;t<a.length;t++)if(a[t]===u){h=Nn(e,n,n.jointNames[r],o),d=!0;break}if(d)break}}const m=Bn(l);!h&&r.length>0&&(h=kn(r,u),h&&-1===i.indexOf(h)&&i.push(h)),new t.Bone(l.jointName||"",o,h,m).id=u}const a=o.bones;o.bones=[];for(let t=0;t<n.jointNames.length;t++){const s=Dn(e,n.jointNames[t]);if(s)for(let e=0;e<a.length;e++)if(a[e].id===s.id){o.bones.push(a[e]);break}}o.prepare();for(let e=0;e<i.length;e++)o.bones.push(i[e]);return o})(e,r,0,r.babylonSkeleton),r.babylonSkeleton||(r.babylonSkeleton=i.skeleton)),o=i}}else if(n.meshes)o=Vn(e,n,n.mesh?[n.mesh]:n.meshes,s,n.babylonNode);else if(!n.light||n.babylonNode||e.importOnlyMeshes){if(n.camera&&!n.babylonNode&&!e.importOnlyMeshes){const s=e.cameras[n.camera];if(s){if(e.scene._blockEntityCollection=!!e.assetContainer,"orthographic"===s.type){const s=new t.FreeCamera(n.camera,t.Vector3.Zero(),e.scene,!1);s.name=n.name||"",s.mode=t.Camera.ORTHOGRAPHIC_CAMERA,s.attachControl(),o=s,s._parentContainer=e.assetContainer}else if("perspective"===s.type){const r=s[s.type],i=new t.FreeCamera(n.camera,t.Vector3.Zero(),e.scene,!1);i.name=n.name||"",i.attachControl(),r.aspectRatio||(r.aspectRatio=e.scene.getEngine().getRenderWidth()/e.scene.getEngine().getRenderHeight()),r.znear&&r.zfar&&(i.maxZ=r.zfar,i.minZ=r.znear),o=i,i._parentContainer=e.assetContainer}e.scene._blockEntityCollection=!1}}}else{const s=e.lights[n.light];if(s)if("ambient"===s.type){const r=s[s.type],i=new t.HemisphericLight(n.light,t.Vector3.Zero(),e.scene);i.name=n.name||"",r.color&&(i.diffuse=t.Color3.FromArray(r.color)),o=i}else if("directional"===s.type){const r=s[s.type],i=new t.DirectionalLight(n.light,t.Vector3.Zero(),e.scene);i.name=n.name||"",r.color&&(i.diffuse=t.Color3.FromArray(r.color)),o=i}else if("point"===s.type){const r=s[s.type],i=new t.PointLight(n.light,t.Vector3.Zero(),e.scene);i.name=n.name||"",r.color&&(i.diffuse=t.Color3.FromArray(r.color)),o=i}else if("spot"===s.type){const r=s[s.type],i=new t.SpotLight(n.light,t.Vector3.Zero(),t.Vector3.Zero(),0,0,e.scene);i.name=n.name||"",r.color&&(i.diffuse=t.Color3.FromArray(r.color)),r.fallOfAngle&&(i.angle=r.fallOfAngle),r.fallOffExponent&&(i.exponent=r.fallOffExponent),o=i}}if(!n.jointName){if(n.babylonNode)return n.babylonNode;if(null===o){e.scene._blockEntityCollection=!!e.assetContainer;const s=new t.Mesh(n.name||"",e.scene);s._parentContainer=e.assetContainer,e.scene._blockEntityCollection=!1,n.babylonNode=s,o=s}}if(null!==o){if(n.matrix&&o instanceof t.Mesh)((e,n)=>{if(n.matrix){const s=new t.Vector3(0,0,0),o=new t.Quaternion,r=new t.Vector3(0,0,0);t.Matrix.FromArray(n.matrix).decompose(r,o,s),Hn(e,s,o,r)}else n.translation&&n.rotation&&n.scale&&Hn(e,t.Vector3.FromArray(n.translation),t.Quaternion.FromArray(n.rotation),t.Vector3.FromArray(n.scale));e.computeWorldMatrix(!0)})(o,n);else{const e=n.translation||[0,0,0],s=n.rotation||[0,0,0,1],r=n.scale||[1,1,1];Hn(o,t.Vector3.FromArray(e),t.Quaternion.FromArray(s),t.Vector3.FromArray(r))}o.updateCache(!0),n.babylonNode=o}return o},$n=(e,t,n,s=!1)=>{const o=e.nodes[t];let r=null;if(s=!(e.importOnlyMeshes&&!s&&e.importMeshesNames)||-1!==e.importMeshesNames.indexOf(o.name||"")||0===e.importMeshesNames.length,!o.jointName&&s&&(r=Kn(e,o,t),null!==r&&(r.id=t,r.parent=n)),o.children)for(let t=0;t<o.children.length;t++)$n(e,o.children[t],r,s)},Un=e=>{let n=e.currentScene;if(n)for(let t=0;t<n.nodes.length;t++)$n(e,n.nodes[t],null);else for(const t in e.scenes){n=e.scenes[t];for(let t=0;t<n.nodes.length;t++)$n(e,n.nodes[t],null)}(e=>{for(const n in e.animations){const s=e.animations[n];if(!s.channels||!s.samplers)continue;let o=null;for(let r=0;r<s.channels.length;r++){const i=s.channels[r],a=s.samplers[i.sampler];if(!a)continue;let l,u;s.parameters?(l=s.parameters[a.input],u=s.parameters[a.output]):(l=a.input,u=a.output);const c=Cn.GetBufferFromAccessor(e,e.accessors[l]),d=Cn.GetBufferFromAccessor(e,e.accessors[u]),h=i.target.id;let m=e.scene.getNodeById(h);if(null===m&&(m=e.scene.getNodeByName(h)),null===m){t.Tools.Warn("Creating animation named "+n+". But cannot find node named "+h+" to attach to");continue}const f=m instanceof t.Bone;let p=i.target.path;const _=Fn.indexOf(p);-1!==_&&(p=En[_]);let g=t.Animation.ANIMATIONTYPE_MATRIX;f||("rotationQuaternion"===p?(g=t.Animation.ANIMATIONTYPE_QUATERNION,m.rotationQuaternion=new t.Quaternion):g=t.Animation.ANIMATIONTYPE_VECTOR3);let y=null;const v=[];let b=0,x=!1;f&&o&&o.getKeys().length===c.length&&(y=o,x=!0),x||(e.scene._blockEntityCollection=!!e.assetContainer,y=new t.Animation(n,f?"_matrix":p,1,g,t.Animation.ANIMATIONLOOPMODE_CYCLE),e.scene._blockEntityCollection=!1);for(let e=0;e<c.length;e++){let n;if("rotationQuaternion"===p?(n=t.Quaternion.FromArray([d[b],d[b+1],d[b+2],d[b+3]]),b+=4):(n=t.Vector3.FromArray([d[b],d[b+1],d[b+2]]),b+=3),f){const s=m;let r=t.Vector3.Zero(),i=new t.Quaternion,a=t.Vector3.Zero(),l=s.getBaseMatrix();x&&o&&(l=o.getKeys()[e].value),l.decompose(a,i,r),"position"===p?r=n:"rotationQuaternion"===p?i=n:a=n,n=t.Matrix.Compose(a,i,r)}x?o&&(o.getKeys()[e].value=n):v.push({frame:c[e],value:n})}!x&&y&&(y.setKeys(v),m.animations.push(y)),o=y,e.scene.stopAnimation(m),e.scene.beginAnimation(m,0,c[c.length-1],!0,1)}}})(e);for(let t=0;t<e.scene.skeletons.length;t++){const n=e.scene.skeletons[t];e.scene.beginAnimation(n,0,Number.MAX_VALUE,!0,1)}},qn=(e,t,n)=>{for(const s in t.uniforms){const o=t.uniforms[s],r=t.parameters[o];if(e.currentIdentifier===s&&r.semantic&&!r.source&&!r.node){const e=Sn.indexOf(r.semantic);if(-1!==e)return delete n[s],On[e]}}return e.currentIdentifier},Wn=e=>{for(const t in e.materials)Xn.LoadMaterialAsync(e,t,()=>{},()=>{})};class zn{static CreateRuntime(e,t,n){const s={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&&In(e.extensions,"extensions",s),e.extensionsUsed&&In(e.extensionsUsed,"extensionsUsed",s),e.buffers&&((e,t)=>{for(const n in e){const s=e[n];t.buffers[n]=s,t.buffersCount++}})(e.buffers,s),e.bufferViews&&In(e.bufferViews,"bufferViews",s),e.accessors&&In(e.accessors,"accessors",s),e.meshes&&In(e.meshes,"meshes",s),e.lights&&In(e.lights,"lights",s),e.cameras&&In(e.cameras,"cameras",s),e.nodes&&In(e.nodes,"nodes",s),e.images&&In(e.images,"images",s),e.textures&&In(e.textures,"textures",s),e.shaders&&((e,t)=>{for(const n in e){const s=e[n];t.shaders[n]=s,t.shaderscount++}})(e.shaders,s),e.programs&&In(e.programs,"programs",s),e.samplers&&In(e.samplers,"samplers",s),e.techniques&&In(e.techniques,"techniques",s),e.materials&&In(e.materials,"materials",s),e.animations&&In(e.animations,"animations",s),e.skins&&In(e.skins,"skins",s),e.scenes&&(s.scenes=e.scenes),e.scene&&e.scenes&&(s.currentScene=e.scenes[e.scene]),s}static LoadBufferAsync(e,n,s,o,r){const i=e.buffers[n];t.Tools.IsBase64(i.uri)?setTimeout(()=>s(new Uint8Array(t.Tools.DecodeBase64(i.uri)))):t.Tools.LoadFile(e.rootUrl+i.uri,e=>s(new Uint8Array(e)),r,void 0,!0,e=>{e&&o(e.status+" "+e.statusText)})}static LoadTextureBufferAsync(e,n,s,o){const r=e.textures[n];if(!r||!r.source)return void o("");if(r.babylonTexture)return void s(null);const i=e.images[r.source];t.Tools.IsBase64(i.uri)?setTimeout(()=>s(new Uint8Array(t.Tools.DecodeBase64(i.uri)))):t.Tools.LoadFile(e.rootUrl+i.uri,e=>s(new Uint8Array(e)),void 0,void 0,!0,e=>{e&&o(e.status+" "+e.statusText)})}static CreateTextureAsync(e,n,s,o){const r=e.textures[n];if(r.babylonTexture)return void o(r.babylonTexture);const i=e.samplers[r.sampler],a=i.minFilter===bn.NEAREST_MIPMAP_NEAREST||i.minFilter===bn.NEAREST_MIPMAP_LINEAR||i.minFilter===bn.LINEAR_MIPMAP_NEAREST||i.minFilter===bn.LINEAR_MIPMAP_LINEAR,l=t.Texture.BILINEAR_SAMPLINGMODE,u=null==s?new Blob:new Blob([t.GetBlobBufferSource(s)]),c=URL.createObjectURL(u),d=()=>URL.revokeObjectURL(c),h=new t.Texture(c,e.scene,!a,!0,l,d,d);void 0!==i.wrapS&&(h.wrapU=Cn.GetWrapMode(i.wrapS)),void 0!==i.wrapT&&(h.wrapV=Cn.GetWrapMode(i.wrapT)),h.name=n,r.babylonTexture=h,o(h)}static LoadShaderStringAsync(e,n,s,o){const r=e.shaders[n];if(t.Tools.IsBase64(r.uri)){const e=atob(r.uri.split(",")[1]);s&&s(e)}else t.Tools.LoadFile(e.rootUrl+r.uri,s,void 0,void 0,!1,e=>{e&&o&&o(e.status+" "+e.statusText)})}static LoadMaterialAsync(e,n,s,o){const r=e.materials[n];if(!r.technique)return void(o&&o("No technique found."));const i=e.techniques[r.technique];if(!i){e.scene._blockEntityCollection=!!e.assetContainer;const o=new t.StandardMaterial(n,e.scene);return o._parentContainer=e.assetContainer,e.scene._blockEntityCollection=!1,o.diffuseColor=new t.Color3(.5,.5,.5),o.sideOrientation=t.Material.CounterClockWiseSideOrientation,void s(o)}const a=e.programs[i.program],l=i.states,u=t.Effect.ShadersStore[a.vertexShader+"VertexShader"],c=t.Effect.ShadersStore[a.fragmentShader+"PixelShader"];let d="",h="";const m=new Rn(u),f=new Rn(c),p={},_=[],g=[],y=[];for(const e in i.uniforms){const t=i.uniforms[e],n=i.parameters[t];if(p[e]=n,!n.semantic||n.node||n.source)n.type===yn.SAMPLER_2D?y.push(e):_.push(e);else{const t=Sn.indexOf(n.semantic);-1!==t?(_.push(On[t]),delete p[e]):_.push(e)}}for(const e in i.attributes){const t=i.attributes[e],n=i.parameters[t];if(n.semantic){const e=Pn(n);e&&g.push(e)}}for(;!m.isEnd()&&m.getNextToken();){if(m.currentToken!==Mn.IDENTIFIER){d+=m.currentString;continue}let e=!1;for(const t in i.attributes){const n=i.attributes[t],s=i.parameters[n];if(m.currentIdentifier===t&&s.semantic){d+=Pn(s),e=!0;break}}e||(d+=qn(m,i,p))}for(;!f.isEnd()&&f.getNextToken();)f.currentToken===Mn.IDENTIFIER?h+=qn(f,i,p):h+=f.currentString;const v={vertex:a.vertexShader+n,fragment:a.fragmentShader+n},b={attributes:g,uniforms:_,samplers:y,needAlphaBlending:l&&l.enable&&-1!==l.enable.indexOf(3042)};t.Effect.ShadersStore[a.vertexShader+n+"VertexShader"]=d,t.Effect.ShadersStore[a.fragmentShader+n+"PixelShader"]=h;const x=new t.ShaderMaterial(n,e.scene,v,b);if(x.onError=((e,t,n)=>(s,o)=>{t.dispose(!0),n("Cannot compile program named "+e.name+". Error: "+o+". Default material will be applied")})(a,x,o),x.onCompiled=((e,t,n,s,o,r)=>i=>{((e,t,n,s,o)=>{const r=s.values||n.parameters,i=n.uniforms;for(const n in o){const a=o[n],l=a.type;let u=r[i[n]];if(void 0===u&&(u=a.value),!u)continue;const c=e=>n=>{a.value&&e&&(t.setTexture(e,n),delete o[e])};l===yn.SAMPLER_2D?Xn.LoadTextureAsync(e,s.values?u:a.value,c(n),()=>c(null)):a.value&&Cn.SetUniform(t,n,s.values?u:a.value,l)&&delete o[n]}})(e,t,n,s,o),t.onBind=i=>{((e,t,n,s,o,r,i)=>{const a=r.values||o.parameters;for(const i in n){const l=n[i],u=l.type;if(u===yn.FLOAT_MAT2||u===yn.FLOAT_MAT3||u===yn.FLOAT_MAT4)if(!l.semantic||l.source||l.node){if(l.semantic&&(l.source||l.node)){let e=t.scene.getNodeByName(l.source||l.node||"");if(null===e&&(e=t.scene.getNodeById(l.source||l.node||"")),null===e)continue;Cn.SetMatrix(t.scene,e,l,i,s.getEffect())}}else Cn.SetMatrix(t.scene,e,l,i,s.getEffect());else{const e=a[o.uniforms[i]];if(!e)continue;if(u===yn.SAMPLER_2D){const n=t.textures[r.values?e:l.value].babylonTexture;if(null==n)continue;s.getEffect().setTexture(i,n)}else Cn.SetUniform(s.getEffect(),i,e,u)}}i(s)})(i,e,o,t,n,s,r)}})(e,x,i,r,p,s),x.sideOrientation=t.Material.CounterClockWiseSideOrientation,l&&l.functions){const e=l.functions;e.cullFace&&e.cullFace[0]!==Tn.BACK&&(x.backFaceCulling=!1);const n=e.blendFuncSeparate;n&&(n[0]===An.SRC_ALPHA&&n[1]===An.ONE_MINUS_SRC_ALPHA&&n[2]===An.ONE&&n[3]===An.ONE?x.alphaMode=t.Constants.ALPHA_COMBINE:n[0]===An.ONE&&n[1]===An.ONE&&n[2]===An.ZERO&&n[3]===An.ONE?x.alphaMode=t.Constants.ALPHA_ONEONE:n[0]===An.SRC_ALPHA&&n[1]===An.ONE&&n[2]===An.ZERO&&n[3]===An.ONE?x.alphaMode=t.Constants.ALPHA_ADD:n[0]===An.ZERO&&n[1]===An.ONE_MINUS_SRC_COLOR&&n[2]===An.ONE&&n[3]===An.ONE?x.alphaMode=t.Constants.ALPHA_SUBTRACT:n[0]===An.DST_COLOR&&n[1]===An.ZERO&&n[2]===An.ONE&&n[3]===An.ONE?x.alphaMode=t.Constants.ALPHA_MULTIPLY:n[0]===An.SRC_ALPHA&&n[1]===An.ONE_MINUS_SRC_COLOR&&n[2]===An.ONE&&n[3]===An.ONE&&(x.alphaMode=t.Constants.ALPHA_MAXIMIZED))}}}let jn=class e{static RegisterExtension(n){e.Extensions[n.name]?t.Tools.Error('Tool with the same name "'+n.name+'" already exists'):e.Extensions[n.name]=n}dispose(){}_importMeshAsync(e,n,s,o,r,i,a,l){return n.useRightHandedSystem=!0,Xn.LoadRuntimeAsync(n,s,o,n=>{n.assetContainer=r,n.importOnlyMeshes=!0,""===e?n.importMeshesNames=[]:"string"==typeof e?n.importMeshesNames=[e]:!e||e instanceof Array?(n.importMeshesNames=[],t.Tools.Warn("Argument meshesNames must be of type string or string[]")):n.importMeshesNames=[e],this._createNodes(n);const s=[],o=[];for(const e in n.nodes){const o=n.nodes[e];o.babylonNode instanceof t.AbstractMesh&&s.push(o.babylonNode)}for(const e in n.skins){const s=n.skins[e];s.babylonSkeleton instanceof t.Skeleton&&o.push(s.babylonSkeleton)}this._loadBuffersAsync(n,()=>{this._loadShadersAsync(n,()=>{Wn(n),Un(n),!mn.IncrementalLoading&&i&&i(s,o)})}),mn.IncrementalLoading&&i&&i(s,o)},l),!0}importMeshAsync(e,t,n,s,o,r){return new Promise((i,a)=>{this._importMeshAsync(e,t,s,o,n,(e,t)=>{i({meshes:e,particleSystems:[],skeletons:t,animationGroups:[],lights:[],transformNodes:[],geometries:[],spriteManagers:[]})},r,e=>{a(new Error(e))})})}_loadAsync(e,t,n,s,o,r){e.useRightHandedSystem=!0,Xn.LoadRuntimeAsync(e,t,n,e=>{Xn.LoadRuntimeExtensionsAsync(e,()=>{this._createNodes(e),this._loadBuffersAsync(e,()=>{this._loadShadersAsync(e,()=>{Wn(e),Un(e),mn.IncrementalLoading||s()})}),mn.IncrementalLoading&&s()},r)},r)}loadAsync(e,t,n,s){return b(this,void 0,void 0,function*(){return yield new Promise((o,r)=>{this._loadAsync(e,t,n,()=>{o()},s,e=>{r(new Error(e))})})})}_loadShadersAsync(e,n){let s=!1;const o=(s,o)=>{Xn.LoadShaderStringAsync(e,s,r=>{r instanceof ArrayBuffer||(e.loadedShaderCount++,r&&(t.Effect.ShadersStore[s+(o.type===gn.VERTEX?"VertexShader":"PixelShader")]=r),e.loadedShaderCount===e.shaderscount&&n())},()=>{t.Tools.Error("Error when loading shader program named "+s+" located at "+o.uri)})};for(const n in e.shaders){s=!0;const r=e.shaders[n];r?o.bind(this,n,r)():t.Tools.Error("No shader named: "+n)}s||n()}_loadBuffersAsync(e,n){let s=!1;const o=(s,o)=>{Xn.LoadBufferAsync(e,s,r=>{e.loadedBufferCount++,r&&(r.byteLength!=e.buffers[s].byteLength&&t.Tools.Error("Buffer named "+s+" is length "+r.byteLength+". Expected: "+o.byteLength),e.loadedBufferViews[s]=r),e.loadedBufferCount===e.buffersCount&&n()},()=>{t.Tools.Error("Error when loading buffer named "+s+" located at "+o.uri)})};for(const n in e.buffers){s=!0;const r=e.buffers[n];r?o.bind(this,n,r)():t.Tools.Error("No buffer named: "+n)}s||n()}_createNodes(e){let t=e.currentScene;if(t)for(let n=0;n<t.nodes.length;n++)$n(e,t.nodes[n],null);else for(const n in e.scenes){t=e.scenes[n];for(let n=0;n<t.nodes.length;n++)$n(e,t.nodes[n],null)}}};jn.Extensions={};class Xn{constructor(e){this._name=e}get name(){return this._name}loadRuntimeAsync(e,t,n,s,o){return!1}loadRuntimeExtensionsAsync(e,t,n){return!1}loadBufferAsync(e,t,n,s,o){return!1}loadTextureBufferAsync(e,t,n,s){return!1}createTextureAsync(e,t,n,s,o){return!1}loadShaderStringAsync(e,t,n,s){return!1}loadMaterialAsync(e,t,n,s){return!1}static LoadRuntimeAsync(e,t,n,s,o){Xn._ApplyExtensions(r=>r.loadRuntimeAsync(e,t,n,s,o),()=>{setTimeout(()=>{s&&s(zn.CreateRuntime(t.json,e,n))})})}static LoadRuntimeExtensionsAsync(e,t,n){Xn._ApplyExtensions(s=>s.loadRuntimeExtensionsAsync(e,t,n),()=>{setTimeout(()=>{t()})})}static LoadBufferAsync(e,t,n,s,o){Xn._ApplyExtensions(r=>r.loadBufferAsync(e,t,n,s,o),()=>{zn.LoadBufferAsync(e,t,n,s,o)})}static LoadTextureAsync(e,t,n,s){Xn._LoadTextureBufferAsync(e,t,o=>{o&&Xn._CreateTextureAsync(e,t,o,n,s)},s)}static LoadShaderStringAsync(e,t,n,s){Xn._ApplyExtensions(o=>o.loadShaderStringAsync(e,t,n,s),()=>{zn.LoadShaderStringAsync(e,t,n,s)})}static LoadMaterialAsync(e,t,n,s){Xn._ApplyExtensions(o=>o.loadMaterialAsync(e,t,n,s),()=>{zn.LoadMaterialAsync(e,t,n,s)})}static _LoadTextureBufferAsync(e,t,n,s){Xn._ApplyExtensions(o=>o.loadTextureBufferAsync(e,t,n,s),()=>{zn.LoadTextureBufferAsync(e,t,n,s)})}static _CreateTextureAsync(e,t,n,s,o){Xn._ApplyExtensions(r=>r.createTextureAsync(e,t,n,s,o),()=>{zn.CreateTextureAsync(e,t,n,s)})}static _ApplyExtensions(e,t){for(const t in jn.Extensions)if(e(jn.Extensions[t]))return;t()}}mn._CreateGLTF1Loader=()=>new jn;class Yn extends Xn{constructor(){super("KHR_binary_glTF")}loadRuntimeAsync(e,t,n,s){const o=t.json.extensionsUsed;return!(!o||-1===o.indexOf(this.name)||!t.bin||(this._bin=t.bin,s(zn.CreateRuntime(t.json,e,n)),0))}loadBufferAsync(e,t,n,s){return-1!==e.extensionsUsed.indexOf(this.name)&&"binary_glTF"===t&&(this._bin.readAsync(0,this._bin.byteLength).then(n,e=>s(e.message)),!0)}loadTextureBufferAsync(e,t,n){const s=e.textures[t],o=e.images[s.source];if(!o.extensions||!(this.name in o.extensions))return!1;const r=o.extensions[this.name],i=e.bufferViews[r.bufferView];return n(Cn.GetBufferFromBufferView(e,i,0,i.byteLength,_n.UNSIGNED_BYTE)),!0}loadShaderStringAsync(e,t,n){const s=e.shaders[t];if(!s.extensions||!(this.name in s.extensions))return!1;const o=s.extensions[this.name],r=e.bufferViews[o.bufferView],i=Cn.GetBufferFromBufferView(e,r,0,r.byteLength,_n.UNSIGNED_BYTE);return setTimeout(()=>{const e=Cn.DecodeBufferToText(i);n(e)}),!0}}jn.RegisterExtension(new Yn);class Qn extends Xn{constructor(){super("KHR_materials_common")}loadRuntimeExtensionsAsync(e){if(!e.extensions)return!1;const n=e.extensions[this.name];if(!n)return!1;const s=n.lights;if(s)for(const n in s){const o=s[n];switch(o.type){case"ambient":{const n=new t.HemisphericLight(o.name,new t.Vector3(0,1,0),e.scene),s=o.ambient;s&&(n.diffuse=t.Color3.FromArray(s.color||[1,1,1]));break}case"point":{const n=new t.PointLight(o.name,new t.Vector3(10,10,10),e.scene),s=o.point;s&&(n.diffuse=t.Color3.FromArray(s.color||[1,1,1]));break}case"directional":{const n=new t.DirectionalLight(o.name,new t.Vector3(0,-1,0),e.scene),s=o.directional;s&&(n.diffuse=t.Color3.FromArray(s.color||[1,1,1]));break}case"spot":{const n=o.spot;n&&(new t.SpotLight(o.name,new t.Vector3(0,10,0),new t.Vector3(0,-1,0),n.fallOffAngle||Math.PI,n.fallOffExponent||0,e.scene).diffuse=t.Color3.FromArray(n.color||[1,1,1]));break}default:t.Tools.Warn('GLTF Material Common extension: light type "'+o.type+"” not supported")}}return!1}loadMaterialAsync(e,n,s,o){const r=e.materials[n];if(!r||!r.extensions)return!1;const i=r.extensions[this.name];if(!i)return!1;const a=new t.StandardMaterial(n,e.scene);return a.sideOrientation=t.Material.CounterClockWiseSideOrientation,"CONSTANT"===i.technique&&(a.disableLighting=!0),a.backFaceCulling=void 0!==i.doubleSided&&!i.doubleSided,a.alpha=void 0===i.values.transparency?1:i.values.transparency,a.specularPower=void 0===i.values.shininess?0:i.values.shininess,"string"==typeof i.values.ambient?this._loadTexture(e,i.values.ambient,a,"ambientTexture",o):a.ambientColor=t.Color3.FromArray(i.values.ambient||[0,0,0]),"string"==typeof i.values.diffuse?this._loadTexture(e,i.values.diffuse,a,"diffuseTexture",o):a.diffuseColor=t.Color3.FromArray(i.values.diffuse||[0,0,0]),"string"==typeof i.values.emission?this._loadTexture(e,i.values.emission,a,"emissiveTexture",o):a.emissiveColor=t.Color3.FromArray(i.values.emission||[0,0,0]),"string"==typeof i.values.specular?this._loadTexture(e,i.values.specular,a,"specularTexture",o):a.specularColor=t.Color3.FromArray(i.values.specular||[0,0,0]),!0}_loadTexture(e,t,n,s,o){zn.LoadTextureBufferAsync(e,t,o=>{zn.CreateTextureAsync(e,t,o,e=>n[s]=e)},o)}}jn.RegisterExtension(new Qn);var Zn={__proto__:null,get EBlendingFunction(){return An},get EComponentType(){return _n},get ECullingType(){return Tn},get EParameterType(){return yn},get EShaderType(){return gn},get ETextureFilterType(){return bn},get ETextureFormat(){return xn},get ETextureWrapMode(){return vn},GLTFBinaryExtension:Yn,GLTFLoader:jn,GLTFLoaderBase:zn,GLTFLoaderExtension:Xn,GLTFMaterialsCommonExtension:Qn,GLTFUtils:Cn};const Jn=new Map,es=Jn;function ts(e,n,s){ns(e)&&t.Logger.Warn(`Extension with the name '${e}' already exists`),Jn.set(e,{isGLTFExtension:n,factory:s})}function ns(e){return Jn.delete(e)}const ss=[{regex:new RegExp("^/nodes/\\d+/extensions/")},{regex:new RegExp("^/animations/\\d+/extensions/")},{regex:new RegExp("^/nodes/\\d+/weights")},{regex:new RegExp("^/meshes/\\d+/weights")},{regex:new RegExp("/extensions/KHR_texture_transform/")}];class os{constructor(e,t){this._gltf=e,this._infoTree=t}convert(e){let t,n=this._gltf,s=this._infoTree;if(!e.startsWith("/"))throw new Error("Path must start with a /");const o=e.split("/");if(o.shift(),o[o.length-1].includes(".length")){const e=o[o.length-1].split(".");o.pop(),o.push(...e)}let r=!1;for(const i of o)if("length"===i){if(!s.length)throw s.__array__?new Error(`Path ${e} is invalid - no length accessor`):new Error(`Path ${e} is invalid`);s=s.length,void 0!==n&&(t=n)}else{if(s.__ignoreObjectTree__&&(r=!0),s.__array__)s=s.__array__;else if(s=s[i],!s)throw new Error(`Path ${e} is invalid`);if(s.__passThroughTarget__)r=!0;else if(r){const e=/^\d+$/.test(i)?parseInt(i,10):NaN;if(!isNaN(e)&&"function"==typeof s.get){const t=s;s=Object.assign({},t),s.get=(n,s,...o)=>t.get(n,e,...o),"function"==typeof t.set&&(s.set=(n,s,o,...r)=>t.set(n,s,e,...r)),"function"==typeof t.getTarget&&(s.getTarget=(n,s,...o)=>t.getTarget(n,e,...o))}}else if(void 0===n){if(!ss.find(t=>t.regex.test(e)))throw new Error(`Path ${e} is invalid`)}else n=null==n?void 0:n[i];s.__target__&&void 0!==n&&(t=n)}return{object:t,info:s}}}function rs(e,n){return{type:"FlowGraphInteger",get:n=>{const s=e(n);return void 0===s?void 0:t.FlowGraphInteger.FromValue(s)},getTarget:n,getPropertyName:[()=>"length"]}}const is={length:rs(e=>e.length,e=>e.map(e=>e._babylonTransformNode)),__array__:{__target__:!0,translation:{type:"Vector3",get:e=>{var t;return null===(t=e._babylonTransformNode)||void 0===t?void 0:t.position},set:(e,t)=>{var n;return null===(n=t._babylonTransformNode)||void 0===n?void 0:n.position.copyFrom(e)},getTarget:e=>e._babylonTransformNode,getPropertyName:[()=>"position"]},rotation:{type:"Quaternion",get:e=>{var t;return null===(t=e._babylonTransformNode)||void 0===t?void 0:t.rotationQuaternion},set:(e,t)=>{var n,s;return null===(s=null===(n=t._babylonTransformNode)||void 0===n?void 0:n.rotationQuaternion)||void 0===s?void 0:s.copyFrom(e)},getTarget:e=>e._babylonTransformNode,getPropertyName:[()=>"rotationQuaternion"]},scale:{type:"Vector3",get:e=>{var t;return null===(t=e._babylonTransformNode)||void 0===t?void 0:t.scaling},set:(e,t)=>{var n;return null===(n=t._babylonTransformNode)||void 0===n?void 0:n.scaling.copyFrom(e)},getTarget:e=>e._babylonTransformNode,getPropertyName:[()=>"scaling"]},weights:{__passThroughTarget__:!0,length:rs(e=>{const t=ds(e);return t?t.mtm.numTargets:void 0!==(null==e?void 0:e.mesh)?0:void 0},e=>null==e?void 0:e._babylonTransformNode),__array__:{__target__:!0,type:"number",get:(e,t)=>{const n=ds(e);if(n&&void 0!==t&&t>=0&&t<n.mtm.numTargets)return hs(n.mtm.getTarget(t).influence)},set:(e,t,n)=>{var s;const o="number"==typeof e?e:"number"==typeof(null==e?void 0:e.value)?e.value:e,r=ds(t);if(!(!r||void 0===n||n<0||n>=r.mtm.numTargets))for(const e of r.meshes){const t=null===(s=e.morphTargetManager)||void 0===s?void 0:s.getTarget(n);t&&(t.influence=o)}},getTarget:(e,t)=>{const n=ds(e);return n&&void 0!==t&&t>=0&&t<n.mtm.numTargets?n.mtm.getTarget(t):null==e?void 0:e._babylonTransformNode},getPropertyName:[()=>"influence"]},type:"number[]",get:e=>{const t=ds(e);if(!t)return[];const n=[];for(let e=0;e<t.mtm.numTargets;e++)n.push(hs(t.mtm.getTarget(e).influence));return n},getTarget:e=>null==e?void 0:e._babylonTransformNode,getPropertyName:[()=>"influence"]},matrix:{type:"Matrix",get:e=>{var n,s,o;return t.Matrix.Compose(null===(n=e._babylonTransformNode)||void 0===n?void 0:n.scaling,null===(s=e._babylonTransformNode)||void 0===s?void 0:s.rotationQuaternion,null===(o=e._babylonTransformNode)||void 0===o?void 0:o.position)},getTarget:e=>e._babylonTransformNode,isReadOnly:!0},globalMatrix:{type:"Matrix",get:e=>{var n,s,o,r,i,a,l;const u=t.Matrix.Identity();let c=e.parent;for(;c&&c.parent;)c=c.parent;const d=(null===(n=e._babylonTransformNode)||void 0===n?void 0:n.position._isDirty)||(null===(o=null===(s=e._babylonTransformNode)||void 0===s?void 0:s.rotationQuaternion)||void 0===o?void 0:o._isDirty)||(null===(r=e._babylonTransformNode)||void 0===r?void 0:r.scaling._isDirty);if(c){const t=null===(i=c._babylonTransformNode)||void 0===i?void 0:i.computeWorldMatrix(!0).invert();t&&(null===(l=null===(a=e._babylonTransformNode)||void 0===a?void 0:a.computeWorldMatrix(d))||void 0===l||l.multiplyToRef(t,u))}else e._babylonTransformNode&&u.copyFrom(e._babylonTransformNode.computeWorldMatrix(d));return u},getTarget:e=>e._babylonTransformNode,isReadOnly:!0},camera:{type:"string",get:e=>void 0!==e.camera?`/cameras/${e.camera}`:"",getTarget:e=>e,isReadOnly:!0},mesh:{type:"string",get:e=>void 0!==e.mesh?`/meshes/${e.mesh}`:"",getTarget:e=>e,isReadOnly:!0},skin:{type:"string",get:e=>void 0!==e.skin?`/skins/${e.skin}`:"",getTarget:e=>e,isReadOnly:!0},parent:{type:"string",get:e=>e.parent&&void 0!==e.parent.index?`/nodes/${e.parent.index}`:"",getTarget:e=>e,isReadOnly:!0},children:{length:rs(e=>{var t;return null!==(t=null==e?void 0:e.length)&&void 0!==t?t:0},e=>null!=e?e:[]),__array__:{__target__:!0,type:"string",get:e=>"number"==typeof e?`/nodes/${e}`:"",getTarget:()=>({__nodeIndex:!0}),isReadOnly:!0}},extensions:{EXT_lights_ies:{multiplier:{type:"number",get:e=>{var n,s;return null===(s=null===(n=e._babylonTransformNode)||void 0===n?void 0:n.getChildren(e=>e instanceof t.SpotLight,!0)[0])||void 0===s?void 0:s.intensity},getTarget:e=>{var n;return null===(n=e._babylonTransformNode)||void 0===n?void 0:n.getChildren(e=>e instanceof t.SpotLight,!0)[0]},set:(e,n)=>{if(n._babylonTransformNode){const s=n._babylonTransformNode.getChildren(e=>e instanceof t.SpotLight,!0)[0];s&&(s.intensity=e)}}},color:{type:"Color3",get:e=>{var n,s;return null===(s=null===(n=e._babylonTransformNode)||void 0===n?void 0:n.getChildren(e=>e instanceof t.SpotLight,!0)[0])||void 0===s?void 0:s.diffuse},getTarget:e=>{var n;return null===(n=e._babylonTransformNode)||void 0===n?void 0:n.getChildren(e=>e instanceof t.SpotLight,!0)[0]},set:(e,n)=>{if(n._babylonTransformNode){const s=n._babylonTransformNode.getChildren(e=>e instanceof t.SpotLight,!0)[0];s&&(s.diffuse=e)}}}},KHR_node_visibility:{visible:{type:"boolean",get:e=>!!e._primitiveBabylonMeshes&&e._primitiveBabylonMeshes[0].isVisible,getTarget:()=>{},set:(e,t)=>{t._primitiveBabylonMeshes&&t._primitiveBabylonMeshes.forEach(t=>t.isVisible=e)}}}}}},as={length:rs(e=>e.length,e=>e.map(e=>e._babylonAnimationGroup)),__array__:{__target__:!0,type:"string",get:e=>e&&"number"==typeof e.index?`/animations/${e.index}`:"",getTarget:e=>e._babylonAnimationGroup,isReadOnly:!0}},ls={length:rs(e=>e.length,e=>e.map(e=>{var t;return null===(t=e.primitives[0]._instanceData)||void 0===t?void 0:t.babylonSourceMesh})),__array__:{__target__:!0,primitives:{length:rs(e=>{var t;return null!==(t=null==e?void 0:e.length)&&void 0!==t?t:0},e=>null!=e?e:[]),__array__:{__target__:!0,material:{type:"string",get:e=>void 0!==e.material?`/materials/${e.material}`:"",getTarget:e=>e,isReadOnly:!0}}},weights:{length:rs(e=>{var t;return null!==(t=null==e?void 0:e.length)&&void 0!==t?t:0},e=>null!=e?e:[]),__array__:{__target__:!0,type:"number",get:e=>e,getTarget:()=>({__weightValue:!0}),isReadOnly:!0}}}};function us(e,t,n,s){const o=cs(e);return s?o[n][s]:o[n]}function cs(e,n,s){var o,r,i;return null===(i=null===(o=e._data)||void 0===o?void 0:o[null!==(r=null==s?void 0:s.fillMode)&&void 0!==r?r:t.Constants.MATERIAL_TriangleFillMode])||void 0===i?void 0:i.babylonMaterial}function ds(e){var t,n,s,o;const r=null==e?void 0:e._babylonTransformNode;if(!r)return;const i=function(e){var t;const n=null==e?void 0:e._babylonTransformNode;if(!n)return;if(n.morphTargetManager)return n.morphTargetManager;const s=e._primitiveBabylonMeshes;if(s)for(const e of s){if(null==e?void 0:e.morphTargetManager)return e.morphTargetManager;if(null===(t=null==e?void 0:e.sourceMesh)||void 0===t?void 0:t.morphTargetManager)return e.sourceMesh.morphTargetManager}}(e);if(i&&e._primitiveBabylonMeshes&&e._primitiveBabylonMeshes.length>0)return{mtm:i,meshes:e._primitiveBabylonMeshes};const a=r.getDescendants(!1);for(const e of a){const r=e,i=null!==(t=r.morphTargetManager)&&void 0!==t?t:null===(n=r.sourceMesh)||void 0===n?void 0:n.morphTargetManager;if(!i)continue;const a=[],l=r.parent;if(l)for(const e of l.getChildMeshes(!0))(null!==(s=e.morphTargetManager)&&void 0!==s?s:null===(o=e.sourceMesh)||void 0===o?void 0:o.morphTargetManager)===i&&a.push(e);return 0===a.length&&a.push(r),{mtm:i,meshes:a}}}function hs(e){return Number.isFinite(e)?parseFloat(e.toPrecision(7)):e}function ms(e,t,n){if(!e)return;let s=e.extensions;if(!s){if(!n)return;s={},e.extensions=s}let o=s[t.extensionKey];if(!o){if(!n)return;o={},s[t.extensionKey]=o}for(const e of t.texturePath){let t=o[e];if(!t){if(!n)return;t={},o[e]=t}o=t}if(!o.extensions){if(!n)return;o.extensions={}}let r=o.extensions.KHR_texture_transform;if(!r){if(!n)return;r={},o.extensions.KHR_texture_transform=r}return r}function fs(e,n,s){return{offset:{componentsCount:2,type:"Vector2",get:(o,r,i)=>{var a,l;const u=us(o,0,e,n);if(u)return new t.Vector2(u.uOffset,u.vOffset);if(s){const e=ms(o,s,!1),n=null==e?void 0:e.offset;return new t.Vector2(null!==(a=null==n?void 0:n[0])&&void 0!==a?a:0,null!==(l=null==n?void 0:n[1])&&void 0!==l?l:0)}return new t.Vector2(0,0)},getTarget:cs,set:(t,o,r,i)=>{const a=us(o,0,e,n);if(a&&(a.uOffset=t.x,a.vOffset=t.y),s){const e=ms(o,s,!0);e&&(e.offset=[t.x,t.y])}},getPropertyName:[()=>`${e}${n?"."+n:""}.uOffset`,()=>`${e}${n?"."+n:""}.vOffset`]},rotation:{type:"number",get:(t,o,r)=>{var i;const a=us(t,0,e,n);if(a)return a.wAng;if(s){const e=ms(t,s,!1);return null!==(i=null==e?void 0:e.rotation)&&void 0!==i?i:0}return 0},getTarget:cs,set:(t,o,r,i)=>{const a=us(o,0,e,n);if(a&&(a.wAng=t),s){const e=ms(o,s,!0);e&&(e.rotation=t)}},getPropertyName:[()=>`${e}${n?"."+n:""}.wAng`]},scale:{componentsCount:2,type:"Vector2",get:(o,r,i)=>{var a,l;const u=us(o,0,e,n);if(u)return new t.Vector2(u.uScale,u.vScale);if(s){const e=ms(o,s,!1),n=null==e?void 0:e.scale;return new t.Vector2(null!==(a=null==n?void 0:n[0])&&void 0!==a?a:1,null!==(l=null==n?void 0:n[1])&&void 0!==l?l:1)}return new t.Vector2(1,1)},getTarget:cs,set:(t,o,r,i)=>{const a=us(o,0,e,n);if(a&&(a.uScale=t.x,a.vScale=t.y),s){const e=ms(o,s,!0);e&&(e.scale=[t.x,t.y])}},getPropertyName:[()=>`${e}${n?"."+n:""}.uScale`,()=>`${e}${n?"."+n:""}.vScale`]}}}const ps={scene:{__target__:!0,type:"number",get:e=>null!=e?e:0,getTarget:()=>({__gltfRoot:!0}),isReadOnly:!0,getPropertyName:[()=>"scene"]},cameras:{length:rs(e=>e.length,e=>e.map(e=>e._babylonCamera)),__array__:{__target__:!0,orthographic:{xmag:{componentsCount:2,type:"Vector2",get:e=>{var n,s,o,r;return new t.Vector2(null!==(s=null===(n=e._babylonCamera)||void 0===n?void 0:n.orthoLeft)&&void 0!==s?s:0,null!==(r=null===(o=e._babylonCamera)||void 0===o?void 0:o.orthoRight)&&void 0!==r?r: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=>{var n,s,o,r;return new t.Vector2(null!==(s=null===(n=e._babylonCamera)||void 0===n?void 0:n.orthoBottom)&&void 0!==s?s:0,null!==(r=null===(o=e._babylonCamera)||void 0===o?void 0:o.orthoTop)&&void 0!==r?r: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=>{var t;return null===(t=e._babylonCamera)||void 0===t?void 0:t.maxZ},set:(e,t)=>{t._babylonCamera&&(t._babylonCamera.maxZ=e)},getTarget:e=>e,getPropertyName:[()=>"maxZ"]},znear:{type:"number",get:e=>{var t;return null===(t=e._babylonCamera)||void 0===t?void 0:t.minZ},set:(e,t)=>{t._babylonCamera&&(t._babylonCamera.minZ=e)},getTarget:e=>e,getPropertyName:[()=>"minZ"]}},perspective:{aspectRatio:{type:"number",get:e=>{var t;return null===(t=e._babylonCamera)||void 0===t?void 0:t.getEngine().getAspectRatio(e._babylonCamera)},getTarget:e=>e,getPropertyName:[()=>"aspectRatio"],isReadOnly:!0},yfov:{type:"number",get:e=>{var t;return null===(t=e._babylonCamera)||void 0===t?void 0:t.fov},set:(e,t)=>{t._babylonCamera&&(t._babylonCamera.fov=e)},getTarget:e=>e,getPropertyName:[()=>"fov"]},zfar:{type:"number",get:e=>{var t;return null===(t=e._babylonCamera)||void 0===t?void 0:t.maxZ},set:(e,t)=>{t._babylonCamera&&(t._babylonCamera.maxZ=e)},getTarget:e=>e,getPropertyName:[()=>"maxZ"]},znear:{type:"number",get:e=>{var t;return null===(t=e._babylonCamera)||void 0===t?void 0:t.minZ},set:(e,t)=>{t._babylonCamera&&(t._babylonCamera.minZ=e)},getTarget:e=>e,getPropertyName:[()=>"minZ"]}}}},nodes:is,materials:{length:rs(e=>e.length,e=>e.map(e=>{var n,s;return null===(s=null===(n=e._data)||void 0===n?void 0:n[t.Constants.MATERIAL_TriangleFillMode])||void 0===s?void 0:s.babylonMaterial})),__array__:{__target__:!0,doubleSided:{type:"boolean",get:(e,t,n)=>{var s;return!(null===(s=cs(e,0,n))||void 0===s?void 0:s.backFaceCulling)},set:(e,t,n,s)=>{const o=cs(t,0,s);o&&(o.backFaceCulling=!e)},getTarget:(e,t,n)=>cs(e,0,n),getPropertyName:[()=>"backFaceCulling"]},alphaCutoff:{type:"number",get:(e,t,n)=>{var s;return null===(s=cs(e,0,n))||void 0===s?void 0:s.alphaCutOff},set:(e,t,n,s)=>{const o=cs(t,0,s);o&&(o.alphaCutOff=e)},getTarget:(e,t,n)=>cs(e,0,n),getPropertyName:[()=>"alphaCutOff"]},emissiveFactor:{type:"Color3",get:(e,t,n)=>cs(e,0,n).emissiveColor,set:(e,t,n,s)=>cs(t,0,s).emissiveColor.copyFrom(e),getTarget:(e,t,n)=>cs(e,0,n),getPropertyName:[()=>"emissiveColor"]},emissiveTexture:{extensions:{KHR_texture_transform:fs("emissiveTexture")}},normalTexture:{scale:{type:"number",get:(e,t,n)=>{var s;return null===(s=us(e,0,"bumpTexture"))||void 0===s?void 0:s.level},set:(e,t,n,s)=>{const o=us(t,0,"bumpTexture");o&&(o.level=e)},getTarget:(e,t,n)=>cs(e,0,n),getPropertyName:[()=>"level"]},extensions:{KHR_texture_transform:fs("bumpTexture")}},occlusionTexture:{strength:{type:"number",get:(e,t,n)=>cs(e,0,n).ambientTextureStrength,set:(e,t,n,s)=>{const o=cs(t,0,s);o&&(o.ambientTextureStrength=e)},getTarget:(e,t,n)=>cs(e,0,n),getPropertyName:[()=>"ambientTextureStrength"]},extensions:{KHR_texture_transform:fs("ambientTexture")}},pbrMetallicRoughness:{baseColorFactor:{type:"Color4",get:(e,n,s)=>{const o=cs(e,0,s);return t.Color4.FromColor3(o.albedoColor,o.alpha)},set:(e,t,n,s)=>{const o=cs(t,0,s);o.albedoColor.set(e.r,e.g,e.b),o.alpha=e.a},getTarget:(e,t,n)=>cs(e,0,n),getPropertyName:[()=>"albedoColor",()=>"alpha"]},baseColorTexture:{extensions:{KHR_texture_transform:fs("albedoTexture")}},metallicFactor:{type:"number",get:(e,t,n)=>cs(e,0,n).metallic,set:(e,t,n,s)=>{const o=cs(t,0,s);o&&(o.metallic=e)},getTarget:(e,t,n)=>cs(e,0,n),getPropertyName:[()=>"metallic"]},roughnessFactor:{type:"number",get:(e,t,n)=>cs(e,0,n).roughness,set:(e,t,n,s)=>{const o=cs(t,0,s);o&&(o.roughness=e)},getTarget:(e,t,n)=>cs(e,0,n),getPropertyName:[()=>"roughness"]},metallicRoughnessTexture:{extensions:{KHR_texture_transform:fs("metallicTexture")}}},extensions:{KHR_materials_anisotropy:{anisotropyStrength:{type:"number",get:(e,t,n)=>{var s,o;return null===(o=null===(s=cs(e,0,n))||void 0===s?void 0:s.anisotropy)||void 0===o?void 0:o.intensity},set:(e,t,n,s)=>{const o=cs(t,0,s);o&&(o.anisotropy.intensity=e)},getTarget:(e,t,n)=>cs(e,0,n),getPropertyName:[()=>"anisotropy.intensity"]},anisotropyRotation:{type:"number",get:(e,t,n)=>{var s,o;return null===(o=null===(s=cs(e,0,n))||void 0===s?void 0:s.anisotropy)||void 0===o?void 0:o.angle},set:(e,t,n,s)=>{const o=cs(t,0,s);o&&(o.anisotropy.angle=e)},getTarget:(e,t,n)=>cs(e,0,n),getPropertyName:[()=>"anisotropy.angle"]},anisotropyTexture:{extensions:{KHR_texture_transform:fs("anisotropy","texture")}}},KHR_materials_clearcoat:{clearcoatFactor:{type:"number",get:(e,t,n)=>cs(e,0,n).clearCoat.intensity,set:(e,t,n,s)=>{cs(t,0,s).clearCoat.intensity=e},getTarget:(e,t,n)=>cs(e,0,n),getPropertyName:[()=>"clearCoat.intensity"]},clearcoatRoughnessFactor:{type:"number",get:(e,t,n)=>cs(e,0,n).clearCoat.roughness,set:(e,t,n,s)=>{cs(t,0,s).clearCoat.roughness=e},getTarget:(e,t,n)=>cs(e,0,n),getPropertyName:[()=>"clearCoat.roughness"]},clearcoatTexture:{extensions:{KHR_texture_transform:fs("clearCoat","texture")}},clearcoatNormalTexture:{scale:{type:"number",get:(e,t,n)=>{var s;return null===(s=cs(e,0,n).clearCoat.bumpTexture)||void 0===s?void 0:s.level},getTarget:cs,set:(e,t,n,s)=>cs(t,0,s).clearCoat.bumpTexture.level=e},extensions:{KHR_texture_transform:fs("clearCoat","bumpTexture")}},clearcoatRoughnessTexture:{extensions:{KHR_texture_transform:fs("clearCoat","textureRoughness")}}},KHR_materials_dispersion:{dispersion:{type:"number",get:(e,t,n)=>cs(e,0,n).subSurface.dispersion,getTarget:cs,set:(e,t,n,s)=>cs(t,0,s).subSurface.dispersion=e}},KHR_materials_emissive_strength:{emissiveStrength:{type:"number",get:(e,t,n)=>cs(e,0,n).emissiveIntensity,getTarget:cs,set:(e,t,n,s)=>cs(t,0,s).emissiveIntensity=e}},KHR_materials_ior:{ior:{type:"number",get:(e,t,n)=>cs(e,0,n).indexOfRefraction,getTarget:cs,set:(e,t,n,s)=>cs(t,0,s).indexOfRefraction=e}},KHR_materials_iridescence:{iridescenceFactor:{type:"number",get:(e,t,n)=>cs(e,0,n).iridescence.intensity,getTarget:cs,set:(e,t,n,s)=>cs(t,0,s).iridescence.intensity=e},iridescenceIor:{type:"number",get:(e,t,n)=>cs(e,0,n).iridescence.indexOfRefraction,getTarget:cs,set:(e,t,n,s)=>cs(t,0,s).iridescence.indexOfRefraction=e},iridescenceTexture:{extensions:{KHR_texture_transform:fs("iridescence","texture")}},iridescenceThicknessMaximum:{type:"number",get:(e,t,n)=>cs(e,0,n).iridescence.maximumThickness,getTarget:cs,set:(e,t,n,s)=>cs(t,0,s).iridescence.maximumThickness=e},iridescenceThicknessMinimum:{type:"number",get:(e,t,n)=>cs(e,0,n).iridescence.minimumThickness,getTarget:cs,set:(e,t,n,s)=>cs(t,0,s).iridescence.minimumThickness=e},iridescenceThicknessTexture:{extensions:{KHR_texture_transform:fs("iridescence","thicknessTexture")}}},KHR_materials_sheen:{sheenColorFactor:{type:"Color3",get:(e,t,n)=>cs(e,0,n).sheen.color,getTarget:cs,set:(e,t,n,s)=>cs(t,0,s).sheen.color.copyFrom(e)},sheenColorTexture:{extensions:{KHR_texture_transform:fs("sheen","texture")}},sheenRoughnessFactor:{type:"number",get:(e,t,n)=>cs(e,0,n).sheen.intensity,getTarget:cs,set:(e,t,n,s)=>cs(t,0,s).sheen.intensity=e},sheenRoughnessTexture:{extensions:{KHR_texture_transform:fs("sheen","textureRoughness")}}},KHR_materials_specular:{specularFactor:{type:"number",get:(e,t,n)=>cs(e,0,n).metallicF0Factor,getTarget:cs,set:(e,t,n,s)=>cs(t,0,s).metallicF0Factor=e,getPropertyName:[()=>"metallicF0Factor"]},specularColorFactor:{type:"Color3",get:(e,t,n)=>cs(e,0,n).metallicReflectanceColor,getTarget:cs,set:(e,t,n,s)=>cs(t,0,s).metallicReflectanceColor.copyFrom(e),getPropertyName:[()=>"metallicReflectanceColor"]},specularTexture:{extensions:{KHR_texture_transform:fs("metallicReflectanceTexture")}},specularColorTexture:{extensions:{KHR_texture_transform:fs("reflectanceTexture")}}},KHR_materials_transmission:{transmissionFactor:{type:"number",get:(e,t,n)=>cs(e,0,n).subSurface.refractionIntensity,getTarget:cs,set:(e,t,n,s)=>cs(t,0,s).subSurface.refractionIntensity=e,getPropertyName:[()=>"subSurface.refractionIntensity"]},transmissionTexture:{extensions:{KHR_texture_transform:fs("subSurface","refractionIntensityTexture",{extensionKey:"KHR_materials_transmission",texturePath:["transmissionTexture"]})}}},KHR_materials_diffuse_transmission:{diffuseTransmissionFactor:{type:"number",get:(e,t,n)=>cs(e,0,n).subSurface.translucencyIntensity,getTarget:cs,set:(e,t,n,s)=>cs(t,0,s).subSurface.translucencyIntensity=e},diffuseTransmissionTexture:{extensions:{KHR_texture_transform:fs("subSurface","translucencyIntensityTexture",{extensionKey:"KHR_materials_diffuse_transmission",texturePath:["diffuseTransmissionTexture"]})}},diffuseTransmissionColorFactor:{type:"Color3",get:(e,t,n)=>cs(e,0,n).subSurface.translucencyColor,getTarget:cs,set:(e,t,n,s)=>{var o;return e&&(null===(o=cs(t,0,s).subSurface.translucencyColor)||void 0===o?void 0:o.copyFrom(e))}},diffuseTransmissionColorTexture:{extensions:{KHR_texture_transform:fs("subSurface","translucencyColorTexture",{extensionKey:"KHR_materials_diffuse_transmission",texturePath:["diffuseTransmissionColorTexture"]})}}},KHR_materials_volume:{attenuationColor:{type:"Color3",get:(e,t,n)=>cs(e,0,n).subSurface.tintColor,getTarget:cs,set:(e,t,n,s)=>cs(t,0,s).subSurface.tintColor.copyFrom(e)},attenuationDistance:{type:"number",get:(e,t,n)=>cs(e,0,n).subSurface.tintColorAtDistance,getTarget:cs,set:(e,t,n,s)=>cs(t,0,s).subSurface.tintColorAtDistance=e},thicknessFactor:{type:"number",get:(e,t,n)=>cs(e,0,n).subSurface.maximumThickness,getTarget:cs,set:(e,t,n,s)=>cs(t,0,s).subSurface.maximumThickness=e},thicknessTexture:{extensions:{KHR_texture_transform:fs("subSurface","thicknessTexture",{extensionKey:"KHR_materials_volume",texturePath:["thicknessTexture"]})}}}}}},extensions:{KHR_lights_punctual:{lights:{length:rs(e=>e.length,e=>e.map(e=>e._babylonLight)),__array__:{__target__:!0,color:{type:"Color3",get:e=>{var t;return null===(t=e._babylonLight)||void 0===t?void 0:t.diffuse},set:(e,t)=>{var n;return null===(n=t._babylonLight)||void 0===n?void 0:n.diffuse.copyFrom(e)},getTarget:e=>e._babylonLight,getPropertyName:[e=>"diffuse"]},intensity:{type:"number",get:e=>{var t;return null===(t=e._babylonLight)||void 0===t?void 0:t.intensity},set:(e,t)=>t._babylonLight?t._babylonLight.intensity=e:void 0,getTarget:e=>e._babylonLight,getPropertyName:[e=>"intensity"]},range:{type:"number",get:e=>{var t;return null===(t=e._babylonLight)||void 0===t?void 0:t.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=>{var t;return null===(t=e._babylonLight)||void 0===t?void 0:t.innerAngle},set:(e,t)=>t._babylonLight?t._babylonLight.innerAngle=e:void 0,getTarget:e=>e._babylonLight,getPropertyName:[e=>"innerConeAngle"]},outerConeAngle:{type:"number",get:e=>{var t;return null===(t=e._babylonLight)||void 0===t?void 0:t.angle},set:(e,t)=>t._babylonLight?t._babylonLight.angle=e:void 0,getTarget:e=>e._babylonLight,getPropertyName:[e=>"outerConeAngle"]}}}}},EXT_lights_area:{lights:{length:rs(e=>e.length,e=>e.map(e=>e._babylonLight)),__array__:{__target__:!0,color:{type:"Color3",get:e=>{var t;return null===(t=e._babylonLight)||void 0===t?void 0:t.diffuse},set:(e,t)=>{var n;return null===(n=t._babylonLight)||void 0===n?void 0:n.diffuse.copyFrom(e)},getTarget:e=>e._babylonLight,getPropertyName:[e=>"diffuse"]},intensity:{type:"number",get:e=>{var t;return null===(t=e._babylonLight)||void 0===t?void 0:t.intensity},set:(e,t)=>t._babylonLight?t._babylonLight.intensity=e:void 0,getTarget:e=>e._babylonLight,getPropertyName:[e=>"intensity"]},size:{type:"number",get:e=>{var t;return null===(t=e._babylonLight)||void 0===t?void 0:t.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=>{var t,n;return(null===(t=e._babylonLight)||void 0===t?void 0:t.width)/(null===(n=e._babylonLight)||void 0===n?void 0:n.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:rs(e=>e.length,e=>e.map(e=>e._babylonLight))}},EXT_lights_image_based:{lights:{length:rs(e=>e.length,e=>e.map(e=>e._babylonTexture)),__array__:{__target__:!0,intensity:{type:"number",get:e=>{var t;return null===(t=e._babylonTexture)||void 0===t?void 0:t.level},set:(e,t)=>{t._babylonTexture&&(t._babylonTexture.level=e)},getTarget:e=>e._babylonTexture},rotation:{type:"Quaternion",get:e=>{var n;return e._babylonTexture&&t.Quaternion.FromRotationMatrix(null===(n=e._babylonTexture)||void 0===n?void 0:n.getReflectionTextureMatrix())},set:(e,n)=>{var s;n._babylonTexture&&((null===(s=n._babylonTexture.getScene())||void 0===s?void 0:s.useRightHandedSystem)||(e=t.Quaternion.Inverse(e)),t.Matrix.FromQuaternionToRef(e,n._babylonTexture.getReflectionTextureMatrix()))},getTarget:e=>e._babylonTexture}}}}},animations:as,meshes:ls,scenes:{length:rs(e=>e.length,e=>e),__array__:{__target__:!0,nodes:{length:rs(e=>{var t;return null!==(t=null==e?void 0:e.length)&&void 0!==t?t:0},e=>null!=e?e:[]),__array__:{__target__:!0,type:"string",get:e=>"number"==typeof e?`/nodes/${e}`:"",getTarget:()=>({__nodeIndex:!0}),isReadOnly:!0}}}},skins:{length:rs(e=>e.length,e=>e.map(e=>{var t;return null===(t=e._data)||void 0===t?void 0:t.babylonSkeleton})),__array__:{__target__:!0,joints:{length:rs(e=>{var t;return null!==(t=null==e?void 0:e.length)&&void 0!==t?t:0},e=>null!=e?e:[]),__array__:{__target__:!0,type:"string",get:e=>"number"==typeof e?`/nodes/${e}`:"",getTarget:()=>({__nodeIndex:!0}),isReadOnly:!0}},skeleton:{type:"string",get:e=>{const t=e.skeleton;return"number"==typeof t?`/nodes/${t}`:""},getTarget:e=>e,isReadOnly:!0}}}};function _s(e){return new os(e,ps)}function gs(e){const t=e.split("/").map(e=>e.replace(/{}/g,"__array__"));let n=ps;for(const e of t)e&&(n=n[e]);if(n&&n.type&&n.get)return n}function ys(e,t){const n=e.split("/").map(e=>e.replace(/{}/g,"__array__"));let s=ps;for(const e of n)e&&(s=s[e]);s&&s.type&&s.get&&(s.interpolation=t)}function vs(e,t){const n=e.split("/").map(e=>e.replace(/{}/g,"__array__"));let s=ps;for(const e of n)if(e){if(!s[e]){if("?"===e){s.__ignoreObjectTree__=!0;continue}s[e]={},"__array__"===e&&(s[e].__target__=!0)}s=s[e]}Object.assign(s,t)}const bs=new t.Lazy(()=>Promise.resolve(BABYLON)),xs=new t.Lazy(()=>Promise.resolve().then(function(){return Ps}));class Ts{static Get(e,t,n){if(!t||null==n||!t[n])throw new Error(`${e}: Failed to find index (${n})`);return t[n]}static TryGet(e,t){return e&&null!=t&&e[t]?e[t]:null}static Assign(e){if(e)for(let t=0;t<e.length;t++)e[t].index=t}}function As(e){if(e.min&&e.max){const n=e.min,s=e.max,o=t.TmpVectors.Vector3[0].copyFromFloats(n[0],n[1],n[2]),r=t.TmpVectors.Vector3[1].copyFromFloats(s[0],s[1],s[2]);if(e.normalized&&5126!==e.componentType){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}const n=1/t;o.scaleInPlace(n),r.scaleInPlace(n)}return new t.BoundingInfo(o,r)}return null}class Ms{isMatchingMaterialType(e){if(!e)return!1;const t=Array.from(this._pbrMaterialImpls.values());for(const n of t)if(e instanceof n.materialClass)return!0;return!1}static RegisterExtension(e,t){ts(e,!1,t)}static UnregisterExtension(e){return ns(e)}get gltf(){if(!this._gltf)throw new 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 new Error("Scene is not available");return this._babylonScene}get rootBabylonMesh(){return this._rootBabylonMesh}get rootUrl(){return this._rootUrl}constructor(e){this._completePromises=new Array,this._assetContainer=null,this._babylonLights=[],this._disableInstancedMesh=0,this._allMaterialsDirtyRequired=!1,this._skipStartAnimationStep=!1,this._extensions=new Array,this._disposed=!1,this._rootUrl=null,this._fileName=null,this._uniqueRootUrl=null,this._bin=null,this._rootBabylonMesh=null,this._defaultBabylonMaterialData={},this._postSceneLoadActions=new Array,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){const n=Array.from(this._pbrMaterialImpls.values());for(const s of n)if(e instanceof s.materialClass){t=new s.adapterClass(e);break}if(!t)throw new Error("Appropriate material adapter class not found");const s=t;this._materialAdapterCache.set(e,s),this._materialAdapters.add(s)}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())}importMeshAsync(e,t,n,s,o,r){return b(this,arguments,void 0,function*(e,t,n,s,o,r,i=""){return yield Promise.resolve().then(()=>b(this,void 0,void 0,function*(){this._babylonScene=t,this._assetContainer=n,this._loadData(s);let r=null;if(e){const t={};if(this._gltf.nodes)for(const e of this._gltf.nodes)e.name&&(t[e.name]=e.index);r=(e instanceof Array?e:[e]).map(e=>{const n=t[e];if(void 0===n)throw new Error(`Failed to find node '${e}'`);return n})}return yield this._loadAsync(o,i,r,()=>({meshes:this._getMeshes(),particleSystems:[],skeletons:this._getSkeletons(),animationGroups:this._getAnimationGroups(),lights:this._babylonLights,transformNodes:this._getTransformNodes(),geometries:this._getGeometries(),spriteManagers:[]}))}))})}loadAsync(e,t,n,s){return b(this,arguments,void 0,function*(e,t,n,s,o=""){return this._babylonScene=e,this._loadData(t),yield this._loadAsync(n,o,null,()=>{})})}_loadAsync(n,s,o,r){return b(this,void 0,void 0,function*(){return yield Promise.resolve().then(()=>b(this,void 0,void 0,function*(){var i;if(this._rootUrl=n,this._uniqueRootUrl=!n.startsWith("file:")&&s?n:`${n}${t.RandomGUID()}/`,this._fileName=s,this._allMaterialsDirtyRequired=!1,yield this._loadExtensionsAsync(),!this.parent.skipMaterials){const e=this.parent.useOpenPBR||this.isExtensionUsed("KHR_materials_openpbr");let t=!1;this.parent.useOpenPBR?(null===(i=this._gltf.materials)||void 0===i?void 0:i.length)&&this._gltf.materials.some(e=>{var t;return!(null===(t=e.extensions)||void 0===t?void 0:t.KHR_materials_openpbr)})&&(t=!0):t=!0;const n=[];e&&!this._pbrMaterialImpls.has("openpbr")&&n.push(Promise.all([Promise.resolve(BABYLON),Promise.resolve().then(function(){return Ns})]).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([Promise.resolve(BABYLON),Promise.resolve().then(function(){return Ds})]).then(([{PBRMaterial:e,RegisterPbrMaterial:t},{PBRMaterialLoadingAdapter:n}])=>{t(),this._pbrMaterialImpls.set("pbr",{materialClass:e,adapterClass:n})})),yield Promise.all(n)}const a=`${e.GLTFLoaderState[e.GLTFLoaderState.LOADING]} => ${e.GLTFLoaderState[e.GLTFLoaderState.READY]}`,l=`${e.GLTFLoaderState[e.GLTFLoaderState.LOADING]} => ${e.GLTFLoaderState[e.GLTFLoaderState.COMPLETE]}`;this._parent._startPerformanceCounter(a),this._parent._startPerformanceCounter(l),this._parent._setState(e.GLTFLoaderState.LOADING),this._extensionsOnLoading();const u=new Array,c=this._babylonScene.blockMaterialDirtyMechanism;if(this._babylonScene.blockMaterialDirtyMechanism=!0,!this.parent.loadOnlyMaterials)if(o)u.push(this.loadSceneAsync("/nodes",{nodes:o,index:-1}));else if(null!=this._gltf.scene||this._gltf.scenes&&this._gltf.scenes[0]){const e=Ts.Get("/scene",this._gltf.scenes,this._gltf.scene||0);u.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){const n=this._gltf.materials[e],s="/materials/"+e,o=t.Material.TriangleFillMode;u.push(this._loadMaterialAsync(s,n,null,o,()=>{}))}this._allMaterialsDirtyRequired?this._babylonScene.blockMaterialDirtyMechanism=c:this._babylonScene._forceBlockMaterialDirtyMechanism(c),this._parent.compileMaterials&&u.push(this._compileMaterialsAsync()),this._parent.compileShadowGenerators&&u.push(this._compileShadowGeneratorsAsync());const d=Promise.all(u).then(()=>{this._rootBabylonMesh&&this._rootBabylonMesh!==this._parent.customRootNode&&this._rootBabylonMesh.setEnabled(!0);for(const e of this._babylonScene.materials){const t=e;void 0!==t.maxSimultaneousLights&&(t.maxSimultaneousLights=Math.max(t.maxSimultaneousLights,this._babylonScene.lights.length))}for(const e of Array.from(this._materialAdapters))this._completePromises.push(e.finalizeAsync(this));return this._extensionsOnReady(),this._parent._setState(e.GLTFLoaderState.READY),this._skipStartAnimationStep||this._startAnimations(),r()});return yield d.then(n=>(this._parent._endPerformanceCounter(a),t.Tools.SetImmediate(()=>{this._disposed||Promise.all(this._completePromises).then(()=>{this._parent._endPerformanceCounter(l),this._parent._setState(e.GLTFLoaderState.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()})}),n))})).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){const n=this._gltf.buffers;if(n&&n[0]&&!n[0].uri){const s=n[0];(s.byteLength<e.bin.byteLength-3||s.byteLength>e.bin.byteLength)&&t.Logger.Warn(`Binary buffer length (${s.byteLength}) from JSON does not match chunk length (${e.bin.byteLength})`),this._bin=e.bin}else t.Logger.Warn("Unexpected BIN chunk")}}_setupData(){if(Ts.Assign(this._gltf.accessors),Ts.Assign(this._gltf.animations),Ts.Assign(this._gltf.buffers),Ts.Assign(this._gltf.bufferViews),Ts.Assign(this._gltf.cameras),Ts.Assign(this._gltf.images),Ts.Assign(this._gltf.materials),Ts.Assign(this._gltf.meshes),Ts.Assign(this._gltf.nodes),Ts.Assign(this._gltf.samplers),Ts.Assign(this._gltf.scenes),Ts.Assign(this._gltf.skins),Ts.Assign(this._gltf.textures),this._gltf.nodes){const e={};for(const t of this._gltf.nodes)if(t.children)for(const n of t.children)e[n]=t.index;const t=this._createRootNode();for(const n of this._gltf.nodes){const s=e[n.index];n.parent=void 0===s?t:this._gltf.nodes[s]}}}_loadExtensionsAsync(){return b(this,void 0,void 0,function*(){var e;const n=[];if(es.forEach((e,s)=>{var o;!1===(null===(o=this.parent.extensionOptions[s])||void 0===o?void 0:o.enabled)?e.isGLTFExtension&&this.isExtensionUsed(s)&&t.Logger.Warn(`Extension ${s} is used but has been explicitly disabled.`):e.isGLTFExtension&&!this.isExtensionUsed(s)||n.push((()=>b(this,void 0,void 0,function*(){const n=yield e.factory(this);return n.name!==s&&t.Logger.Warn(`The name of the glTF loader extension instance does not match the registered name: ${n.name} !== ${s}`),this._parent.onExtensionLoadedObservable.notifyObservers(n),n}))())}),this._extensions.push(...yield Promise.all(n)),this._extensions.sort((e,t)=>(e.order||Number.MAX_VALUE)-(t.order||Number.MAX_VALUE)),this._parent.onExtensionLoadedObservable.clear(),this._gltf.extensionsRequired)for(const t of this._gltf.extensionsRequired)if(!this._extensions.some(e=>e.name===t&&e.enabled)){if(!1===(null===(e=this.parent.extensionOptions[t])||void 0===e?void 0:e.enabled))throw new Error(`Required extension ${t} is disabled`);throw new Error(`Required extension ${t} is not available`)}})}_createRootNode(){if(void 0!==this._parent.customRootNode)return this._rootBabylonMesh=this._parent.customRootNode,{_babylonTransformNode:null===this._rootBabylonMesh?void 0:this._rootBabylonMesh,index:-1};this._babylonScene._blockEntityCollection=!!this._assetContainer;const n=new t.Mesh("__root__",this._babylonScene);this._rootBabylonMesh=n,this._rootBabylonMesh._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,this._rootBabylonMesh.setEnabled(!1);const s={_babylonTransformNode:this._rootBabylonMesh,index:-1};switch(this._parent.coordinateSystemMode){case e.GLTFLoaderCoordinateSystemMode.AUTO:this._babylonScene.useRightHandedSystem||(s.rotation=[0,1,0,0],s.scale=[1,1,-1],Ms._LoadTransform(s,this._rootBabylonMesh));break;case e.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED:this._babylonScene.useRightHandedSystem=!0;break;default:throw new Error(`Invalid coordinate system mode (${this._parent.coordinateSystemMode})`)}return this._parent.onMeshLoadedObservable.notifyObservers(n),s}loadSceneAsync(e,t){const n=this._extensionsLoadSceneAsync(e,t);if(n)return n;const s=new Array;if(this.logOpen(`${e} ${t.name||""}`),t.nodes)for(const n of t.nodes){const t=Ts.Get(`${e}/nodes/${n}`,this._gltf.nodes,n);s.push(this.loadNodeAsync(`/nodes/${t.index}`,t,e=>{e.parent=this._rootBabylonMesh}))}for(const e of this._postSceneLoadActions)e();return s.push(this._loadAnimationsAsync()),this.logClose(),Promise.all(s).then(()=>{})}_forEachPrimitive(e,t){if(e._primitiveBabylonMeshes)for(const n of e._primitiveBabylonMeshes)t(n)}_getGeometries(){const e=[],t=this._gltf.nodes;if(t)for(const n of t)this._forEachPrimitive(n,t=>{const n=t.geometry;n&&-1===e.indexOf(n)&&e.push(n)});return e}_getMeshes(){const e=[];this._rootBabylonMesh instanceof t.AbstractMesh&&e.push(this._rootBabylonMesh);const n=this._gltf.nodes;if(n)for(const t of n)this._forEachPrimitive(t,t=>{e.push(t)});return e}_getTransformNodes(){const e=[],t=this._gltf.nodes;if(t)for(const n of t)n._babylonTransformNode&&"TransformNode"===n._babylonTransformNode.getClassName()&&e.push(n._babylonTransformNode),n._babylonTransformNodeForSkin&&e.push(n._babylonTransformNodeForSkin);return e}_getSkeletons(){const e=[],t=this._gltf.skins;if(t)for(const n of t)n._data&&e.push(n._data.babylonSkeleton);return e}_getAnimationGroups(){const e=[],t=this._gltf.animations;if(t)for(const n of t)n._babylonAnimationGroup&&e.push(n._babylonAnimationGroup);return e}_startAnimations(){switch(this._parent.animationStartMode){case e.GLTFLoaderAnimationStartMode.NONE:break;case e.GLTFLoaderAnimationStartMode.FIRST:{const e=this._getAnimationGroups();0!==e.length&&e[0].start(!0);break}case e.GLTFLoaderAnimationStartMode.ALL:{const e=this._getAnimationGroups();for(const t of e)t.start(!0);break}default:return void t.Logger.Error(`Invalid animation start mode (${this._parent.animationStartMode})`)}}loadNodeAsync(e,n,s=()=>{}){const o=this._extensionsLoadNodeAsync(e,n,s);if(o)return o;if(n._babylonTransformNode)throw new Error(`${e}: Invalid recursive node hierarchy`);const r=new Array;this.logOpen(`${e} ${n.name||""}`);const i=t=>{if(Ms.AddPointerMetadata(t,e),Ms._LoadTransform(n,t),null!=n.camera){const s=Ts.Get(`${e}/camera`,this._gltf.cameras,n.camera);r.push(this.loadCameraAsync(`/cameras/${s.index}`,s,e=>{e.parent=t,this._babylonScene.useRightHandedSystem||(t.scaling.x=-1)}))}if(n.children)for(const s of n.children){const n=Ts.Get(`${e}/children/${s}`,this._gltf.nodes,s);r.push(this.loadNodeAsync(`/nodes/${n.index}`,n,e=>{e.parent=t}))}s(t)},a=null!=n.mesh,l=this._parent.loadSkins&&null!=n.skin;if(!a||l){const e=n.name||`node${n.index}`;this._babylonScene._blockEntityCollection=!!this._assetContainer;const s=new t.TransformNode(e,this._babylonScene);s._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,null==n.mesh?n._babylonTransformNode=s:n._babylonTransformNodeForSkin=s,i(s)}if(a)if(l){const s=Ts.Get(`${e}/mesh`,this._gltf.meshes,n.mesh);r.push(this._loadMeshAsync(`/meshes/${s.index}`,n,s,s=>{const o=n._babylonTransformNodeForSkin;s.metadata=t.deepMerge(o.metadata,s.metadata||{});const i=Ts.Get(`${e}/skin`,this._gltf.skins,n.skin);r.push(this._loadSkinAsync(`/skins/${i.index}`,n,i,e=>{this._forEachPrimitive(n,t=>{t.skeleton=e}),this._postSceneLoadActions.push(()=>{if(null!=i.skeleton){const e=Ts.Get(`/skins/${i.index}/skeleton`,this._gltf.nodes,i.skeleton).parent;n.index===e.index?s.parent=o.parent:s.parent=e._babylonTransformNode}else s.parent=this._rootBabylonMesh;this._parent.onSkinLoadedObservable.notifyObservers({node:o,skinnedNode:s})})}))}))}else{const t=Ts.Get(`${e}/mesh`,this._gltf.meshes,n.mesh);r.push(this._loadMeshAsync(`/meshes/${t.index}`,n,t,i))}return this.logClose(),Promise.all(r).then(()=>(this._forEachPrimitive(n,e=>{const t=e;!t.isAnInstance&&t.geometry&&t.geometry.useBoundingInfoFromGeometry?e._updateBoundingInfo():e.refreshBoundingInfo(!0,!0)}),n._babylonTransformNode))}_loadMeshAsync(e,n,s,o){const r=s.primitives;if(!r||!r.length)throw new Error(`${e}: Primitives are missing`);null==r[0].index&&Ts.Assign(r);const i=new Array;this.logOpen(`${e} ${s.name||""}`);const a=n.name||`node${n.index}`;if(1===r.length){const t=s.primitives[0];i.push(this._loadMeshPrimitiveAsync(`${e}/primitives/${t.index}`,a,n,s,t,e=>{n._babylonTransformNode=e,n._primitiveBabylonMeshes=[e]}))}else{this._babylonScene._blockEntityCollection=!!this._assetContainer,n._babylonTransformNode=new t.TransformNode(a,this._babylonScene),n._babylonTransformNode._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,n._primitiveBabylonMeshes=[];for(const t of r)i.push(this._loadMeshPrimitiveAsync(`${e}/primitives/${t.index}`,`${a}_primitive${t.index}`,n,s,t,e=>{e.parent=n._babylonTransformNode,n._primitiveBabylonMeshes.push(e)}))}return o(n._babylonTransformNode),this.logClose(),Promise.all(i).then(()=>n._babylonTransformNode)}_loadMeshPrimitiveAsync(e,n,s,o,r,i){const a=this._extensionsLoadMeshPrimitiveAsync(e,n,s,o,r,i);if(a)return a;this.logOpen(`${e}`);const l=0===this._disableInstancedMesh&&this._parent.createInstances&&null==s.skin&&!o.primitives[0].targets;let u,c;if(l&&r._instanceData)this._babylonScene._blockEntityCollection=!!this._assetContainer,u=r._instanceData.babylonSourceMesh.createInstance(n),u._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,c=r._instanceData.promise;else{const i=new Array;this._babylonScene._blockEntityCollection=!!this._assetContainer;const a=new t.Mesh(n,this._babylonScene);if(a._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,a.sideOrientation=this._babylonScene.useRightHandedSystem?t.Material.CounterClockWiseSideOrientation:t.Material.ClockWiseSideOrientation,this._createMorphTargets(e,s,o,r,a),i.push(this._loadVertexDataAsync(e,r,a).then(t=>b(this,void 0,void 0,function*(){return yield this._loadMorphTargetsAsync(e,r,a,t).then(()=>{this._disposed||(this._babylonScene._blockEntityCollection=!!this._assetContainer,t.applyToMesh(a),t._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1)})}))),!this.parent.skipMaterials){const t=Ms._GetDrawMode(e,r.mode);if(null==r.material){let e=this._defaultBabylonMaterialData[t];e||(e=this._createDefaultMaterial("__GLTFLoader._default",t,this._getDefaultImpl()),this._parent.onMaterialLoadedObservable.notifyObservers(e),this._defaultBabylonMaterialData[t]=e),a.material=e}else{const n=Ts.Get(`${e}/material`,this._gltf.materials,r.material);i.push(this._loadMaterialAsync(`/materials/${n.index}`,n,a,t,e=>{a.material=e}))}}c=Promise.all(i),l&&(r._instanceData={babylonSourceMesh:a,promise:c}),u=a}return Ms.AddPointerMetadata(u,e),this._parent.onMeshLoadedObservable.notifyObservers(u),i(u),this.logClose(),c.then(()=>u)}_loadVertexDataAsync(e,n,s){const o=this._extensionsLoadVertexDataAsync(e,n,s);if(o)return o;const r=n.attributes;if(!r)throw new Error(`${e}: Attributes are missing`);const i=new Array,a=new t.Geometry(s.name,this._babylonScene);if(null==n.indices)s.isUnIndexed=!0;else{const t=Ts.Get(`${e}/indices`,this._gltf.accessors,n.indices);i.push(this._loadIndicesAccessorAsync(`/accessors/${t.index}`,t).then(e=>{a.setIndices(e)}))}const l=(n,o,l)=>{if(null==r[n])return;s._delayInfo=s._delayInfo||[],-1===s._delayInfo.indexOf(o)&&s._delayInfo.push(o);const u=Ts.Get(`${e}/attributes/${n}`,this._gltf.accessors,r[n]);i.push(this._loadVertexAccessorAsync(`/accessors/${u.index}`,u,o).then(e=>{if(e.getKind()===t.VertexBuffer.PositionKind&&!this.parent.alwaysComputeBoundingBox&&!s.skeleton){const e=As(u);e&&(a._boundingInfo=e,a.useBoundingInfoFromGeometry=!0)}a.setVerticesBuffer(e,u.count)})),o==t.VertexBuffer.MatricesIndicesExtraKind&&(s.numBoneInfluencers=8),l&&l(u)};return l("POSITION",t.VertexBuffer.PositionKind),l("NORMAL",t.VertexBuffer.NormalKind),l("TANGENT",t.VertexBuffer.TangentKind),l("TEXCOORD_0",t.VertexBuffer.UVKind),l("TEXCOORD_1",t.VertexBuffer.UV2Kind),l("TEXCOORD_2",t.VertexBuffer.UV3Kind),l("TEXCOORD_3",t.VertexBuffer.UV4Kind),l("TEXCOORD_4",t.VertexBuffer.UV5Kind),l("TEXCOORD_5",t.VertexBuffer.UV6Kind),l("JOINTS_0",t.VertexBuffer.MatricesIndicesKind),l("WEIGHTS_0",t.VertexBuffer.MatricesWeightsKind),l("JOINTS_1",t.VertexBuffer.MatricesIndicesExtraKind),l("WEIGHTS_1",t.VertexBuffer.MatricesWeightsExtraKind),l("COLOR_0",t.VertexBuffer.ColorKind,e=>{"VEC4"===e.type&&(s.hasVertexAlpha=!0)}),Promise.all(i).then(()=>a)}_createMorphTargets(e,n,s,o,r){if(!o.targets||!this._parent.loadMorphTargets)return;if(null==n._numMorphTargets)n._numMorphTargets=o.targets.length;else if(o.targets.length!==n._numMorphTargets)throw new Error(`${e}: Primitives do not have the same number of targets`);const i=s.extras?s.extras.targetNames:null;this._babylonScene._blockEntityCollection=!!this._assetContainer,r.morphTargetManager=new t.MorphTargetManager(this._babylonScene),r.morphTargetManager._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,r.morphTargetManager.areUpdatesFrozen=!0;for(let e=0;e<o.targets.length;e++){const o=n.weights?n.weights[e]:s.weights?s.weights[e]:0,a=i?i[e]:`morphTarget${e}`;r.morphTargetManager.addTarget(new t.MorphTarget(a,o,r.getScene()))}}_loadMorphTargetsAsync(e,n,s,o){if(!n.targets||!this._parent.loadMorphTargets)return Promise.resolve();const r=new Array,i=s.morphTargetManager;for(let t=0;t<i.numTargets;t++){const s=i.getTarget(t);r.push(this._loadMorphTargetVertexDataAsync(`${e}/targets/${t}`,o,n.targets[t],s))}return Promise.all(r).then(()=>{i.areUpdatesFrozen=!1,this._parent.useMaxMorphTargetInfluencers&&(i.isUsingTextureForTargets||i.numTargets<=t.MorphTargetManager.MaxActiveMorphTargetsInVertexAttributeMode)&&(i.optimizeInfluencers=!1,i.numMaxInfluencers=i.numTargets)})}_loadMorphTargetVertexDataAsync(e,n,s,o){return b(this,void 0,void 0,function*(){const r=new Array,i=(t,o,i)=>{if(null==s[t])return;const a=n.getVertexBuffer(o);if(!a)return;const l=Ts.Get(`${e}/${t}`,this._gltf.accessors,s[t]);r.push(this._loadFloatAccessorAsync(`/accessors/${l.index}`,l).then(e=>{i(a,e)}))};return i("POSITION",t.VertexBuffer.PositionKind,(e,t)=>{const n=new Float32Array(t.length);e.forEach(t.length,(e,s)=>{n[s]=t[s]+e}),o.setPositions(n)}),i("NORMAL",t.VertexBuffer.NormalKind,(e,t)=>{const n=new Float32Array(t.length);e.forEach(n.length,(e,s)=>{n[s]=t[s]+e}),o.setNormals(n)}),i("TANGENT",t.VertexBuffer.TangentKind,(e,t)=>{const n=new Float32Array(t.length/3*4);let s=0;e.forEach(t.length/3*4,(e,o)=>{(o+1)%4!=0&&(n[s]=t[s]+e,s++)}),o.setTangents(n)}),i("TEXCOORD_0",t.VertexBuffer.UVKind,(e,t)=>{const n=new Float32Array(t.length);e.forEach(t.length,(e,s)=>{n[s]=t[s]+e}),o.setUVs(n)}),i("TEXCOORD_1",t.VertexBuffer.UV2Kind,(e,t)=>{const n=new Float32Array(t.length);e.forEach(t.length,(e,s)=>{n[s]=t[s]+e}),o.setUV2s(n)}),i("COLOR_0",t.VertexBuffer.ColorKind,(t,n)=>{let s=null;const r=t.getSize();if(3===r){s=new Float32Array(n.length/3*4),t.forEach(n.length,(e,t)=>{const o=Math.floor(t/3),r=t%3;s[4*o+r]=n[3*o+r]+e});for(let e=0;e<n.length/3;++e)s[4*e+3]=1}else{if(4!==r)throw new Error(`${e}: Invalid number of components (${r}) for COLOR_0 attribute`);s=new Float32Array(n.length),t.forEach(n.length,(e,t)=>{s[t]=n[t]+e})}o.setColors(s)}),yield Promise.all(r).then(()=>{})})}static _LoadTransform(e,n){if(null!=e.skin)return;let s=t.Vector3.Zero(),o=t.Quaternion.Identity(),r=t.Vector3.One();e.matrix?t.Matrix.FromArray(e.matrix).decompose(r,o,s):(e.translation&&(s=t.Vector3.FromArray(e.translation)),e.rotation&&(o=t.Quaternion.FromArray(e.rotation)),e.scale&&(r=t.Vector3.FromArray(e.scale))),n.position=s,n.rotationQuaternion=o,n.scaling=r}_loadSkinAsync(e,n,s,o){if(!this._parent.loadSkins)return Promise.resolve();const r=this._extensionsLoadSkinAsync(e,n,s);if(r)return r;if(s._data)return o(s._data.babylonSkeleton),s._data.promise;const i=`skeleton${s.index}`;this._babylonScene._blockEntityCollection=!!this._assetContainer;const a=new t.Skeleton(s.name||i,i,this._babylonScene);a._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,this._loadBones(e,s,a);const l=this._loadSkinInverseBindMatricesDataAsync(e,s).then(e=>{this._updateBoneMatrices(a,e)});return s._data={babylonSkeleton:a,promise:l},o(a),l}_loadBones(e,n,s){if(null==n.skeleton||this._parent.alwaysComputeSkeletonRootNode){const s=this._findSkeletonRootNode(`${e}/joints`,n.joints);if(s)if(void 0===n.skeleton)n.skeleton=s.index;else{const o=(e,t)=>{for(;t.parent;t=t.parent)if(t.parent===e)return!0;return!1},r=Ts.Get(`${e}/skeleton`,this._gltf.nodes,n.skeleton);r===s||o(r,s)||(t.Logger.Warn(`${e}/skeleton: Overriding with nearest common ancestor as skeleton node is not a common root`),n.skeleton=s.index)}else t.Logger.Warn(`${e}: Failed to find common root`)}const o={};for(const t of n.joints){const r=Ts.Get(`${e}/joints/${t}`,this._gltf.nodes,t);this._loadBone(r,n,s,o)}}_findSkeletonRootNode(e,t){if(0===t.length)return null;const n={};for(const s of t){const t=[];let o=Ts.Get(`${e}/${s}`,this._gltf.nodes,s);for(;-1!==o.index;)t.unshift(o),o=o.parent;n[s]=t}let s=null;for(let e=0;;++e){let o=n[t[0]];if(e>=o.length)return s;const r=o[e];for(let i=1;i<t.length;++i)if(o=n[t[i]],e>=o.length||r!==o[e])return s;s=r}}_loadBone(e,n,s,o){e._isJoint=!0;let r=o[e.index];if(r)return r;let i=null;e.index!==n.skeleton&&(e.parent&&-1!==e.parent.index?i=this._loadBone(e.parent,n,s,o):void 0!==n.skeleton&&t.Logger.Warn(`/skins/${n.index}/skeleton: Skeleton node is not a common root`));const a=n.joints.indexOf(e.index);return r=new t.Bone(e.name||`joint${e.index}`,s,i,this._getNodeMatrix(e),null,null,a),o[e.index]=r,this._postSceneLoadActions.push(()=>{r.linkTransformNode(e._babylonTransformNode)}),r}_loadSkinInverseBindMatricesDataAsync(e,t){if(null==t.inverseBindMatrices)return Promise.resolve(null);const n=Ts.Get(`${e}/inverseBindMatrices`,this._gltf.accessors,t.inverseBindMatrices);return this._loadFloatAccessorAsync(`/accessors/${n.index}`,n)}_updateBoneMatrices(e,n){for(const s of e.bones){const e=t.Matrix.Identity(),o=s._index;n&&-1!==o&&(t.Matrix.FromArrayToRef(n,16*o,e),e.invertToRef(e));const r=s.getParent();r&&e.multiplyToRef(r.getAbsoluteInverseBindMatrix(),e),s.updateMatrix(e,!1,!1),s._updateAbsoluteBindMatrices(void 0,!1)}}_getNodeMatrix(e){return e.matrix?t.Matrix.FromArray(e.matrix):t.Matrix.Compose(e.scale?t.Vector3.FromArray(e.scale):t.Vector3.One(),e.rotation?t.Quaternion.FromArray(e.rotation):t.Quaternion.Identity(),e.translation?t.Vector3.FromArray(e.translation):t.Vector3.Zero())}loadCameraAsync(e,n,s=()=>{}){const o=this._extensionsLoadCameraAsync(e,n,s);if(o)return o;const r=new Array;this.logOpen(`${e} ${n.name||""}`),this._babylonScene._blockEntityCollection=!!this._assetContainer;const i=new t.FreeCamera(n.name||`camera${n.index}`,t.Vector3.Zero(),this._babylonScene,!1);switch(i._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,n._babylonCamera=i,i.setTarget(new t.Vector3(0,0,-1)),n.type){case"perspective":{const t=n.perspective;if(!t)throw new Error(`${e}: Camera perspective properties are missing`);i.fov=t.yfov,i.minZ=t.znear,i.maxZ=t.zfar||0;break}case"orthographic":if(!n.orthographic)throw new Error(`${e}: Camera orthographic properties are missing`);i.mode=t.Camera.ORTHOGRAPHIC_CAMERA,i.orthoLeft=-n.orthographic.xmag,i.orthoRight=n.orthographic.xmag,i.orthoBottom=-n.orthographic.ymag,i.orthoTop=n.orthographic.ymag,i.minZ=n.orthographic.znear,i.maxZ=n.orthographic.zfar;break;default:throw new Error(`${e}: Invalid camera type (${n.type})`)}return Ms.AddPointerMetadata(i,e),this._parent.onCameraLoadedObservable.notifyObservers(i),s(i),this.logClose(),Promise.all(r).then(()=>i)}_loadAnimationsAsync(){this._parent._startPerformanceCounter("Load animations");const e=this._gltf.animations;if(!e)return Promise.resolve();const t=new Array;for(let n=0;n<e.length;n++){const s=e[n];t.push(this.loadAnimationAsync(`/animations/${s.index}`,s).then(e=>{0===e.targetedAnimations.length&&e.dispose()}))}return Promise.all(t).then(()=>{this._parent._endPerformanceCounter("Load animations")})}loadAnimationAsync(e,t){this._parent._startPerformanceCounter("Load animation");return this._extensionsLoadAnimationAsync(e,t)||bs.value.then(({AnimationGroup:n})=>{this._babylonScene._blockEntityCollection=!!this._assetContainer;const s=new n(t.name||`animation${t.index}`,this._babylonScene);s._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,t._babylonAnimationGroup=s;const o=new Array;Ts.Assign(t.channels),Ts.Assign(t.samplers);for(const n of t.channels)o.push(this._loadAnimationChannelAsync(`${e}/channels/${n.index}`,e,t,n,(e,t)=>{e.animations=e.animations||[],e.animations.push(t),s.addTargetedAnimation(t,e)}));return this._parent._endPerformanceCounter("Load animation"),Promise.all(o).then(()=>(s.normalize(0),s))})}_loadAnimationChannelAsync(e,t,n,s,o){const r=this._extensionsLoadAnimationChannelAsync(e,t,n,s,o);if(r)return r;if(null==s.target.node)return Promise.resolve();const i=Ts.Get(`${e}/target/node`,this._gltf.nodes,s.target.node),a=s.target.path,l="weights"===a;return l&&!i._numMorphTargets||!l&&!i._babylonTransformNode?Promise.resolve():this._parent.loadNodeAnimations||l||i._isJoint?xs.value.then(()=>{var r,l,u,c;let d;switch(a){case"translation":d=null===(r=gs("/nodes/{}/translation"))||void 0===r?void 0:r.interpolation;break;case"rotation":d=null===(l=gs("/nodes/{}/rotation"))||void 0===l?void 0:l.interpolation;break;case"scale":d=null===(u=gs("/nodes/{}/scale"))||void 0===u?void 0:u.interpolation;break;case"weights":d=null===(c=gs("/nodes/{}/weights"))||void 0===c?void 0:c.interpolation;break;default:throw new Error(`${e}/target/path: Invalid value (${s.target.path})`)}if(!d)throw new Error(`${e}/target/path: Could not find interpolation properties for target path (${s.target.path})`);const h={object:i,info:d};return this._loadAnimationChannelFromTargetInfoAsync(e,t,n,s,h,o)}):Promise.resolve()}_loadAnimationChannelFromTargetInfoAsync(e,t,n,s,o,r){const i=this.parent.targetFps,a=1/i,l=Ts.Get(`${e}/sampler`,n.samplers,s.sampler);return this._loadAnimationSamplerAsync(`${t}/samplers/${s.sampler}`,l).then(e=>{let t=0;const l=o.object,u=o.info;for(const o of u){const u=o.getStride(l),c=e.input,d=e.output,h=new Array(c.length);let m=0;switch(e.interpolation){case"STEP":for(let e=0;e<c.length;e++){const t=o.getValue(l,d,m,1);m+=u,h[e]={frame:c[e]*i,value:t,interpolation:1}}break;case"CUBICSPLINE":for(let e=0;e<c.length;e++){const t=o.getValue(l,d,m,a);m+=u;const n=o.getValue(l,d,m,1);m+=u;const s=o.getValue(l,d,m,a);m+=u,h[e]={frame:c[e]*i,inTangent:t,value:n,outTangent:s}}break;case"LINEAR":for(let e=0;e<c.length;e++){const t=o.getValue(l,d,m,1);m+=u,h[e]={frame:c[e]*i,value:t}}}if(m>0){const e=`${n.name||`animation${n.index}`}_channel${s.index}_${t}`,a=o.buildAnimations(l,e,i,h);for(const e of a)t++,r(e.babylonAnimatable,e.babylonAnimation)}}})}_loadAnimationSamplerAsync(e,t){if(t._data)return t._data;const n=t.interpolation||"LINEAR";switch(n){case"STEP":case"LINEAR":case"CUBICSPLINE":break;default:throw new Error(`${e}/interpolation: Invalid value (${t.interpolation})`)}const s=Ts.Get(`${e}/input`,this._gltf.accessors,t.input),o=Ts.Get(`${e}/output`,this._gltf.accessors,t.output);return t._data=Promise.all([this._loadFloatAccessorAsync(`/accessors/${s.index}`,s),this._loadFloatAccessorAsync(`/accessors/${o.index}`,o)]).then(([e,t])=>({input:e,interpolation:n,output:t})),t._data}loadBufferAsync(e,t,n,s){const o=this._extensionsLoadBufferAsync(e,t,n,s);if(o)return o;if(!t._data)if(t.uri)t._data=this.loadUriAsync(`${e}/uri`,t,t.uri);else{if(!this._bin)throw new 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,s)}catch(t){throw new Error(`${e}: ${t.message}`,{cause:t})}})}loadBufferViewAsync(e,t){const n=this._extensionsLoadBufferViewAsync(e,t);if(n)return n;if(t._data)return t._data;const s=Ts.Get(`${e}/buffer`,this._gltf.buffers,t.buffer);return t._data=this.loadBufferAsync(`/buffers/${s.index}`,s,t.byteOffset||0,t.byteLength),t._data}_loadAccessorAsync(e,n,s){if(n._data)return n._data;const o=Ms._GetNumComponents(e,n.type),r=o*t.VertexBufferGetTypeByteLength(n.componentType),i=o*n.count;if(null==n.bufferView)n._data=Promise.resolve(new s(i));else{const a=Ts.Get(`${e}/bufferView`,this._gltf.bufferViews,n.bufferView);n._data=this.loadBufferViewAsync(`/bufferViews/${a.index}`,a).then(l=>{if(5126!==n.componentType||n.normalized||a.byteStride&&a.byteStride!==r){const e=new s(i);return t.VertexBufferForEach(l,n.byteOffset||0,a.byteStride||r,o,n.componentType,e.length,n.normalized||!1,(t,n)=>{e[n]=t}),e}return Ms._GetTypedArray(e,n.componentType,l,n.byteOffset,i)})}if(n.sparse){const i=n.sparse;n._data=n._data.then(a=>{const l=a,u=Ts.Get(`${e}/sparse/indices/bufferView`,this._gltf.bufferViews,i.indices.bufferView),c=Ts.Get(`${e}/sparse/values/bufferView`,this._gltf.bufferViews,i.values.bufferView);return Promise.all([this.loadBufferViewAsync(`/bufferViews/${u.index}`,u),this.loadBufferViewAsync(`/bufferViews/${c.index}`,c)]).then(([a,u])=>{const c=Ms._GetTypedArray(`${e}/sparse/indices`,i.indices.componentType,a,i.indices.byteOffset,i.count),d=o*i.count;let h;if(5126!==n.componentType||n.normalized){const a=Ms._GetTypedArray(`${e}/sparse/values`,n.componentType,u,i.values.byteOffset,d);h=new s(d),t.VertexBufferForEach(a,0,r,o,n.componentType,h.length,n.normalized||!1,(e,t)=>{h[t]=e})}else h=Ms._GetTypedArray(`${e}/sparse/values`,n.componentType,u,i.values.byteOffset,d);let m=0;for(let e=0;e<c.length;e++){let t=c[e]*o;for(let e=0;e<o;e++)l[t++]=h[m++]}return l})})}return n._data}_loadFloatAccessorAsync(e,t){return this._loadAccessorAsync(e,t,Float32Array)}_loadIndicesAccessorAsync(e,t){if("SCALAR"!==t.type)throw new Error(`${e}/type: Invalid value ${t.type}`);if(5121!==t.componentType&&5123!==t.componentType&&5125!==t.componentType)throw new Error(`${e}/componentType: Invalid value ${t.componentType}`);if(t._data)return t._data;if(t.sparse){const n=Ms._GetTypedArrayConstructor(`${e}/componentType`,t.componentType);t._data=this._loadAccessorAsync(e,t,n)}else{const n=Ts.Get(`${e}/bufferView`,this._gltf.bufferViews,t.bufferView);t._data=this.loadBufferViewAsync(`/bufferViews/${n.index}`,n).then(n=>Ms._GetTypedArray(e,t.componentType,n,t.byteOffset,t.count))}return t._data}_loadVertexBufferViewAsync(e){if(e._babylonBuffer)return e._babylonBuffer;const n=this._babylonScene.getEngine();return e._babylonBuffer=this.loadBufferViewAsync(`/bufferViews/${e.index}`,e).then(e=>new t.Buffer(n,e,!1)),e._babylonBuffer}_loadVertexAccessorAsync(e,n,s){var o;if(null===(o=n._babylonVertexBuffer)||void 0===o?void 0:o[s])return n._babylonVertexBuffer[s];n._babylonVertexBuffer||(n._babylonVertexBuffer={});const r=this._babylonScene.getEngine();if(n.sparse||null==n.bufferView)n._babylonVertexBuffer[s]=this._loadFloatAccessorAsync(e,n).then(e=>new t.VertexBuffer(r,e,s,!1));else{const o=Ts.Get(`${e}/bufferView`,this._gltf.bufferViews,n.bufferView);n._babylonVertexBuffer[s]=this._loadVertexBufferViewAsync(o).then(i=>{const a=Ms._GetNumComponents(e,n.type);return new t.VertexBuffer(r,i,s,!1,void 0,o.byteStride,void 0,n.byteOffset,a,n.componentType,n.normalized,!0,void 0,!0)})}return n._babylonVertexBuffer[s]}_loadMaterialMetallicRoughnessPropertiesAsync(e,n,s){const o=new Array,r=this._getOrCreateMaterialAdapter(s);return n&&(n.baseColorFactor?(r.baseColor=t.Color3.FromArray(n.baseColorFactor),r.geometryOpacity=n.baseColorFactor[3]):r.baseColor=t.Color3.White(),r.baseMetalness=null==n.metallicFactor?1:n.metallicFactor,r.specularRoughness=null==n.roughnessFactor?1:n.roughnessFactor,n.baseColorTexture&&o.push(this.loadTextureInfoAsync(`${e}/baseColorTexture`,n.baseColorTexture,e=>{e.name=`${s.name} (Base Color)`,r.baseColorTexture=e})),n.metallicRoughnessTexture&&(n.metallicRoughnessTexture.nonColorData=!0,o.push(this.loadTextureInfoAsync(`${e}/metallicRoughnessTexture`,n.metallicRoughnessTexture,e=>{e.name=`${s.name} (Metallic Roughness)`,r.baseMetalnessTexture=e,r.specularRoughnessTexture=e})),r.useRoughnessFromMetallicTextureGreen=!0,r.useMetallicFromMetallicTextureBlue=!0)),Promise.all(o).then(()=>{})}_loadMaterialAsync(e,t,n,s,o=()=>{}){const r=this._extensionsLoadMaterialAsync(e,t,n,s,o);if(r)return r;t._data=t._data||{};let i=t._data[s];if(!i){this.logOpen(`${e} ${t.name||""}`);const n=this.createMaterial(e,t,s);i={babylonMaterial:n,babylonMeshes:[],promise:this.loadMaterialPropertiesAsync(e,t,n)},t._data[s]=i,Ms.AddPointerMetadata(n,e),this._parent.onMaterialLoadedObservable.notifyObservers(n),this.logClose()}return n&&(i.babylonMeshes.push(n),n.onDisposeObservable.addOnce(()=>{const e=i.babylonMeshes.indexOf(n);-1!==e&&i.babylonMeshes.splice(e,1)})),o(i.babylonMaterial),i.promise.then(()=>i.babylonMaterial)}_selectImplForGltfMaterial(e){var t;if(this.parent.useOpenPBR||(null===(t=e.extensions)||void 0===t?void 0:t.KHR_materials_openpbr)){const e=this._pbrMaterialImpls.get("openpbr");if(e)return e}const n=this._pbrMaterialImpls.get("pbr");if(n)return n;throw new Error("No PBR material implementation loaded")}_getDefaultImpl(){var e;if(this.parent.useOpenPBR){const e=this._pbrMaterialImpls.get("openpbr");if(e)return e}const t=null!==(e=this._pbrMaterialImpls.get("pbr"))&&void 0!==e?e:this._pbrMaterialImpls.values().next().value;if(t)return t;throw new Error("No PBR material implementation loaded")}_createDefaultMaterial(e,t,n){this._babylonScene._blockEntityCollection=!!this._assetContainer;const s=new n.materialClass(e,this._babylonScene);s._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,s.fillMode=t,s.transparencyMode=n.materialClass.MATERIAL_OPAQUE;const o=this._getOrCreateMaterialAdapter(s);return o.transparencyAsAlphaCoverage=this._parent.transparencyAsCoverage,o.baseMetalness=1,o.specularRoughness=1,s}createMaterial(e,t,n){const s=this._extensionsCreateMaterial(e,t,n);if(s)return s;const o=t.name||`material${t.index}`;return this._createDefaultMaterial(o,n,this._selectImplForGltfMaterial(t))}loadMaterialPropertiesAsync(e,t,n){const s=this._extensionsLoadMaterialPropertiesAsync(e,t,n);if(s)return s;const o=new Array;return o.push(this.loadMaterialBasePropertiesAsync(e,t,n)),t.pbrMetallicRoughness&&o.push(this._loadMaterialMetallicRoughnessPropertiesAsync(`${e}/pbrMetallicRoughness`,t.pbrMetallicRoughness,n)),this.loadMaterialAlphaProperties(e,t,n),Promise.all(o).then(()=>{})}loadMaterialBasePropertiesAsync(e,n,s){const o=new Array,r=this._getOrCreateMaterialAdapter(s);let i;r.emissionColor=n.emissiveFactor?t.Color3.FromArray(n.emissiveFactor):new t.Color3(0,0,0),n.doubleSided&&(r.backFaceCulling=!1,r.twoSidedLighting=!0),n.normalTexture&&(n.normalTexture.nonColorData=!0,o.push(this.loadTextureInfoAsync(`${e}/normalTexture`,n.normalTexture,e=>{var t;e.name=`${s.name} (Normal)`,r.geometryNormalTexture=e,null!=(null===(t=n.normalTexture)||void 0===t?void 0:t.scale)&&(e.level=n.normalTexture.scale)})),r.setNormalMapInversions(!this._babylonScene.useRightHandedSystem,this._babylonScene.useRightHandedSystem));let a,l=1;return n.occlusionTexture&&(n.occlusionTexture.nonColorData=!0,o.push(this.loadTextureInfoAsync(`${e}/occlusionTexture`,n.occlusionTexture,e=>{e.name=`${s.name} (Occlusion)`,i=e})),null!=n.occlusionTexture.strength&&(l=n.occlusionTexture.strength)),n.emissiveTexture&&o.push(this.loadTextureInfoAsync(`${e}/emissiveTexture`,n.emissiveTexture,e=>{e.name=`${s.name} (Emissive)`,a=e})),Promise.all(o).then(()=>{i&&(r.ambientOcclusionTexture=i,r.ambientOcclusionTextureStrength=l),a&&(r.emissionColorTexture=a)})}loadMaterialAlphaProperties(e,n,s){if(0===this._pbrMaterialImpls.size)throw new Error(`${e}: Material type not supported`);const o=this._getOrCreateMaterialAdapter(s),r=o.baseColorTexture;switch(n.alphaMode||"OPAQUE"){case"OPAQUE":s.transparencyMode=t.Material.MATERIAL_OPAQUE,s.alpha=1;break;case"MASK":s.transparencyMode=t.Material.MATERIAL_ALPHATEST,o.alphaCutOff=null==n.alphaCutoff?.5:n.alphaCutoff,r&&(r.hasAlpha=!0,o.useAlphaFromBaseColorTexture=!0);break;case"BLEND":s.transparencyMode=t.Material.MATERIAL_ALPHABLEND,r&&(r.hasAlpha=!0,o.useAlphaFromBaseColorTexture=!0);break;default:throw new Error(`${e}/alphaMode: Invalid value (${n.alphaMode})`)}}loadTextureInfoAsync(e,t,n=()=>{}){const s=this._extensionsLoadTextureInfoAsync(e,t,n);if(s)return s;if(this.logOpen(`${e}`),t.texCoord>=6)throw new Error(`${e}/texCoord: Invalid value (${t.texCoord})`);const o=Ts.Get(`${e}/index`,this._gltf.textures,t.index);o._textureInfo=t;const r=this._loadTextureAsync(`/textures/${t.index}`,o,s=>{s.coordinatesIndex=t.texCoord||0,Ms.AddPointerMetadata(s,e),this._parent.onTextureLoadedObservable.notifyObservers(s),n(s)});return this.logClose(),r}_loadTextureAsync(e,t,n=()=>{}){const s=this._extensionsLoadTextureAsync(e,t,n);if(s)return s;this.logOpen(`${e} ${t.name||""}`);const o=null==t.sampler?Ms.DefaultSampler:Ts.Get(`${e}/sampler`,this._gltf.samplers,t.sampler),r=Ts.Get(`${e}/source`,this._gltf.images,t.source),i=this._createTextureAsync(e,o,r,n,void 0,!t._textureInfo.nonColorData);return this.logClose(),i}_createTextureAsync(e,n,s,o=()=>{},r,i){var a,l;const u=this._loadSampler(`/samplers/${n.index}`,n),c=new Array,d=new t.Deferred;this._babylonScene._blockEntityCollection=!!this._assetContainer;const h={noMipmap:u.noMipMaps,invertY:!1,samplingMode:u.samplingMode,onLoad:()=>{this._disposed||d.resolve()},onError:(t,n)=>{this._disposed||d.reject(new Error(`${e}: ${n&&n.message?n.message:t||"Failed to load texture"}`))},mimeType:null!==(a=s.mimeType)&&void 0!==a?a:t.GetMimeType(null!==(l=s.uri)&&void 0!==l?l:""),loaderOptions:r,useSRGBBuffer:!!i&&this._parent.useSRGBBuffers},m=new t.Texture(null,this._babylonScene,h);m._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,c.push(d.promise);const f=s.uri&&!t.IsBase64DataUrl(s.uri)?s.uri:void 0,p=null!=f?f:`${this._fileName}#image${s.index}`;if(c.push(this.loadImageAsync(`/images/${s.index}`,s).then(e=>{const t=`data:${this._uniqueRootUrl}${p}`;m.updateURL(t,e);const n=m.getInternalTexture();n&&(n.label=s.name)})),m.wrapU=u.wrapU,m.wrapV=u.wrapV,o(m),this._parent.useGltfTextureNames){const e=s.name||f||`image${s.index}`;m.name=e}return Promise.all(c).then(()=>m)}_loadSampler(e,t){return t._data||(t._data={noMipMaps:9728===t.minFilter||9729===t.minFilter,samplingMode:Ms._GetTextureSamplingMode(e,t),wrapU:Ms._GetTextureWrapMode(`${e}/wrapS`,t.wrapS),wrapV:Ms._GetTextureWrapMode(`${e}/wrapT`,t.wrapT)}),t._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{const n=Ts.Get(`${e}/bufferView`,this._gltf.bufferViews,t.bufferView);t._data=this.loadBufferViewAsync(`/bufferViews/${n.index}`,n)}this.logClose()}return t._data}loadUriAsync(e,n,s){const o=this._extensionsLoadUriAsync(e,n,s);if(o)return o;if(!Ms._ValidateUri(s))throw new Error(`${e}: '${s}' is invalid`);if(t.IsBase64DataUrl(s)){const n=new Uint8Array(t.DecodeBase64UrlToBinary(s));return this.log(`${e}: Decoded ${s.substring(0,64)}... (${n.length} bytes)`),Promise.resolve(n)}return this.log(`${e}: Loading ${s}`),this._parent.preprocessUrlAsync(this._rootUrl+s).then(n=>new Promise((o,r)=>{this._parent._loadFile(this._babylonScene,n,t=>{this._disposed||(this.log(`${e}: Loaded ${s} (${t.byteLength} bytes)`),o(new Uint8Array(t)))},!0,n=>{r(new t.LoadFileError(`${e}: Failed to load '${s}'${n?": "+n.status+" "+n.statusText:""}`,n))})}))}static AddPointerMetadata(e,t){e.metadata=e.metadata||{};const n=e._internalMetadata=e._internalMetadata||{},s=n.gltf=n.gltf||{};(s.pointers=s.pointers||[]).push(t)}static _GetTextureWrapMode(e,n){switch(n=null==n?10497:n){case 33071:return t.Texture.CLAMP_ADDRESSMODE;case 33648:return t.Texture.MIRROR_ADDRESSMODE;case 10497:return t.Texture.WRAP_ADDRESSMODE;default:return t.Logger.Warn(`${e}: Invalid value (${n})`),t.Texture.WRAP_ADDRESSMODE}}static _GetTextureSamplingMode(e,n){const s=null==n.magFilter?9729:n.magFilter,o=null==n.minFilter?9987:n.minFilter;if(9729===s)switch(o){case 9728:return t.Texture.LINEAR_NEAREST;case 9729:return t.Texture.LINEAR_LINEAR;case 9984:return t.Texture.LINEAR_NEAREST_MIPNEAREST;case 9985:return t.Texture.LINEAR_LINEAR_MIPNEAREST;case 9986:return t.Texture.LINEAR_NEAREST_MIPLINEAR;case 9987:return t.Texture.LINEAR_LINEAR_MIPLINEAR;default:return t.Logger.Warn(`${e}/minFilter: Invalid value (${o})`),t.Texture.LINEAR_LINEAR_MIPLINEAR}else switch(9728!==s&&t.Logger.Warn(`${e}/magFilter: Invalid value (${s})`),o){case 9728:return t.Texture.NEAREST_NEAREST;case 9729:return t.Texture.NEAREST_LINEAR;case 9984:return t.Texture.NEAREST_NEAREST_MIPNEAREST;case 9985:return t.Texture.NEAREST_LINEAR_MIPNEAREST;case 9986:return t.Texture.NEAREST_NEAREST_MIPLINEAR;case 9987:return t.Texture.NEAREST_LINEAR_MIPLINEAR;default:return t.Logger.Warn(`${e}/minFilter: Invalid value (${o})`),t.Texture.NEAREST_NEAREST_MIPNEAREST}}static _GetTypedArrayConstructor(e,n){try{return t.GetTypedArrayConstructor(n)}catch(t){throw new Error(`${e}: ${t.message}`,{cause:t})}}static _GetTypedArray(e,n,s,o,r){const i=s.buffer;o=s.byteOffset+(o||0);const a=Ms._GetTypedArrayConstructor(`${e}/componentType`,n),l=t.VertexBufferGetTypeByteLength(n);return o%l!==0?(t.Logger.Warn(`${e}: Copying buffer as byte offset (${o}) is not a multiple of component type byte length (${l})`),new a(i.slice(o,o+r*l),0)):new a(i,o,r)}static _GetNumComponents(e,t){switch(t){case"SCALAR":return 1;case"VEC2":return 2;case"VEC3":return 3;case"VEC4":case"MAT2":return 4;case"MAT3":return 9;case"MAT4":return 16}throw new Error(`${e}: Invalid type (${t})`)}static _ValidateUri(e){return t.Tools.IsBase64(e)||-1===e.indexOf("..")}static _GetDrawMode(e,n){switch(null==n&&(n=4),n){case 0:return t.Material.PointListDrawMode;case 1:return t.Material.LineListDrawMode;case 2:return t.Material.LineLoopDrawMode;case 3:return t.Material.LineStripDrawMode;case 4:return t.Material.TriangleFillMode;case 5:return t.Material.TriangleStripDrawMode;case 6:return t.Material.TriangleFanDrawMode}throw new Error(`${e}: Invalid mesh primitive mode (${n})`)}_compileMaterialsAsync(){this._parent._startPerformanceCounter("Compile materials");const e=new Array;if(this._gltf.materials)for(const t of this._gltf.materials)if(t._data)for(const n in t._data){const s=t._data[n];for(const t of s.babylonMeshes){t.computeWorldMatrix(!0);const n=s.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");const e=new Array,t=this._babylonScene.lights;for(const n of t){const t=n.getShadowGenerator();t&&e.push(t.forceCompilationAsync())}return Promise.all(e).then(()=>{this._parent._endPerformanceCounter("Compile shadow generators")})}_forEachExtensions(e){for(const t of this._extensions)t.enabled&&e(t)}_applyExtensions(e,t,n){for(const s of this._extensions)if(s.enabled){const o=`${s.name}.${t}`,r=e;r._activeLoaderExtensionFunctions=r._activeLoaderExtensionFunctions||{};const i=r._activeLoaderExtensionFunctions;if(!i[o]){i[o]=!0;try{const e=n(s);if(e)return e}finally{delete i[o]}}}return null}_extensionsOnLoading(){this._forEachExtensions(e=>e.onLoading&&e.onLoading())}_extensionsOnReady(){this._forEachExtensions(e=>e.onReady&&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",s=>s.loadNodeAsync&&s.loadNodeAsync(e,t,n))}_extensionsLoadCameraAsync(e,t,n){return this._applyExtensions(t,"loadCamera",s=>s.loadCameraAsync&&s.loadCameraAsync(e,t,n))}_extensionsLoadVertexDataAsync(e,t,n){return this._applyExtensions(t,"loadVertexData",s=>s._loadVertexDataAsync&&s._loadVertexDataAsync(e,t,n))}_extensionsLoadMeshPrimitiveAsync(e,t,n,s,o,r){return this._applyExtensions(o,"loadMeshPrimitive",i=>i._loadMeshPrimitiveAsync&&i._loadMeshPrimitiveAsync(e,t,n,s,o,r))}_extensionsLoadMaterialAsync(e,t,n,s,o){return this._applyExtensions(t,"loadMaterial",r=>r._loadMaterialAsync&&r._loadMaterialAsync(e,t,n,s,o))}_extensionsCreateMaterial(e,t,n){return this._applyExtensions(t,"createMaterial",s=>s.createMaterial&&s.createMaterial(e,t,n))}_extensionsLoadMaterialPropertiesAsync(e,t,n){return this._applyExtensions(t,"loadMaterialProperties",s=>s.loadMaterialPropertiesAsync&&s.loadMaterialPropertiesAsync(e,t,n))}_extensionsLoadTextureInfoAsync(e,t,n){return this._applyExtensions(t,"loadTextureInfo",s=>s.loadTextureInfoAsync&&s.loadTextureInfoAsync(e,t,n))}_extensionsLoadTextureAsync(e,t,n){return this._applyExtensions(t,"loadTexture",s=>s._loadTextureAsync&&s._loadTextureAsync(e,t,n))}_extensionsLoadAnimationAsync(e,t){return this._applyExtensions(t,"loadAnimation",n=>n.loadAnimationAsync&&n.loadAnimationAsync(e,t))}_extensionsLoadAnimationChannelAsync(e,t,n,s,o){return this._applyExtensions(n,"loadAnimationChannel",r=>r._loadAnimationChannelAsync&&r._loadAnimationChannelAsync(e,t,n,s,o))}_extensionsLoadSkinAsync(e,t,n){return this._applyExtensions(n,"loadSkin",s=>s._loadSkinAsync&&s._loadSkinAsync(e,t,n))}_extensionsLoadUriAsync(e,t,n){return this._applyExtensions(t,"loadUri",s=>s._loadUriAsync&&s._loadUriAsync(e,t,n))}_extensionsLoadBufferViewAsync(e,t){return this._applyExtensions(t,"loadBufferView",n=>n.loadBufferViewAsync&&n.loadBufferViewAsync(e,t))}_extensionsLoadBufferAsync(e,t,n,s){return this._applyExtensions(t,"loadBuffer",o=>o.loadBufferAsync&&o.loadBufferAsync(e,t,n,s))}static LoadExtensionAsync(e,t,n,s){if(!t.extensions)return null;const o=t.extensions[n];return o?s(`${e}/extensions/${n}`,o):null}static LoadExtraAsync(e,t,n,s){if(!t.extras)return null;const o=t.extras[n];return o?s(`${e}/extras/${n}`,o):null}isExtensionUsed(e){return!!this._gltf.extensionsUsed&&-1!==this._gltf.extensionsUsed.indexOf(e)}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)}}Ms.DefaultSampler={index:-1};let ws=!1;function Cs(){ws||(ws=!0,mn._CreateGLTF2Loader=e=>new Ms(e))}Cs(),pn();var Rs={__proto__:null,ArrayItem:Ts,GLTFFileLoader:mn,GLTFLoader:Ms,LoadBoundingInfoFromPositionAccessor:As,RegisterGLTF2Loader:Cs};function Ss(e,n,s,o){return t.Vector3.FromArray(n,s).scaleInPlace(o)}function Os(e,n,s,o){return t.Quaternion.FromArray(n,s).scaleInPlace(o)}function Fs(e,t,n,s){const o=new Array(e._numMorphTargets);for(let e=0;e<o.length;e++)o[e]=t[n++]*s;return o}class Es{constructor(e,t,n,s){this.type=e,this.name=t,this.getValue=n,this.getStride=s}_buildAnimation(e,n,s){const o=new t.Animation(e,this.name,n,this.type);return o.setKeys(s,!0),o}}class Is extends Es{buildAnimations(e,t,n,s){const o=[];return o.push({babylonAnimatable:e._babylonTransformNode,babylonAnimation:this._buildAnimation(t,n,s)}),o}}class Ls extends Es{buildAnimations(e,n,s,o){const r=[];if(e._numMorphTargets)for(let i=0;i<e._numMorphTargets;i++){const a=new t.Animation(`${n}_${i}`,this.name,s,this.type);if(a.setKeys(o.map(e=>({frame:e.frame,inTangent:e.inTangent?e.inTangent[i]:void 0,value:e.value[i],outTangent:e.outTangent?e.outTangent[i]:void 0,interpolation:e.interpolation})),!0),e._primitiveBabylonMeshes)for(const t of e._primitiveBabylonMeshes)if(t.morphTargetManager){const e=t.morphTargetManager.getTarget(i),n=a.clone();e.animations.push(n),r.push({babylonAnimatable:e,babylonAnimation:n})}}return r}}ys("/nodes/{}/translation",[new Is(t.Animation.ANIMATIONTYPE_VECTOR3,"position",Ss,()=>3)]),ys("/nodes/{}/rotation",[new Is(t.Animation.ANIMATIONTYPE_QUATERNION,"rotationQuaternion",Os,()=>4)]),ys("/nodes/{}/scale",[new Is(t.Animation.ANIMATIONTYPE_VECTOR3,"scaling",Ss,()=>3)]),ys("/nodes/{}/weights",[new Ls(t.Animation.ANIMATIONTYPE_FLOAT,"influence",Fs,e=>e._numMorphTargets)]);var Ps={__proto__:null,AnimationPropertyInfo:Es,TransformNodeAnimationPropertyInfo:Is,WeightAnimationPropertyInfo:Ls,getQuaternion:Os,getVector3:Ss,getWeights:Fs};class Bs{constructor(e){this._specWorkflow=!1,this._diffuseTransmissionTint=t.Color3.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){const t=this._material.ambientOcclusionTexture;t&&(t.level=e)}get ambientOcclusionTextureStrength(){var e;const t=this._material.ambientOcclusionTexture;return null!==(e=null==t?void 0:t.level)&&void 0!==e?e: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||0!==this._material.transmissionDepth?this._material.transmissionDepth=e:this._material.transmissionDepth=0}get transmissionDepth(){return this._material.transmissionDepth}set transmissionColor(e){e.equals(t.Color3.White())||(this._material.transmissionColor=e)}get transmissionColor(){return this._material.transmissionColor}get refractionBackgroundTexture(){return this._material.backgroundRefractionTexture}set refractionBackgroundTexture(e){this._material.backgroundRefractionTexture=e}configureVolume(){this._material.geometryThinWalled=0}set geometryThinWalled(e){this._material.geometryThinWalled=e?1:0}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)}finalizeAsync(e){return b(this,void 0,void 0,function*(){var n,s,o;if(this._diffuseTransmissionTint&&!this._diffuseTransmissionTint.equals(t.Color3.White())||this._diffuseTransmissionTintTexture)if(this._material.geometryThinWalled)this.subsurfaceColor=this._diffuseTransmissionTint,this.subsurfaceColorTexture=this._diffuseTransmissionTintTexture;else if(yield this.copySurfaceToCoatAsync(e,this.subsurfaceWeight,this.subsurfaceWeightTexture,t.TextureChannel.A,this._diffuseTransmissionTint,this._diffuseTransmissionTintTexture,!0),e._disposed)return;if(this.transmissionWeight>0)if(this._material.geometryThinWalled||0===this._material.transmissionDepth)this._material.transmissionColor=this._material.baseColor,this._material.transmissionColorTexture=this._material.baseColorTexture;else if((!this.baseColor.equals(t.Color3.White())||null!==this.baseColorTexture)&&(yield this.copySurfaceToCoatAsync(e,this.transmissionWeight,this.transmissionWeightTexture,t.TextureChannel.R,this.baseColor,this.baseColorTexture,!1),e._disposed))return;if(this._specWorkflow){const r=yield t.InvertTextureAsync("newRoughnessTexture ("+this._material.name+")",yield t.ExtractChannelAsync("glossiness ("+this._material.name+")",t.CreateTextureWithFactorOperand(this.specularColorTexture,new t.Color4(this.specularColor.r,this.specularColor.g,this.specularColor.b,this.glossiness),t.TextureChannel.A,t.TextureColorSpace.Linear),t.TextureChannel.A,this._material.getScene(),t.TextureColorSpace.Linear,t.ChannelMask.R),this._material.getScene(),t.ChannelMask.R,t.TextureColorSpace.Linear,t.ChannelMask.R);if(e._disposed)return void(null===(n=r.texture)||void 0===n||n.dispose());this.specularRoughnessTexture=r.texture,this.specularRoughness=r.factor?r.factor.r:1;const i=yield t.ExtractMaxChannelAsync("metallicTexture ("+this._material.name+")",t.CreateTextureWithFactorOperand(this.specularColorTexture,this.specularColor.toColor4(),t.TextureChannel.RGBA,t.TextureColorSpace.Linear),this._material.getScene(),!1,t.TextureColorSpace.SRGB,t.ChannelMask.RGB);if(e._disposed)return void(null===(s=i.texture)||void 0===s||s.dispose());this.baseMetalnessTexture=i.texture,this.baseMetalness=i.factor?i.factor.r:1;const a=yield t.LerpTexturesAsync("newBaseColor ("+this._material.name+")",t.CreateTextureWithFactorOperand(this.baseColorTexture,this.baseColor.toColor4(),t.TextureChannel.RGBA,t.TextureColorSpace.Linear),t.CreateTextureWithFactorOperand(this.specularColorTexture,this.specularColor.toColor4(),t.TextureChannel.RGBA,t.TextureColorSpace.Linear),Object.assign(Object.assign({},i),{dispose:void 0,colorSpace:t.TextureColorSpace.Linear}),this._material.getScene(),t.TextureColorSpace.SRGB,t.ChannelMask.RGB);if(e._disposed)return void(null===(o=a.texture)||void 0===o||o.dispose());const l=this.baseColorTexture;null==l||l.dispose(),this.baseColorTexture=a.texture,this.baseColor=a.factor?new t.Color3(a.factor.r,a.factor.g,a.factor.b):t.Color3.White();const u=this.specularColorTexture;null==u||u.dispose(),this.specularColorTexture=null}})}copySurfaceToCoatAsync(e,n,s,o,r,i){return b(this,arguments,void 0,function*(e,n,s,o,r,i,a=!1){var l,u,c,d,h,m,f,p,_;const g=this._material.coatWeight,y=this._material.coatWeightTexture,v=this._material.coatColor.clone(),b=this._material.coatColorTexture,x=this._material.geometryCoatNormalTexture,T=new t.Color4(g,g,g,g),A=new t.Color4(n,n,n,n);this.coatWeightTexture=null,this.coatWeight=1;const M=yield Promise.allSettled([t.LerpTexturesAsync("lerpExistingCoat",t.CreateTextureWithFactorOperand(null,new t.Color4(1,1,1,1)),t.CreateTextureWithFactorOperand(b,v.toColor4(),t.TextureChannel.RGBA,t.TextureColorSpace.SRGB),t.CreateTextureWithFactorOperand(y,T,t.TextureChannel.R),this._material.getScene(),t.TextureColorSpace.SRGB),t.LerpTexturesAsync("lerpSurfaceColor",t.CreateTextureWithFactorOperand(null,new t.Color4(1,1,1,1)),t.CreateTextureWithFactorOperand(i,r.toColor4(),t.TextureChannel.RGBA,t.TextureColorSpace.SRGB),t.CreateTextureWithFactorOperand(s,A,o),this._material.getScene(),t.TextureColorSpace.SRGB)]),w=M.find(e=>"rejected"===e.status);if(w){for(const e of M)"fulfilled"===e.status&&(null===(l=e.value.texture)||void 0===l||l.dispose());throw w.reason}const[C,R]=M.map(e=>e.value);if(e._disposed)return null===(u=C.texture)||void 0===u||u.dispose(),void(null===(c=R.texture)||void 0===c||c.dispose());const S=yield t.MultiplyTexturesAsync("newCoatColor ("+this._material.name+")",C,R,this._material.getScene(),t.TextureColorSpace.SRGB);if(e._disposed)return void(null===(d=S.texture)||void 0===d||d.dispose());S.texture?(this.coatColorTexture=S.texture,this.coatColor=t.Color3.White()):S.factor&&(this.coatColorTexture=null,this.coatColor.fromArray([S.factor.r,S.factor.g,S.factor.b]));const O=yield t.LerpTexturesAsync("newCoatIor ("+this._material.name+")",t.CreateTextureWithFactorOperand(null,new t.Color4(this._material.specularIor,this._material.specularIor,this._material.specularIor,1),t.TextureChannel.R),t.CreateTextureWithFactorOperand(null,new t.Color4(this.coatIor,this.coatIor,this.coatIor,1),t.TextureChannel.R),t.CreateTextureWithFactorOperand(y,T,t.TextureChannel.R),this._material.getScene());if(e._disposed)return void(null===(h=O.texture)||void 0===h||h.dispose());this.coatIor=O.factor?O.factor.r:this.coatIor;const F=yield t.LerpTexturesAsync("newCoatRoughness ("+this._material.name+")",t.CreateTextureWithFactorOperand(this.specularRoughnessTexture,new t.Color4(this.specularRoughness,this.specularRoughness,this.specularRoughness,1),t.TextureChannel.G),t.CreateTextureWithFactorOperand(this.coatRoughnessTexture,new t.Color4(this.coatRoughness,this.coatRoughness,this.coatRoughness,1),t.TextureChannel.G),t.CreateTextureWithFactorOperand(y,T,t.TextureChannel.R),this._material.getScene());if(e._disposed)return void(null===(m=F.texture)||void 0===m||m.dispose());this.coatRoughness=F.factor?F.factor.r:1,this.coatRoughnessTexture=F.texture;const E=yield t.LerpTexturesAsync("newCoatDarkening ("+this._material.name+")",t.CreateTextureWithFactorOperand(null,new t.Color4(0,0,0,1),t.TextureChannel.R),t.CreateTextureWithFactorOperand(null,new t.Color4(this.coatDarkening,this.coatDarkening,this.coatDarkening,1),t.TextureChannel.R),t.CreateTextureWithFactorOperand(y,T,t.TextureChannel.R),this._material.getScene());if(e._disposed)null===(f=E.texture)||void 0===f||f.dispose();else{if(this.coatDarkening=E.factor?E.factor.r:this.coatDarkening,a){const n=yield t.LerpTexturesAsync("newSpecularRoughness ("+this._material.name+")",t.CreateTextureWithFactorOperand(this.specularRoughnessTexture,new t.Color4(this._material.specularRoughness,this._material.specularRoughness,this._material.specularRoughness,1),t.TextureChannel.G),t.CreateTextureWithFactorOperand(null,new t.Color4(1,1,1,1),t.TextureChannel.R),t.CreateTextureWithFactorOperand(s,A,o),this._material.getScene());if(e._disposed)return void(null===(p=n.texture)||void 0===p||p.dispose());this.specularRoughness=n.factor?n.factor.r:1,this.specularRoughnessTexture=n.texture}if(x||this.geometryNormalTexture){const n=yield t.LerpTexturesAsync("newCoatNormal ("+this._material.name+")",t.CreateTextureWithFactorOperand(this.geometryNormalTexture,this.geometryNormalTexture?new t.Color4(1,1,1,1):new t.Color4(.5,.5,1,1),t.TextureChannel.RGBA),t.CreateTextureWithFactorOperand(x,x?new t.Color4(1,1,1,1):new t.Color4(.5,.5,1,1),t.TextureChannel.RGBA),t.CreateTextureWithFactorOperand(y,T,t.TextureChannel.R),this._material.getScene());if(e._disposed)return void(null===(_=n.texture)||void 0===_||_.dispose());n.texture&&(this.geometryCoatNormalTexture=n.texture)}}})}}var Ns={__proto__:null,OpenPBRMaterialLoadingAdapter:Bs};class ks{constructor(e){this._specWorkflow=!1,this._material=e,this._material.enableSpecularAntiAliasing=!0}get material(){return this._material}finalizeAsync(e){return b(this,void 0,void 0,function*(){})}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=t.Constants.MATERIAL_DIFFUSE_MODEL_E_OREN_NAYAR)}get baseDiffuseRoughness(){var e;return null!==(e=this._material.baseDiffuseRoughness)&&void 0!==e?e:0}set baseDiffuseRoughnessTexture(e){this._material.baseDiffuseRoughnessTexture=e}get baseDiffuseRoughnessTexture(){return this._material.baseDiffuseRoughnessTexture}set baseMetalness(e){this._material.metallic=e}get baseMetalness(){var e;return null!==(e=this._material.metallic)&&void 0!==e?e: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=t.Constants.MATERIAL_DIELECTRIC_SPECULAR_MODEL_OPENPBR,this._material.brdf.conductorSpecularModel=t.Constants.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(){var e;return null!==(e=this._material.metallicF0Factor)&&void 0!==e?e: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(){var e;return null!==(e=this._material.roughness)&&void 0!==e?e: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(){var e;return null!==(e=this._material.microSurface)&&void 0!==e?e: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(){var e;return null!==(e=this._material.ambientTextureStrength)&&void 0!==e?e: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!=t.Color3.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(){var e;return null!==(e=this._material.clearCoat.roughness)&&void 0!==e?e: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 t.Color3(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 t.Color3(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)}get 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 0===this._material.subSurface.maximumThickness}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){const n=new t.Vector3(-Math.log(this.transmissionColor.r),-Math.log(this.transmissionColor.g),-Math.log(this.transmissionColor.b));n.scaleInPlace(1/Math.max(this.transmissionDepth,.001));const s=n,o=Math.max(s.x,Math.max(s.y,s.z)),r=o>0?1/o:1;this._material.subSurface.diffusionDistance=new t.Color3(Math.exp(-s.x*r),Math.exp(-s.y*r),Math.exp(-s.z*r))}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(){var e;return null!==(e=this._material.subSurface.scatteringDiffusionProfile)&&void 0!==e?e:t.Color3.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)}}var Ds={__proto__:null,PBRMaterialLoadingAdapter:ks};const Gs="EXT_lights_image_based";let Vs=class{constructor(e){this.name=Gs,this._loader=e,this.enabled=this._loader.isExtensionUsed(Gs)}dispose(){this._loader=null,delete this._lights}onLoading(){const e=this._loader.gltf.extensions;if(e&&e[this.name]){const t=e[this.name];this._lights=t.lights}}loadSceneAsync(e,t){return Ms.LoadExtensionAsync(e,t,this.name,(n,s)=>b(this,void 0,void 0,function*(){this._loader._allMaterialsDirtyRequired=!0;const o=new Array;o.push(this._loader.loadSceneAsync(e,t)),this._loader.logOpen(`${n}`);const r=Ts.Get(`${n}/light`,this._lights,s.light);return o.push(this._loadLightAsync(`/extensions/${this.name}/lights/${s.light}`,r).then(e=>{this._loader.babylonScene.environmentTexture=e})),this._loader.logClose(),yield Promise.all(o).then(()=>{})}))}_loadLightAsync(e,n){if(!n._loaded){const s=new Array;this._loader.logOpen(`${e}`);const o=new Array(n.specularImages.length);for(let t=0;t<n.specularImages.length;t++){const r=n.specularImages[t];o[t]=new Array(r.length);for(let n=0;n<r.length;n++){const i=`${e}/specularImages/${t}/${n}`;this._loader.logOpen(`${i}`);const a=r[n],l=Ts.Get(i,this._loader.gltf.images,a);s.push(this._loader.loadImageAsync(`/images/${a}`,l).then(e=>{o[t][n]=e})),this._loader.logClose()}}this._loader.logClose(),n._loaded=Promise.all(s).then(()=>b(this,void 0,void 0,function*(){const s=new t.RawCubeTexture(this._loader.babylonScene,null,n.specularImageSize);if(s.name=n.name||"environment",n._babylonTexture=s,null!=n.intensity&&(s.level=n.intensity),n.rotation){let e=t.Quaternion.FromArray(n.rotation);this._loader.babylonScene.useRightHandedSystem||(e=t.Quaternion.Inverse(e)),t.Matrix.FromQuaternionToRef(e,s.getReflectionTextureMatrix())}if(!n.irradianceCoefficients)throw new Error(`${e}: Irradiance coefficients are missing`);const r=t.SphericalHarmonics.FromArray(n.irradianceCoefficients);r.scaleInPlace(n.intensity),r.convertIrradianceToLambertianRadiance();const i=t.SphericalPolynomial.FromHarmonics(r),a=(o.length-1)/Math.log2(n.specularImageSize);return yield s.updateRGBDAsync(o,i,a)}))}return n._loaded.then(()=>n._babylonTexture)}},Hs=!1;function Ks(){Hs||(Hs=!0,ns(Gs),ts(Gs,!0,e=>new Vs(e)))}Ks();var $s={__proto__:null,EXT_lights_image_based:Vs,RegisterEXT_lights_image_based:Ks};const Us="EXT_mesh_gpu_instancing";let qs=class{constructor(e){this.name=Us,this._loader=e,this.enabled=this._loader.isExtensionUsed(Us)}dispose(){this._loader=null}loadNodeAsync(e,n,s){return Ms.LoadExtensionAsync(e,n,this.name,(e,o)=>b(this,void 0,void 0,function*(){this._loader._disableInstancedMesh++;const r=this._loader.loadNodeAsync(`/nodes/${n.index}`,n,s);if(this._loader._disableInstancedMesh--,!n._primitiveBabylonMeshes)return yield r;const i=new Array;let a=0;const l=t=>{if(null==o.attributes[t])return void i.push(Promise.resolve(null));const n=Ts.Get(`${e}/attributes/${t}`,this._loader.gltf.accessors,o.attributes[t]);if(i.push(this._loader._loadFloatAccessorAsync(`/accessors/${n.bufferView}`,n)),0===a)a=n.count;else if(a!==n.count)throw new Error(`${e}/attributes: Instance buffer accessors do not have the same count.`)};return l("TRANSLATION"),l("ROTATION"),l("SCALE"),l("_COLOR_0"),yield r.then(e=>b(this,void 0,void 0,function*(){const[s,o,r,l]=yield Promise.all(i),u=new Float32Array(16*a);t.TmpVectors.Vector3[0].copyFromFloats(0,0,0),t.TmpVectors.Quaternion[0].copyFromFloats(0,0,0,1),t.TmpVectors.Vector3[1].copyFromFloats(1,1,1);for(let e=0;e<a;++e)s&&t.Vector3.FromArrayToRef(s,3*e,t.TmpVectors.Vector3[0]),o&&t.Quaternion.FromArrayToRef(o,4*e,t.TmpVectors.Quaternion[0]),r&&t.Vector3.FromArrayToRef(r,3*e,t.TmpVectors.Vector3[1]),t.Matrix.ComposeToRef(t.TmpVectors.Vector3[1],t.TmpVectors.Quaternion[0],t.TmpVectors.Vector3[0],t.TmpVectors.Matrix[0]),t.TmpVectors.Matrix[0].copyToArray(u,16*e);for(const e of n._primitiveBabylonMeshes)e.thinInstanceSetBuffer("matrix",u,16,!0),l&&(l.length===3*a?e.thinInstanceSetBuffer("color",l,3,!0):l.length===4*a?e.thinInstanceSetBuffer("color",l,4,!0):t.Logger.Warn("Unexpected size of _COLOR_0 attribute for mesh "+e.name));return e}))}))}},Ws=!1;function zs(){Ws||(Ws=!0,ns(Us),ts(Us,!0,e=>new qs(e)))}zs();var js={__proto__:null,EXT_mesh_gpu_instancing:qs,RegisterEXT_mesh_gpu_instancing:zs};const Xs="EXT_meshopt_compression";let Ys=class{constructor(e){this.name=Xs,this.enabled=e.isExtensionUsed(Xs),this._loader=e}dispose(){this._loader=null}loadBufferViewAsync(e,n){return Ms.LoadExtensionAsync(e,n,this.name,(s,o)=>b(this,void 0,void 0,function*(){const s=n;if(s._meshOptData)return yield s._meshOptData;const r=Ts.Get(`${e}/buffer`,this._loader.gltf.buffers,o.buffer);return s._meshOptData=this._loader.loadBufferAsync(`/buffers/${r.index}`,r,o.byteOffset||0,o.byteLength).then(e=>b(this,void 0,void 0,function*(){return yield t.MeshoptCompression.Default.decodeGltfBufferAsync(e,o.count,o.byteStride,o.mode,o.filter)})),yield s._meshOptData}))}},Qs=!1;function Zs(){Qs||(Qs=!0,ns(Xs),ts(Xs,!0,e=>new Ys(e)))}Zs();var Js={__proto__:null,EXT_meshopt_compression:Ys,RegisterEXT_meshopt_compression:Zs};const eo="EXT_texture_webp";let to=class{constructor(e){this.name=eo,this._loader=e,this.enabled=e.isExtensionUsed(eo)}dispose(){this._loader=null}_loadTextureAsync(e,t,n){return Ms.LoadExtensionAsync(e,t,this.name,(s,o)=>b(this,void 0,void 0,function*(){const r=null==t.sampler?Ms.DefaultSampler:Ts.Get(`${e}/sampler`,this._loader.gltf.samplers,t.sampler),i=Ts.Get(`${s}/source`,this._loader.gltf.images,o.source);return yield this._loader._createTextureAsync(e,r,i,e=>{n(e)},void 0,!t._textureInfo.nonColorData)}))}},no=!1;function so(){no||(no=!0,ns(eo),ts(eo,!0,e=>new to(e)))}so();var oo={__proto__:null,EXT_texture_webp:to,RegisterEXT_texture_webp:so};const ro="EXT_texture_avif";let io=class{constructor(e){this.name=ro,this._loader=e,this.enabled=e.isExtensionUsed(ro)}dispose(){this._loader=null}_loadTextureAsync(e,t,n){return Ms.LoadExtensionAsync(e,t,this.name,(s,o)=>b(this,void 0,void 0,function*(){const r=null==t.sampler?Ms.DefaultSampler:Ts.Get(`${e}/sampler`,this._loader.gltf.samplers,t.sampler),i=Ts.Get(`${s}/source`,this._loader.gltf.images,o.source);return yield this._loader._createTextureAsync(e,r,i,e=>{n(e)},void 0,!t._textureInfo.nonColorData)}))}},ao=!1;function lo(){ao||(ao=!0,ns(ro),ts(ro,!0,e=>new io(e)))}lo();var uo={__proto__:null,EXT_texture_avif:io,RegisterEXT_texture_avif:lo};const co="EXT_lights_ies";let ho=class{constructor(e){this.name=co,this._loader=e,this.enabled=this._loader.isExtensionUsed(co)}dispose(){this._loader=null,delete this._lights}onLoading(){const e=this._loader.gltf.extensions;if(e&&e[this.name]){const t=e[this.name];this._lights=t.lights,Ts.Assign(this._lights)}}loadNodeAsync(e,n,s){return Ms.LoadExtensionAsync(e,n,this.name,(o,r)=>b(this,void 0,void 0,function*(){let i,a;this._loader._allMaterialsDirtyRequired=!0;const l=yield this._loader.loadNodeAsync(e,n,e=>{a=Ts.Get(o,this._lights,r.light);const n=a.name||e.name;this._loader.babylonScene._blockEntityCollection=!!this._loader._assetContainer,i=new t.SpotLight(n,t.Vector3.Zero(),t.Vector3.Backward(),0,1,this._loader.babylonScene),i.angle=Math.PI/2,i.innerAngle=0,i._parentContainer=this._loader._assetContainer,this._loader.babylonScene._blockEntityCollection=!1,a._babylonLight=i,i.falloffType=t.Light.FALLOFF_GLTF,i.diffuse=r.color?t.Color3.FromArray(r.color):t.Color3.White(),i.intensity=r.multiplier||1,i.range=Number.MAX_VALUE,i.parent=e,this._loader._babylonLights.push(i),Ms.AddPointerMetadata(i,o),s(e)});let u;if(a.uri)u=yield this._loader.loadUriAsync(e,a,a.uri);else{const t=Ts.Get(`${e}/bufferView`,this._loader.gltf.bufferViews,a.bufferView);u=yield this._loader.loadBufferViewAsync(`/bufferViews/${t.index}`,t)}return i.iesProfileTexture=new t.Texture(i.name+"_iesProfile",this._loader.babylonScene,!0,!1,void 0,null,null,u,!0,void 0,void 0,void 0,void 0,".ies"),l}))}},mo=!1;function fo(){mo||(mo=!0,ns(co),ts(co,!0,e=>new ho(e)))}fo();var po={__proto__:null,EXT_lights_ies:ho,RegisterEXT_lights_ies:fo};const _o="KHR_draco_mesh_compression";let go=class{constructor(e){this.name=_o,this.useNormalizedFlagFromAccessor=!0,this._loader=e,this.enabled=t.DracoDecoder.DefaultAvailable&&this._loader.isExtensionUsed(_o)}dispose(){delete this.dracoDecoder,this._loader=null}_loadVertexDataAsync(e,n,s){return Ms.LoadExtensionAsync(e,n,this.name,(o,r)=>b(this,void 0,void 0,function*(){if(null!=n.mode&&4!==n.mode&&5!==n.mode)throw new Error(`${e}: Unsupported mode ${n.mode}`);const i={},a={},l=(e,t)=>{const o=r.attributes[e];if(null!=o&&(s._delayInfo=s._delayInfo||[],-1===s._delayInfo.indexOf(t)&&s._delayInfo.push(t),i[t]=o,this.useNormalizedFlagFromAccessor)){const s=Ts.TryGet(this._loader.gltf.accessors,n.attributes[e]);s&&(a[t]=s.normalized||!1)}};l("POSITION",t.VertexBuffer.PositionKind),l("NORMAL",t.VertexBuffer.NormalKind),l("TANGENT",t.VertexBuffer.TangentKind),l("TEXCOORD_0",t.VertexBuffer.UVKind),l("TEXCOORD_1",t.VertexBuffer.UV2Kind),l("TEXCOORD_2",t.VertexBuffer.UV3Kind),l("TEXCOORD_3",t.VertexBuffer.UV4Kind),l("TEXCOORD_4",t.VertexBuffer.UV5Kind),l("TEXCOORD_5",t.VertexBuffer.UV6Kind),l("JOINTS_0",t.VertexBuffer.MatricesIndicesKind),l("WEIGHTS_0",t.VertexBuffer.MatricesWeightsKind),l("COLOR_0",t.VertexBuffer.ColorKind);const u=Ts.Get(o,this._loader.gltf.bufferViews,r.bufferView);return u._dracoBabylonGeometry||(u._dracoBabylonGeometry=this._loader.loadBufferViewAsync(`/bufferViews/${u.index}`,u).then(o=>b(this,void 0,void 0,function*(){const r=this.dracoDecoder||t.DracoDecoder.Default,l=Ts.TryGet(this._loader.gltf.accessors,n.attributes.POSITION),u=this._loader.parent.alwaysComputeBoundingBox||s.skeleton||!l?null:As(l);return yield r._decodeMeshToGeometryForGltfAsync(s.name,this._loader.babylonScene,o,i,a,u).catch(t=>{throw new Error(`${e}: ${t.message}`)})}))),yield u._dracoBabylonGeometry}))}},yo=!1;function vo(){yo||(yo=!0,ns(_o),ts(_o,!0,e=>new go(e)))}vo();var bo={__proto__:null,KHR_draco_mesh_compression:go,RegisterKHR_draco_mesh_compression:vo};const xo="KHR_gaussian_splatting",To=.28209479177387814,Ao=[0,3,5,7];function Mo(e){return e<=0?0:e>=255?255:e+.5|0}let wo=class{constructor(e){this.name=xo,this._loader=e,this.enabled=this._loader.isExtensionUsed(xo)}dispose(){this._loader=null}_loadMeshPrimitiveAsync(e,n,s,o,r,i){return Ms.LoadExtensionAsync(e,r,this.name,s=>b(this,void 0,void 0,function*(){if(null!=r.mode&&0!==r.mode)throw new Error(`${s}: Gaussian splatting primitives must use POINTS mode`);const o=this._loader,a=t=>{const n=r.attributes[t];if(null==n)return null;const s=Ts.Get(`${e}/attributes/${t}`,o.gltf.accessors,n);return o._loadFloatAccessorAsync(`/accessors/${s.index}`,s)},l=a("POSITION");if(!l)throw new Error(`${s}: Gaussian splatting primitive is missing the POSITION attribute`);let u=0;const c=[];for(let e=1;e<=3&&null!=r.attributes[`KHR_gaussian_splatting:SH_DEGREE_${e}_COEF_0`];e++){u=e;for(let t=0;t<Ao[e];t++)c.push(`KHR_gaussian_splatting:SH_DEGREE_${e}_COEF_${t}`)}const d=o.babylonScene;d._blockEntityCollection=!!o._assetContainer;const h=new t.GaussianSplattingMesh(n,null,d);h._parentContainer=o._assetContainer,d._blockEntityCollection=!1,Ms.AddPointerMetadata(h,e),o.parent.onMeshLoadedObservable.notifyObservers(h),i(h);const m=d.getEngine().getCaps(),[f,p,_,g,y,v,...b]=yield Promise.all([l,a("KHR_gaussian_splatting:ROTATION"),a("KHR_gaussian_splatting:SCALE"),a("KHR_gaussian_splatting:OPACITY"),a("KHR_gaussian_splatting:SH_DEGREE_0_COEF_0"),a("COLOR_0"),...c.map(e=>a(e))]),x=f.length/3,T=v?v.length/x:0,A=new ArrayBuffer(32*x),M=new Float32Array(A),w=new Uint8Array(A);let C=null;if(u>0){const e=3*((u+1)*(u+1)-1),n=Math.ceil(e/16),s=m.maxTextureSize,o=Math.ceil(x/s);C=t.AllocateShBuffers(n,o*s*4*4)}for(let e=0;e<x;e++){const t=8*e,n=32*e,s=3*e;if(M[t+0]=f[s+0],M[t+1]=f[s+1],M[t+2]=f[s+2],M[t+3]=_?_[s+0]:1,M[t+4]=_?_[s+1]:1,M[t+5]=_?_[s+2]:1,y)w[n+24]=Mo(255*(.5+To*y[s+0])),w[n+25]=Mo(255*(.5+To*y[s+1])),w[n+26]=Mo(255*(.5+To*y[s+2]));else if(v){const t=e*T;w[n+24]=Mo(255*v[t+0]),w[n+25]=Mo(255*v[t+1]),w[n+26]=Mo(255*v[t+2])}else w[n+24]=255,w[n+25]=255,w[n+26]=255;w[n+27]=g?Mo(255*g[e]):v&&T>=4?Mo(255*v[e*T+3]):255;const o=4*e,r=p?p[o+0]:0,i=p?p[o+1]:0,a=p?p[o+2]:0,l=p?p[o+3]:1;if(w[n+28]=Mo(127.5*l+127.5),w[n+29]=Mo(127.5*r+127.5),w[n+30]=Mo(127.5*i+127.5),w[n+31]=Mo(127.5*a+127.5),C){const t=16*e;for(let e=0;e<b.length;e++){const n=b[e];if(n)for(let o=0;o<3;o++){const r=3*e+o,i=15&r;C[r>>4][t+i]=Mo(128*n[s+o]+128)}}}}return yield h.updateDataAsync(A,null!=C?C:void 0,void 0,u||void 0),h}))}},Co=!1;function Ro(){Co||(Co=!0,ns(xo),ts(xo,!0,e=>new wo(e)))}Ro();var So={__proto__:null,KHR_gaussian_splatting:wo,RegisterKHR_gaussian_splatting:Ro};const Oo="KHR_lights_punctual";class Fo{constructor(e){this.name=Oo,this._loader=e,this.enabled=this._loader.isExtensionUsed(Oo)}dispose(){this._loader=null,delete this._lights}onLoading(){const e=this._loader.gltf.extensions;if(e&&e[this.name]){const t=e[this.name];this._lights=t.lights,Ts.Assign(this._lights)}}loadNodeAsync(e,n,s){return Ms.LoadExtensionAsync(e,n,this.name,(o,r)=>b(this,void 0,void 0,function*(){return this._loader._allMaterialsDirtyRequired=!0,yield this._loader.loadNodeAsync(e,n,e=>{let n;const i=Ts.Get(o,this._lights,r.light),a=i.name||e.name;switch(this._loader.babylonScene._blockEntityCollection=!!this._loader._assetContainer,i.type){case"directional":{const e=new t.DirectionalLight(a,t.Vector3.Backward(),this._loader.babylonScene);e.position.setAll(0),n=e;break}case"point":n=new t.PointLight(a,t.Vector3.Zero(),this._loader.babylonScene);break;case"spot":{const e=new t.SpotLight(a,t.Vector3.Zero(),t.Vector3.Backward(),0,1,this._loader.babylonScene);e.angle=2*(i.spot&&i.spot.outerConeAngle||Math.PI/4),e.innerAngle=2*(i.spot&&i.spot.innerConeAngle||0),n=e;break}default:throw this._loader.babylonScene._blockEntityCollection=!1,new Error(`${o}: Invalid light type (${i.type})`)}n._parentContainer=this._loader._assetContainer,this._loader.babylonScene._blockEntityCollection=!1,i._babylonLight=n,n.falloffType=t.Light.FALLOFF_GLTF,n.diffuse=i.color?t.Color3.FromArray(i.color):t.Color3.White(),n.intensity=null==i.intensity?1:i.intensity,n.range=null==i.range?Number.MAX_VALUE:i.range,n.parent=e,this._loader._babylonLights.push(n),Ms.AddPointerMetadata(n,o),s(e)})}))}}let Eo=!1;function Io(){Eo||(Eo=!0,ns(Oo),ts(Oo,!0,e=>new Fo(e)))}Io();var Lo={__proto__:null,KHR_lights:Fo,RegisterKHR_lights:Io};const Po="EXT_lights_area";let Bo=class{constructor(e){this.name=Po,this._loader=e,this.enabled=this._loader.isExtensionUsed(Po)}dispose(){this._loader=null,delete this._lights}onLoading(){const e=this._loader.gltf.extensions;if(e&&e[this.name]){const t=e[this.name];this._lights=t.lights,Ts.Assign(this._lights)}}loadNodeAsync(e,n,s){return Ms.LoadExtensionAsync(e,n,this.name,(o,r)=>b(this,void 0,void 0,function*(){return this._loader._allMaterialsDirtyRequired=!0,yield this._loader.loadNodeAsync(e,n,e=>{var n;let i;const a=Ts.Get(o,this._lights,r.light),l=a.name||e.name;this._loader.babylonScene._blockEntityCollection=!!this._loader._assetContainer;const u=void 0!==a.size?a.size:1;switch(a.type){case"rect":{const e=void 0!==(null===(n=a.rect)||void 0===n?void 0:n.aspect)?a.rect.aspect*u:u,s=u;i=new t.RectAreaLight(l,t.Vector3.Zero(),e,s,this._loader.babylonScene);break}case"disk":{const e=Math.sqrt(u*u*.25*Math.PI);i=new t.RectAreaLight(l,t.Vector3.Zero(),e,e,this._loader.babylonScene);break}default:throw this._loader.babylonScene._blockEntityCollection=!1,new Error(`${o}: Invalid area light type (${a.type})`)}i._parentContainer=this._loader._assetContainer,this._loader.babylonScene._blockEntityCollection=!1,a._babylonLight=i,i.falloffType=t.Light.FALLOFF_GLTF,i.diffuse=a.color?t.Color3.FromArray(a.color):t.Color3.White(),i.intensity=null==a.intensity?1:a.intensity;const c=new t.TransformNode(`${l}_orientation`,this._loader.babylonScene);c.rotationQuaternion=t.Quaternion.RotationAxis(t.Vector3.Up(),Math.PI),c.parent=e,i.parent=c,this._loader._babylonLights.push(i),Ms.AddPointerMetadata(i,o),s(e)})}))}},No=!1;function ko(){No||(No=!0,ns(Po),ts(Po,!0,e=>new Bo(e)))}ko();var Do={__proto__:null,EXT_lights_area:Bo,RegisterEXT_lights_area:ko};const Go="KHR_materials_pbrSpecularGlossiness";let Vo=class{constructor(e){this.name=Go,this.order=200,this._loader=e,this.enabled=this._loader.isExtensionUsed(Go)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return Ms.LoadExtensionAsync(e,t,this.name,(s,o)=>b(this,void 0,void 0,function*(){const r=new Array;return r.push(this._loader.loadMaterialBasePropertiesAsync(e,t,n)),r.push(this._loadSpecularGlossinessPropertiesAsync(s,o,n)),this._loader.loadMaterialAlphaProperties(e,t,n),yield Promise.all(r).then(()=>{})}))}_loadSpecularGlossinessPropertiesAsync(e,n,s){const o=this._loader._getOrCreateMaterialAdapter(s),r=new Array;return o.configureSpecularGlossiness(),n.diffuseFactor?(o.baseColor=t.Color3.FromArray(n.diffuseFactor),s.alpha=n.diffuseFactor[3]):o.baseColor=t.Color3.White(),o.specularColor=n.specularFactor?t.Color3.FromArray(n.specularFactor):t.Color3.White(),o.glossiness=null==n.glossinessFactor?1:n.glossinessFactor,n.diffuseTexture&&r.push(this._loader.loadTextureInfoAsync(`${e}/diffuseTexture`,n.diffuseTexture,e=>{e.name=`${s.name} (Diffuse)`,o.baseColorTexture=e})),n.specularGlossinessTexture&&r.push(this._loader.loadTextureInfoAsync(`${e}/specularGlossinessTexture`,n.specularGlossinessTexture,e=>{e.name=`${s.name} (Specular Glossiness)`,o.specularColorTexture=e})),Promise.all(r).then(()=>{})}},Ho=!1;function Ko(){Ho||(Ho=!0,ns(Go),ts(Go,!0,e=>new Vo(e)))}Ko();var $o={__proto__:null,KHR_materials_pbrSpecularGlossiness:Vo,RegisterKHR_materials_pbrSpecularGlossiness:Ko};const Uo="KHR_materials_unlit";let qo=class{constructor(e){this.name=Uo,this.order=210,this._loader=e,this.enabled=this._loader.isExtensionUsed(Uo)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return Ms.LoadExtensionAsync(e,t,this.name,()=>b(this,void 0,void 0,function*(){return yield this._loadUnlitPropertiesAsync(e,t,n)}))}_loadUnlitPropertiesAsync(e,n,s){const o=this._loader._getOrCreateMaterialAdapter(s),r=new Array,i=n.pbrMetallicRoughness;return i&&(i.baseColorFactor&&(o.baseColor=t.Color3.FromArray(i.baseColorFactor),o.geometryOpacity=i.baseColorFactor[3]),i.baseColorTexture&&r.push(this._loader.loadTextureInfoAsync(`${e}/baseColorTexture`,i.baseColorTexture,e=>{e.name=`${s.name} (Base Color)`,o.baseColorTexture=e}))),o.isUnlit=!0,n.doubleSided&&(o.backFaceCulling=!1,o.twoSidedLighting=!0),this._loader.loadMaterialAlphaProperties(e,n,s),Promise.all(r).then(()=>{})}},Wo=!1;function zo(){Wo||(Wo=!0,ns(Uo),ts(Uo,!0,e=>new qo(e)))}zo();var jo={__proto__:null,KHR_materials_unlit:qo,RegisterKHR_materials_unlit:zo};const Xo="KHR_materials_clearcoat";let Yo=class{constructor(e){this.name=Xo,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(Xo)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return Ms.LoadExtensionAsync(e,t,this.name,(s,o)=>b(this,void 0,void 0,function*(){const r=new Array;r.push(this._loader.loadMaterialPropertiesAsync(e,t,n)),r.push(this._loadClearCoatPropertiesAsync(s,o,n)),yield Promise.all(r)}))}_loadClearCoatPropertiesAsync(e,t,n){const s=this._loader._getOrCreateMaterialAdapter(n),o=new Array;return s.configureCoat(),s.coatWeight=void 0!==t.clearcoatFactor?t.clearcoatFactor:0,s.coatRoughness=void 0!==t.clearcoatRoughnessFactor?t.clearcoatRoughnessFactor:0,t.clearcoatTexture&&o.push(this._loader.loadTextureInfoAsync(`${e}/clearcoatTexture`,t.clearcoatTexture,e=>{e.name=`${n.name} (ClearCoat)`,s.coatWeightTexture=e})),t.clearcoatRoughnessTexture&&(t.clearcoatRoughnessTexture.nonColorData=!0,o.push(this._loader.loadTextureInfoAsync(`${e}/clearcoatRoughnessTexture`,t.clearcoatRoughnessTexture,e=>{e.name=`${n.name} (ClearCoat Roughness)`,s.coatRoughnessTexture=e}))),t.clearcoatNormalTexture&&(t.clearcoatNormalTexture.nonColorData=!0,o.push(this._loader.loadTextureInfoAsync(`${e}/clearcoatNormalTexture`,t.clearcoatNormalTexture,e=>{var o;e.name=`${n.name} (ClearCoat Normal)`,s.geometryCoatNormalTexture=e,null!=(null===(o=t.clearcoatNormalTexture)||void 0===o?void 0:o.scale)&&(s.geometryCoatNormalTextureScale=t.clearcoatNormalTexture.scale)})),s.setNormalMapInversions(!n.getScene().useRightHandedSystem,n.getScene().useRightHandedSystem)),Promise.all(o).then(()=>{})}},Qo=!1;function Zo(){Qo||(Qo=!0,ns(Xo),ts(Xo,!0,e=>new Yo(e)))}Zo();var Jo={__proto__:null,KHR_materials_clearcoat:Yo,RegisterKHR_materials_clearcoat:Zo};const er="KHR_materials_coat";let tr=class{constructor(e){this.name=er,this.order=191,this.useOpenPBR=!1,this._loader=e,this.enabled=this._loader.isExtensionUsed(er)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return Ms.LoadExtensionAsync(e,t,this.name,(s,o)=>b(this,void 0,void 0,function*(){const r=new Array;r.push(this._loader.loadMaterialPropertiesAsync(e,t,n)),t.extensions&&t.extensions.KHR_materials_openpbr&&(this.useOpenPBR=!0),r.push(this._loadCoatPropertiesAsync(s,o,n)),yield Promise.all(r)}))}_loadCoatPropertiesAsync(e,n,s){var o,r;const i=this._loader._getOrCreateMaterialAdapter(s),a=new Array;i.configureCoat(),i.coatWeight=void 0!==n.coatFactor?n.coatFactor:0,i.coatRoughness=void 0!==n.coatRoughnessFactor?n.coatRoughnessFactor:0,n.coatTexture&&a.push(this._loader.loadTextureInfoAsync(`${e}/coatTexture`,n.coatTexture,e=>{e.name=`${s.name} (Coat)`,i.coatWeightTexture=e})),n.coatRoughnessTexture&&(n.coatRoughnessTexture.nonColorData=!0,a.push(this._loader.loadTextureInfoAsync(`${e}/coatRoughnessTexture`,n.coatRoughnessTexture,e=>{e.name=`${s.name} (Coat Roughness)`,i.coatRoughnessTexture=e}))),n.coatNormalTexture&&(n.coatNormalTexture.nonColorData=!0,a.push(this._loader.loadTextureInfoAsync(`${e}/coatNormalTexture`,n.coatNormalTexture,e=>{var t;e.name=`${s.name} (Coat Normal)`,i.geometryCoatNormalTexture=e,null!=(null===(t=n.coatNormalTexture)||void 0===t?void 0:t.scale)&&(i.geometryCoatNormalTextureScale=n.coatNormalTexture.scale)})),i.setNormalMapInversions(!s.getScene().useRightHandedSystem,s.getScene().useRightHandedSystem)),i.coatDarkening=void 0!==n.coatDarkeningFactor?n.coatDarkeningFactor:1,i.coatIor=void 0!==n.coatIor?n.coatIor:1.5;const l=t.Color3.White();void 0!==n.coatColorFactor&&l.fromArray(n.coatColorFactor),i.coatColor=l,n.coatColorTexture&&a.push(this._loader.loadTextureInfoAsync(`${e}/coatColorTexture`,n.coatColorTexture,e=>{e.name=`${s.name} (Coat Color)`,i.coatColorTexture=e}));const u=null!==(o=n.coatAnisotropyStrength)&&void 0!==o?o:0,c=null!==(r=n.coatAnisotropyRotation)&&void 0!==r?r:0;return i.coatRoughnessAnisotropy=u,i.geometryCoatTangentAngle=c,this.useOpenPBR||i.configureGltfStyleAnisotropy(!0),n.coatAnisotropyTexture&&(n.coatAnisotropyTexture.nonColorData=!0,a.push(this._loader.loadTextureInfoAsync(`${e}/coatAnisotropyTexture`,n.coatAnisotropyTexture,e=>{e.name=`${s.name} (Coat Anisotropy)`,i.geometryCoatTangentTexture=e}))),Promise.all(a).then(()=>{})}},nr=!1;function sr(){nr||(nr=!0,ns(er),ts(er,!0,e=>new tr(e)))}sr();var or={__proto__:null,KHR_materials_coat:tr,RegisterKHR_materials_coat:sr};const rr="KHR_materials_iridescence";let ir=class{constructor(e){this.name=rr,this.order=195,this._loader=e,this.enabled=this._loader.isExtensionUsed(rr)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return Ms.LoadExtensionAsync(e,t,this.name,(s,o)=>b(this,void 0,void 0,function*(){const r=new Array;return r.push(this._loader.loadMaterialPropertiesAsync(e,t,n)),r.push(this._loadIridescencePropertiesAsync(s,o,n)),yield Promise.all(r).then(()=>{})}))}_loadIridescencePropertiesAsync(e,t,n){var s,o,r,i,a;const l=this._loader._getOrCreateMaterialAdapter(n),u=new Array;return l.thinFilmWeight=null!==(s=t.iridescenceFactor)&&void 0!==s?s:0,l.thinFilmIor=null!==(r=null!==(o=t.iridescenceIor)&&void 0!==o?o:t.iridescenceIOR)&&void 0!==r?r:1.3,l.thinFilmThicknessMinimum=null!==(i=t.iridescenceThicknessMinimum)&&void 0!==i?i:100,l.thinFilmThicknessMaximum=null!==(a=t.iridescenceThicknessMaximum)&&void 0!==a?a:400,t.iridescenceTexture&&u.push(this._loader.loadTextureInfoAsync(`${e}/iridescenceTexture`,t.iridescenceTexture,e=>{e.name=`${n.name} (Iridescence)`,l.thinFilmWeightTexture=e})),t.iridescenceThicknessTexture&&u.push(this._loader.loadTextureInfoAsync(`${e}/iridescenceThicknessTexture`,t.iridescenceThicknessTexture,e=>{e.name=`${n.name} (Iridescence Thickness)`,l.thinFilmThicknessTexture=e})),Promise.all(u).then(()=>{})}},ar=!1;function lr(){ar||(ar=!0,ns(rr),ts(rr,!0,e=>new ir(e)))}lr();var ur={__proto__:null,KHR_materials_iridescence:ir,RegisterKHR_materials_iridescence:lr};const cr="KHR_materials_anisotropy";let dr=class{constructor(e){this.name=cr,this.order=195,this._loader=e,this.enabled=this._loader.isExtensionUsed(cr)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return Ms.LoadExtensionAsync(e,t,this.name,(s,o)=>b(this,void 0,void 0,function*(){const r=new Array;r.push(this._loader.loadMaterialPropertiesAsync(e,t,n)),r.push(this._loadAnisotropyPropertiesAsync(s,o,n)),yield Promise.all(r)}))}_loadAnisotropyPropertiesAsync(e,t,n){return b(this,void 0,void 0,function*(){var s,o,r;const i=this._loader._getOrCreateMaterialAdapter(n),a=new Array,l=null!==(s=t.anisotropyStrength)&&void 0!==s?s:0,u=null!==(o=t.anisotropyRotation)&&void 0!==o?o:0;i.specularRoughnessAnisotropy=l,i.geometryTangentAngle=u;const c=null!==(r=t.extensions)&&void 0!==r?r:{};c.EXT_materials_anisotropy_openpbr&&c.EXT_materials_anisotropy_openpbr.openPbrAnisotropyEnabled||i.configureGltfStyleAnisotropy(!0),t.anisotropyTexture&&(t.anisotropyTexture.nonColorData=!0,a.push(this._loader.loadTextureInfoAsync(`${e}/anisotropyTexture`,t.anisotropyTexture,e=>{e.name=`${n.name} (Anisotropy Intensity)`,i.geometryTangentTexture=e}))),yield Promise.all(a)})}},hr=!1;function mr(){hr||(hr=!0,ns(cr),ts(cr,!0,e=>new dr(e)))}mr();var fr={__proto__:null,KHR_materials_anisotropy:dr,RegisterKHR_materials_anisotropy:mr};const pr="KHR_materials_emissive_strength";let _r=class{constructor(e){this.name=pr,this.order=170,this._loader=e,this.enabled=this._loader.isExtensionUsed(pr)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return Ms.LoadExtensionAsync(e,t,this.name,(s,o)=>b(this,void 0,void 0,function*(){return yield this._loader.loadMaterialPropertiesAsync(e,t,n),this._loadEmissiveProperties(s,o,n),yield Promise.resolve()}))}_loadEmissiveProperties(e,t,n){void 0!==t.emissiveStrength&&(this._loader._getOrCreateMaterialAdapter(n).emissionLuminance=t.emissiveStrength)}},gr=!1;function yr(){gr||(gr=!0,ns(pr),ts(pr,!0,e=>new _r(e)))}yr();var vr={__proto__:null,KHR_materials_emissive_strength:_r,RegisterKHR_materials_emissive_strength:yr};const br="KHR_materials_sheen";let xr=class{constructor(e){this.name=br,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(br)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return Ms.LoadExtensionAsync(e,t,this.name,(s,o)=>b(this,void 0,void 0,function*(){const r=new Array;return r.push(this._loader.loadMaterialPropertiesAsync(e,t,n)),r.push(this._loadSheenPropertiesAsync(s,o,n)),yield Promise.all(r).then(()=>{})}))}_loadSheenPropertiesAsync(e,n,s){const o=this._loader._getOrCreateMaterialAdapter(s),r=new Array;o.configureFuzz();const i=void 0!==n.sheenColorFactor?t.Color3.FromArray(n.sheenColorFactor):t.Color3.Black(),a=void 0!==n.sheenRoughnessFactor?n.sheenRoughnessFactor:0;return o.fuzzWeight=1,o.fuzzColor=i,o.fuzzRoughness=a,n.sheenColorTexture&&r.push(this._loader.loadTextureInfoAsync(`${e}/sheenColorTexture`,n.sheenColorTexture,e=>{e.name=`${s.name} (Sheen Color)`,o.fuzzColorTexture=e})),n.sheenRoughnessTexture&&(n.sheenRoughnessTexture.nonColorData=!0,r.push(this._loader.loadTextureInfoAsync(`${e}/sheenRoughnessTexture`,n.sheenRoughnessTexture,e=>{e.name=`${s.name} (Sheen Roughness)`,o.fuzzRoughnessTexture=e}))),Promise.all(r).then(()=>{})}},Tr=!1;function Ar(){Tr||(Tr=!0,ns(br),ts(br,!0,e=>new xr(e)))}Ar();var Mr={__proto__:null,KHR_materials_sheen:xr,RegisterKHR_materials_sheen:Ar};const wr="KHR_materials_fuzz";let Cr=class{constructor(e){this.name=wr,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(wr)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return Ms.LoadExtensionAsync(e,t,this.name,(s,o)=>b(this,void 0,void 0,function*(){const r=new Array;return r.push(this._loader.loadMaterialPropertiesAsync(e,t,n)),r.push(this._loadFuzzPropertiesAsync(s,o,n)),yield Promise.all(r).then(()=>{})}))}_loadFuzzPropertiesAsync(e,n,s){const o=this._loader._getOrCreateMaterialAdapter(s),r=new Array;return o.configureFuzz(),o.fuzzWeight=void 0!==n.fuzzFactor?n.fuzzFactor:0,o.fuzzColor=void 0!==n.fuzzColorFactor?t.Color3.FromArray(n.fuzzColorFactor):t.Color3.White(),o.fuzzRoughness=void 0!==n.fuzzRoughnessFactor?n.fuzzRoughnessFactor:.5,n.fuzzTexture&&r.push(this._loader.loadTextureInfoAsync(`${e}/fuzzTexture`,n.fuzzTexture,e=>{e.name=`${s.name} (Fuzz)`,o.fuzzWeightTexture=e})),n.fuzzColorTexture&&r.push(this._loader.loadTextureInfoAsync(`${e}/fuzzColorTexture`,n.fuzzColorTexture,e=>{e.name=`${s.name} (Fuzz Color)`,o.fuzzColorTexture=e})),n.fuzzRoughnessTexture&&(n.fuzzRoughnessTexture.nonColorData=!0,r.push(this._loader.loadTextureInfoAsync(`${e}/fuzzRoughnessTexture`,n.fuzzRoughnessTexture,e=>{e.name=`${s.name} (Fuzz Roughness)`,o.fuzzRoughnessTexture=e}))),Promise.all(r).then(()=>{})}},Rr=!1;function Sr(){Rr||(Rr=!0,ns(wr),ts(wr,!0,e=>new Cr(e)))}Sr();var Or={__proto__:null,KHR_materials_fuzz:Cr,RegisterKHR_materials_fuzz:Sr};const Fr="KHR_materials_specular";let Er=class{constructor(e){this.name=Fr,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(Fr)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return Ms.LoadExtensionAsync(e,t,this.name,(s,o)=>b(this,void 0,void 0,function*(){const r=new Array;r.push(this._loader.loadMaterialPropertiesAsync(e,t,n)),r.push(this._loadSpecularPropertiesAsync(s,o,n));const i=this._loader._getOrCreateMaterialAdapter(n);return o.extensions&&o.extensions.EXT_materials_specular_edge_color&&o.extensions.EXT_materials_specular_edge_color.specularEdgeColorEnabled&&i.enableSpecularEdgeColor(!0),yield Promise.all(r).then(()=>{})}))}_loadSpecularPropertiesAsync(e,n,s){var o;const r=this._loader._getOrCreateMaterialAdapter(s),i=new Array;return r.specularWeight=null!==(o=n.specularFactor)&&void 0!==o?o:1,r.specularColor=void 0!==n.specularColorFactor?t.Color3.FromArray(n.specularColorFactor):new t.Color3(1,1,1),n.specularTexture&&(n.specularTexture.nonColorData=!0,i.push(this._loader.loadTextureInfoAsync(`${e}/specularTexture`,n.specularTexture,e=>{e.name=`${s.name} (Specular)`,r.specularWeightTexture=e}))),n.specularColorTexture&&i.push(this._loader.loadTextureInfoAsync(`${e}/specularColorTexture`,n.specularColorTexture,e=>{e.name=`${s.name} (Specular Color)`,r.specularColorTexture=e})),Promise.all(i).then(()=>{})}},Ir=!1;function Lr(){Ir||(Ir=!0,ns(Fr),ts(Fr,!0,e=>new Er(e)))}Lr();var Pr={__proto__:null,KHR_materials_specular:Er,RegisterKHR_materials_specular:Lr};const Br="KHR_materials_ior";let Nr=class e{constructor(e){this.name=Br,this.order=180,this._loader=e,this.enabled=this._loader.isExtensionUsed(Br)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return Ms.LoadExtensionAsync(e,t,this.name,(s,o)=>b(this,void 0,void 0,function*(){const r=new Array;return r.push(this._loader.loadMaterialPropertiesAsync(e,t,n)),r.push(this._loadIorPropertiesAsync(s,o,n)),yield Promise.all(r).then(()=>{})}))}_loadIorPropertiesAsync(t,n,s){const o=this._loader._getOrCreateMaterialAdapter(s),r=void 0!==n.ior?n.ior:e._DEFAULT_IOR;return o.specularIor=r,Promise.resolve()}};Nr._DEFAULT_IOR=1.5;let kr=!1;function Dr(){kr||(kr=!0,ns(Br),ts(Br,!0,e=>new Nr(e)))}Dr();var Gr={__proto__:null,KHR_materials_ior:Nr,RegisterKHR_materials_ior:Dr};const Vr="KHR_materials_variants";let Hr=class e{constructor(e){this.name=Vr,this._loader=e,this.enabled=this._loader.isExtensionUsed(Vr)&&!this._loader.parent.skipMaterials}dispose(){this._loader=null}static GetAvailableVariants(e){const t=this._GetExtensionMetadata(e);return t?Object.keys(t.variants):[]}getAvailableVariants(t){return e.GetAvailableVariants(t)}static SelectVariant(e,t){const n=this._GetExtensionMetadata(e);if(!n)throw new Error(`Cannot select variant on a glTF mesh that does not have the ${Vr} extension`);const s=e=>{const t=n.variants[e];if(t)for(const e of t)e.mesh.material=e.material};if(t instanceof Array)for(const e of t)s(e);else s(t);n.lastSelected=t}selectVariant(t,n){e.SelectVariant(t,n)}static Reset(e){const t=this._GetExtensionMetadata(e);if(!t)throw new Error(`Cannot reset on a glTF mesh that does not have the ${Vr} extension`);for(const e of t.original)e.mesh.material=e.material;t.lastSelected=null}reset(t){e.Reset(t)}static GetLastSelectedVariant(e){const t=this._GetExtensionMetadata(e);if(!t)throw new Error(`Cannot get the last selected variant on a glTF mesh that does not have the ${Vr} extension`);return t.lastSelected}getLastSelectedVariant(t){return e.GetLastSelectedVariant(t)}static _GetExtensionMetadata(e){var t,n;return(null===(n=null===(t=null==e?void 0:e._internalMetadata)||void 0===t?void 0:t.gltf)||void 0===n?void 0:n[Vr])||null}onLoading(){const e=this._loader.gltf.extensions;if(e&&e[this.name]){const t=e[this.name];this._variants=t.variants}}onReady(){var t;const n=this._loader.rootBabylonMesh;if(n){const s=this._loader.parent.extensionOptions[Vr];(null==s?void 0:s.defaultVariant)&&e.SelectVariant(n,s.defaultVariant),null===(t=null==s?void 0:s.onLoaded)||void 0===t||t.call(s,{get variants(){return e.GetAvailableVariants(n)},get selectedVariant(){const t=e.GetLastSelectedVariant(n);return t?Array.isArray(t)?t[0]:t:e.GetAvailableVariants(n)[0]},set selectedVariant(t){e.SelectVariant(n,t)}})}}_loadMeshPrimitiveAsync(n,s,o,r,i,a){return Ms.LoadExtensionAsync(n,i,this.name,(l,u)=>b(this,void 0,void 0,function*(){const c=new Array;return c.push(this._loader._loadMeshPrimitiveAsync(n,s,o,r,i,s=>{if(a(s),s instanceof t.Mesh){const t=Ms._GetDrawMode(n,i.mode),o=this._loader.rootBabylonMesh,r=o?o._internalMetadata=o._internalMetadata||{}:{},a=r.gltf=r.gltf||{},d=a[Vr]=a[Vr]||{lastSelected:null,original:[],variants:{}};d.original.push({mesh:s,material:s.material});for(let n=0;n<u.mappings.length;++n){const r=u.mappings[n],i=Ts.Get(`${l}/mappings/${n}/material`,this._loader.gltf.materials,r.material);c.push(this._loader._loadMaterialAsync(`#/materials/${r.material}`,i,s,t,t=>{for(let n=0;n<r.variants.length;++n){const i=r.variants[n],a=Ts.Get(`/extensions/${Vr}/variants/${i}`,this._variants,i);d.variants[a.name]=d.variants[a.name]||[],d.variants[a.name].push({mesh:s,material:t}),s.onClonedObservable.add(t=>{const n=t;let r,i=n;do{if(i=i.parent,!i)return;r=e._GetExtensionMetadata(i)}while(null===r);if(o&&r===e._GetExtensionMetadata(o)){i._internalMetadata={};for(const e in o._internalMetadata)i._internalMetadata[e]=o._internalMetadata[e];i._internalMetadata.gltf=[];for(const e in o._internalMetadata.gltf)i._internalMetadata.gltf[e]=o._internalMetadata.gltf[e];i._internalMetadata.gltf[Vr]={lastSelected:null,original:[],variants:{}};for(const e of r.original)i._internalMetadata.gltf[Vr].original.push({mesh:e.mesh,material:e.material});for(const e in r.variants)if(Object.prototype.hasOwnProperty.call(r.variants,e)){i._internalMetadata.gltf[Vr].variants[e]=[];for(const t of r.variants[e])i._internalMetadata.gltf[Vr].variants[e].push({mesh:t.mesh,material:t.material})}r=i._internalMetadata.gltf[Vr]}for(const e of r.original)e.mesh===s&&(e.mesh=n);for(const e of r.variants[a.name])e.mesh===s&&(e.mesh=n)})}}))}}})),yield Promise.all(c).then(([e])=>e)}))}},Kr=!1;function $r(){Kr||(Kr=!0,ns(Vr),ts(Vr,!0,e=>new Hr(e)))}$r();var Ur={__proto__:null,KHR_materials_variants:Hr,RegisterKHR_materials_variants:$r};class qr{static _GetDefaultOptions(){return{renderSize:1024,samples:4,lodGenerationScale:1,lodGenerationOffset:-4,renderTargetTextureType:t.Constants.TEXTURETYPE_HALF_FLOAT,generateMipmaps:!0}}constructor(e,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=Object.assign(Object.assign({},qr._GetDefaultOptions()),e),this._scene=n,this._scene._transmissionHelper=this,this.onErrorObservable=new t.Observable,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;const t=Object.assign(Object.assign({},this._options),e),n=this._options;this._options=t,t.renderSize===n.renderSize&&t.renderTargetTextureType===n.renderTargetTextureType&&t.generateMipmaps===n.generateMipmaps&&this._opaqueRenderTarget?(this._opaqueRenderTarget.samples=t.samples,this._opaqueRenderTarget.lodGenerationScale=t.lodGenerationScale,this._opaqueRenderTarget.lodGenerationOffset=t.lodGenerationOffset):this._setupRenderTargets()}getOpaqueTarget(){return this._opaqueRenderTarget}_getOrCreateAdapter(e){let t=this._adapterCache.get(e);if(!t)for(const n of this._materialImpls)if(e instanceof n.materialClass){t=new n.adapterClass(e),this._adapterCache.set(e,t);break}return t}_classifyMeshMaterials(e){const n=e.material;if(!n)return"opaque";if(!(n instanceof t.MultiMaterial)){const e=this._getOrCreateAdapter(n);return e&&e.isTranslucent()?(e.refractionBackgroundTexture=this._opaqueRenderTarget,"transparent"):"opaque"}let s=!1,o=!1;const r=new Set;for(let e=0;e<n.subMaterials.length;e++){const t=n.subMaterials[e];if(!t){o=!0;continue}const i=this._getOrCreateAdapter(t);i&&i.isTranslucent()?(i.refractionBackgroundTexture=this._opaqueRenderTarget,s=!0,r.add(e)):o=!0}return s&&o?(this._translucentMaterialIndices.set(e,r),this._rebuildOpaqueOnlySubMeshes(e,r),"mixed"):(this._translucentMaterialIndices.delete(e),this._opaqueOnlySubMeshes.delete(e),s?"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)),t.Tools.SetImmediate(()=>{!this._disposed&&e.material&&("transparent"===this._classifyMeshMaterials(e)?-1===this._transparentMeshesCache.indexOf(e)&&this._transparentMeshesCache.push(e):-1===this._opaqueMeshesCache.indexOf(e)&&this._opaqueMeshesCache.push(e))})}_removeMesh(e){e.onMaterialChangedObservable.remove(this._materialObservers[e.uniqueId]),delete this._materialObservers[e.uniqueId];let t=this._transparentMeshesCache.indexOf(e);-1!==t&&this._transparentMeshesCache.splice(t,1),t=this._opaqueMeshesCache.indexOf(e),-1!==t&&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){const t=this._transparentMeshesCache.indexOf(e),n=this._opaqueMeshesCache.indexOf(e);"transparent"===this._classifyMeshMaterials(e)?-1!==n?(this._opaqueMeshesCache.splice(n,1),this._transparentMeshesCache.push(e)):-1===t&&this._transparentMeshesCache.push(e):-1!==t?(this._transparentMeshesCache.splice(t,1),this._opaqueMeshesCache.push(e)):-1===n&&this._opaqueMeshesCache.push(e)}_isRenderTargetValid(){var e;return null!==(null===(e=this._opaqueRenderTarget)||void 0===e?void 0:e.getInternalTexture())}_setupRenderTargets(){var e,n;let s;this._opaqueRenderTarget&&this._opaqueRenderTarget.dispose(),this._opaqueRenderTarget=new t.RenderTargetTexture("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=null!==(n=null===(e=this._options.clearColor)||void 0===e?void 0:e.clone())&&void 0!==n?n: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,this._opaqueRenderTarget.onBeforeBindObservable.add(e=>{s=this._scene.environmentIntensity,this._scene.environmentIntensity=1,this._options.clearColor?e.clearColor.copyFrom(this._options.clearColor):this._scene.clearColor.toLinearSpaceToRef(e.clearColor,this._scene.getEngine().useExactSrgbConversions),e.clearColor.a=0;const t=this._opaqueOnlySubMeshes.entries();for(let e=t.next();!e.done;e=t.next()){const t=e.value[0],n=e.value[1];t.subMeshes&&(this._savedSubMeshes.set(t,t.subMeshes),t.subMeshes=n)}}),this._opaqueRenderTarget.onAfterUnbindObservable.add(()=>{this._scene.environmentIntensity=s;const e=this._savedSubMeshes.entries();for(let t=e.next();!t.done;t=e.next())t.value[0].subMeshes=t.value[1];this._savedSubMeshes.clear()});for(const e of this._transparentMeshesCache)e.material&&this._classifyMeshMaterials(e);const o=this._translucentMaterialIndices.entries();for(let e=o.next();!e.done;e=o.next()){const t=e.value[0];t.material&&this._classifyMeshMaterials(t)}}dispose(){var e,t;this._disposed=!0,null===(e=this._newMeshObserver)||void 0===e||e.remove(),null===(t=this._removedMeshObserver)||void 0===t||t.remove(),this._newMeshObserver=null,this._removedMeshObserver=null;const n=[...this._transparentMeshesCache,...this._opaqueMeshesCache];for(const e of n){const t=this._materialObservers[e.uniqueId];t&&(t.remove(),delete this._materialObservers[e.uniqueId])}for(const e of this._scene.meshes){const 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(),this._opaqueRenderTarget=null),this._transparentMeshesCache=[],this._opaqueMeshesCache=[],this._translucentMaterialIndices.clear(),this._opaqueOnlySubMeshes.clear(),this._savedSubMeshes.clear()}}function Wr(e,t){if(e.parent.dontUseTransmissionHelper)return;const n=t.getScene()._transmissionHelper,s=null!=n?n:new qr({},t.getScene());for(const t of Array.from(e._pbrMaterialImpls.values()))s.addMaterialImpl(t);n&&!n._isRenderTargetValid()&&n._setupRenderTargets()}const zr="KHR_materials_transmission";let jr=class{constructor(e){this.name=zr,this.order=175,this._loader=e,this.enabled=this._loader.isExtensionUsed(zr),this.enabled&&(e.parent.transparencyAsCoverage=!0)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return Ms.LoadExtensionAsync(e,t,this.name,(s,o)=>b(this,void 0,void 0,function*(){const r=new Array;return r.push(this._loader.loadMaterialPropertiesAsync(e,t,n)),r.push(this._loadTransparentPropertiesAsync(s,t,n,o)),yield Promise.all(r).then(()=>{})}))}_loadTransparentPropertiesAsync(e,t,n,s){const o=this._loader._getOrCreateMaterialAdapter(n),r=void 0!==s.transmissionFactor?s.transmissionFactor:0;if(0===r||!o)return Promise.resolve();o.configureTransmission(),o.transmissionWeight=r,r>0&&Wr(this._loader,n);let i=Promise.resolve(null);return s.transmissionTexture&&(s.transmissionTexture.nonColorData=!0,i=this._loader.loadTextureInfoAsync(`${e}/transmissionTexture`,s.transmissionTexture,e=>{e.name=`${n.name} (Transmission)`,o.transmissionWeightTexture=e})),i.then(()=>{})}},Xr=!1;function Yr(){Xr||(Xr=!0,ns(zr),ts(zr,!0,e=>new jr(e)))}Yr();var Qr={__proto__:null,KHR_materials_transmission:jr,RegisterKHR_materials_transmission:Yr};const Zr="KHR_materials_diffuse_transmission";let Jr=class{constructor(e){this.name=Zr,this.order=174,this._loader=e,this.enabled=this._loader.isExtensionUsed(Zr),this.enabled&&(e.parent.transparencyAsCoverage=!0)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return Ms.LoadExtensionAsync(e,t,this.name,(s,o)=>b(this,void 0,void 0,function*(){const r=new Array;return r.push(this._loader.loadMaterialPropertiesAsync(e,t,n)),r.push(this._loadTranslucentPropertiesAsync(s,t,n,o)),yield Promise.all(r).then(()=>{})}))}_loadTranslucentPropertiesAsync(e,n,s,o){var r;const i=this._loader._getOrCreateMaterialAdapter(s);i.configureSubsurface(),i.subsurfaceWeight=null!==(r=o.diffuseTransmissionFactor)&&void 0!==r?r:0,i.subsurfaceWeight>0&&Wr(this._loader,s),i.diffuseTransmissionTint=void 0!==o.diffuseTransmissionColorFactor?t.Color3.FromArray(o.diffuseTransmissionColorFactor):t.Color3.White();const a=new Array;return o.diffuseTransmissionTexture&&(o.diffuseTransmissionTexture.nonColorData=!0,a.push(this._loader.loadTextureInfoAsync(`${e}/diffuseTransmissionTexture`,o.diffuseTransmissionTexture).then(e=>{e.name=`${s.name} (Diffuse Transmission)`,i.subsurfaceWeightTexture=e}))),o.diffuseTransmissionColorTexture&&a.push(this._loader.loadTextureInfoAsync(`${e}/diffuseTransmissionColorTexture`,o.diffuseTransmissionColorTexture).then(e=>{e.name=`${s.name} (Diffuse Transmission Color)`,i.diffuseTransmissionTintTexture=e})),Promise.all(a).then(()=>{})}},ei=!1;function ti(){ei||(ei=!0,ns(Zr),ts(Zr,!0,e=>new Jr(e)))}ti();var ni={__proto__:null,KHR_materials_diffuse_transmission:Jr,RegisterKHR_materials_diffuse_transmission:ti};const si="KHR_materials_volume";let oi=class{constructor(e){this.name=si,this.order=173,this._loader=e,this.enabled=this._loader.isExtensionUsed(si),this.enabled&&this._loader._disableInstancedMesh++}dispose(){this.enabled&&this._loader._disableInstancedMesh--,this._loader=null}loadMaterialPropertiesAsync(e,t,n){return Ms.LoadExtensionAsync(e,t,this.name,(s,o)=>b(this,void 0,void 0,function*(){const r=new Array;return r.push(this._loader.loadMaterialPropertiesAsync(e,t,n)),r.push(this._loadVolumePropertiesAsync(s,t,n,o)),yield Promise.all(r).then(()=>{})}))}_loadVolumePropertiesAsync(e,n,s,o){var r;const i=this._loader._getOrCreateMaterialAdapter(s);if(0===i.transmissionWeight&&0===i.subsurfaceWeight||!o.thicknessFactor)return Promise.resolve();i.geometryThinWalled=!1;const a=void 0!==o.attenuationDistance?o.attenuationDistance:Number.MAX_VALUE,l=void 0!==o.attenuationColor&&3==o.attenuationColor.length?t.Color3.FromArray(o.attenuationColor):t.Color3.White();i.configureVolume(),i.transmissionColor=l,i.transmissionDepth=a,i.volumeThickness=null!==(r=o.thicknessFactor)&&void 0!==r?r:0;const u=new Array;return o.thicknessTexture&&(o.thicknessTexture.nonColorData=!0,u.push(this._loader.loadTextureInfoAsync(`${e}/thicknessTexture`,o.thicknessTexture,e=>{e.name=`${s.name} (Thickness)`,i.volumeThicknessTexture=e}))),Promise.all(u).then(()=>{})}},ri=!1;function ii(){ri||(ri=!0,ns(si),ts(si,!0,e=>new oi(e)))}ii();var ai={__proto__:null,KHR_materials_volume:oi,RegisterKHR_materials_volume:ii};const li="KHR_materials_volume_scatter";let ui=class{constructor(e){this.name=li,this.order=172,this._loader=e,this.enabled=this._loader.isExtensionUsed(li),this.enabled&&this._loader._disableInstancedMesh++}dispose(){this.enabled&&this._loader._disableInstancedMesh--,this._loader=null}loadMaterialPropertiesAsync(e,t,n){return Ms.LoadExtensionAsync(e,t,this.name,(s,o)=>b(this,void 0,void 0,function*(){const r=new Array;return r.push(this._loader.loadMaterialPropertiesAsync(e,t,n)),r.push(this._loadVolumePropertiesAsync(s,t,n,o)),yield Promise.all(r).then(()=>{})}))}_loadVolumePropertiesAsync(e,n,s,o){const r=this._loader._getOrCreateMaterialAdapter(s);if(0===r.transmissionWeight&&0===r.subsurfaceWeight||r.geometryThinWalled)return Promise.resolve();const i=void 0!==o.multiscatterColorFactor&&3==o.multiscatterColorFactor.length?t.Color3.FromArray(o.multiscatterColorFactor):t.Color3.Black(),a=void 0!==o.scatterAnisotropy?o.scatterAnisotropy:0;let l=Promise.resolve(null);o.multiscatterColorTexture&&(o.multiscatterColorTexture.nonColorData=!0,l=this._loader.loadTextureInfoAsync(`${e}/multiscatterColorTexture`,o.multiscatterColorTexture,e=>{e.name=`${s.name} (Scatter Color)`,r.transmissionWeight>0&&(r.transmissionScatterTexture=e),r.subsurfaceWeight>0&&(r.subsurfaceColorTexture=e)}));const u=new t.Vector3(-Math.log(r.transmissionColor.r),-Math.log(r.transmissionColor.g),-Math.log(r.transmissionColor.b));if(u.scaleInPlace(1/Math.max(r.transmissionDepth,1e-6)),r.transmissionWeight>0){const e=function(e){const n=new t.Vector3(e.r,e.g,e.b),s=new t.Vector3(4.09712,4.09712,4.09712);s.addInPlace(new t.Vector3(4.20863,4.20863,4.20863).multiplyInPlace(n));const o=new t.Vector3(9.59217,9.59217,9.59217);return o.addInPlace(new t.Vector3(41.6808,41.6808,41.6808).multiplyInPlace(n)),o.addInPlace(new t.Vector3(17.7126,17.7126,17.7126).multiplyInPlace(n.multiply(n))),s.subtractInPlace(new t.Vector3(Math.sqrt(o.x),Math.sqrt(o.y),Math.sqrt(o.z))),new t.Vector3(1,1,1).subtract(s.multiply(s))}(i),n=u.multiply(e);n.scaleInPlace(r.transmissionDepth),r.transmissionScatter.set(n.x,n.y,n.z),r.transmissionScatterAnisotropy=a}if(r.subsurfaceWeight>0){r.subsurfaceScatterAnisotropy=a,r.subsurfaceColor=i;const e=new t.Vector3(0!==u.x?1/u.x:1,0!==u.y?1/u.y:1,0!==u.z?1/u.z:1);r.subsurfaceRadius=Math.max(e.x,e.y,e.z),r.subsurfaceRadiusScale=new t.Color3(e.x/r.subsurfaceRadius,e.y/r.subsurfaceRadius,e.z/r.subsurfaceRadius)}return l.then(()=>{})}},ci=!1;function di(){ci||(ci=!0,ns(li),ts(li,!0,e=>new ui(e)))}di();var hi={__proto__:null,KHR_materials_volume_scatter:ui,RegisterKHR_materials_volume_scatter:di};const mi="KHR_materials_dispersion";let fi=class{constructor(e){this.name=mi,this.order=174,this._loader=e,this.enabled=this._loader.isExtensionUsed(mi)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return Ms.LoadExtensionAsync(e,t,this.name,(s,o)=>b(this,void 0,void 0,function*(){const r=new Array;return r.push(this._loader.loadMaterialPropertiesAsync(e,t,n)),r.push(this._loadDispersionPropertiesAsync(s,t,n,o)),yield Promise.all(r).then(()=>{})}))}_loadDispersionPropertiesAsync(e,t,n,s){const o=this._loader._getOrCreateMaterialAdapter(n);return 0!=o.transmissionWeight&&s.dispersion?(o.transmissionDispersionAbbeNumber=20,o.transmissionDispersionScale=s.dispersion,Promise.resolve()):Promise.resolve()}},pi=!1;function _i(){pi||(pi=!0,ns(mi),ts(mi,!0,e=>new fi(e)))}_i();var gi={__proto__:null,KHR_materials_dispersion:fi,RegisterKHR_materials_dispersion:_i};const yi="KHR_materials_diffuse_roughness";let vi=class{constructor(e){this.name=yi,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(yi)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return Ms.LoadExtensionAsync(e,t,this.name,(s,o)=>b(this,void 0,void 0,function*(){const r=new Array;return r.push(this._loader.loadMaterialPropertiesAsync(e,t,n)),r.push(this._loadDiffuseRoughnessPropertiesAsync(s,o,n)),yield Promise.all(r).then(()=>{})}))}_loadDiffuseRoughnessPropertiesAsync(e,t,n){var s;const o=this._loader._getOrCreateMaterialAdapter(n),r=new Array;return o.baseDiffuseRoughness=null!==(s=t.diffuseRoughnessFactor)&&void 0!==s?s:0,t.diffuseRoughnessTexture&&r.push(this._loader.loadTextureInfoAsync(`${e}/diffuseRoughnessTexture`,t.diffuseRoughnessTexture,e=>{e.name=`${n.name} (Diffuse Roughness)`,o.baseDiffuseRoughnessTexture=e})),Promise.all(r).then(()=>{})}},bi=!1;function xi(){bi||(bi=!0,ns(yi),ts(yi,!0,e=>new vi(e)))}xi();var Ti={__proto__:null,KHR_materials_diffuse_roughness:vi,RegisterKHR_materials_diffuse_roughness:xi};const Ai="KHR_mesh_quantization";let Mi=class{constructor(e){this.name=Ai,this.enabled=e.isExtensionUsed(Ai)}dispose(){}},wi=!1;function Ci(){wi||(wi=!0,ns(Ai),ts(Ai,!0,e=>new Mi(e)))}Ci();var Ri={__proto__:null,KHR_mesh_quantization:Mi,RegisterKHR_mesh_quantization:Ci};const Si="KHR_texture_basisu";let Oi=class{constructor(e){this.name=Si,this._loader=e,this.enabled=e.isExtensionUsed(Si)}dispose(){this._loader=null}_loadTextureAsync(e,t,n){return Ms.LoadExtensionAsync(e,t,this.name,(s,o)=>b(this,void 0,void 0,function*(){const r=null==t.sampler?Ms.DefaultSampler:Ts.Get(`${e}/sampler`,this._loader.gltf.samplers,t.sampler),i=Ts.Get(`${s}/source`,this._loader.gltf.images,o.source);return yield this._loader._createTextureAsync(e,r,i,e=>{n(e)},t._textureInfo.nonColorData?{useRGBAIfASTCBC7NotAvailableWhenUASTC:!0}:void 0,!t._textureInfo.nonColorData)}))}},Fi=!1;function Ei(){Fi||(Fi=!0,ns(Si),ts(Si,!0,e=>new Oi(e)))}Ei();var Ii={__proto__:null,KHR_texture_basisu:Oi,RegisterKHR_texture_basisu:Ei};const Li="KHR_texture_transform";let Pi=class{constructor(e){this.name=Li,this._loader=e,this.enabled=this._loader.isExtensionUsed(Li)}dispose(){this._loader=null}loadTextureInfoAsync(e,n,s){return Ms.LoadExtensionAsync(e,n,this.name,(o,r)=>b(this,void 0,void 0,function*(){return yield this._loader.loadTextureInfoAsync(e,n,e=>{if(!(e instanceof t.Texture))throw new Error(`${o}: Texture type not supported`);r.offset&&(e.uOffset=r.offset[0],e.vOffset=r.offset[1]),e.uRotationCenter=0,e.vRotationCenter=0,r.rotation&&(e.wAng=-r.rotation),r.scale&&(e.uScale=r.scale[0],e.vScale=r.scale[1]),null!=r.texCoord&&(e.coordinatesIndex=r.texCoord),s(e)})}))}},Bi=!1;function Ni(){Bi||(Bi=!0,ns(Li),ts(Li,!0,e=>new Pi(e)))}Ni();var ki={__proto__:null,KHR_texture_transform:Pi,RegisterKHR_texture_transform:Ni};const Di="KHR_xmp_json_ld";let Gi=class{constructor(e){this.name=Di,this.order=100,this._loader=e,this.enabled=this._loader.isExtensionUsed(Di)}dispose(){this._loader=null}onLoading(){var e,t,n;if(null===this._loader.rootBabylonMesh)return;const s=null===(e=this._loader.gltf.extensions)||void 0===e?void 0:e.KHR_xmp_json_ld,o=null===(n=null===(t=this._loader.gltf.asset)||void 0===t?void 0:t.extensions)||void 0===n?void 0:n.KHR_xmp_json_ld;if(s&&o){const e=+o.packet;s.packets&&e<s.packets.length&&(this._loader.rootBabylonMesh.metadata=this._loader.rootBabylonMesh.metadata||{},this._loader.rootBabylonMesh.metadata.xmp=s.packets[e])}}},Vi=!1;function Hi(){Vi||(Vi=!0,ns(Di),ts(Di,!0,e=>new Gi(e)))}Hi();var Ki={__proto__:null,KHR_xmp_json_ld:Gi,RegisterKHR_xmp_json_ld:Hi};const $i="KHR_animation_pointer";let Ui=class{constructor(e){this.name=$i,this._loader=e,this._pathToObjectConverter=_s(this._loader.gltf)}get enabled(){return this._loader.isExtensionUsed($i)}dispose(){this._loader=null,delete this._pathToObjectConverter}_loadAnimationChannelAsync(e,n,s,o,r){var i;const a=null===(i=o.target.extensions)||void 0===i?void 0:i.KHR_animation_pointer;if(!a||!this._pathToObjectConverter)return null;"pointer"!==o.target.path&&t.Logger.Warn(`${e}/target/path: Value (${o.target.path}) must be (pointer) when using the ${this.name} extension`),null!=o.target.node&&t.Logger.Warn(`${e}/target/node: Value (${o.target.node}) must not be present when using the ${this.name} extension`);const l=`${e}/extensions/${this.name}`,u=a.pointer;if(!u)throw new Error(`${l}: Pointer is missing`);try{const t=this._pathToObjectConverter.convert(u);if(!t.info.interpolation)throw new Error(`${l}/pointer: Interpolation is missing`);return this._loader._loadAnimationChannelFromTargetInfoAsync(e,n,s,o,{object:t.object,info:t.info.interpolation},r)}catch(e){return t.Logger.Warn(`${l}/pointer: Invalid pointer (${u}) skipped`),null}}},qi=!1;function Wi(){qi||(qi=!0,ns($i),ts($i,!0,e=>new Ui(e)))}function zi(e,n,s,o){return t.Color3.FromArray(n,s).scale(o)}function ji(e,t,n,s){return t[n]*s}function Xi(e,t,n,s){return-t[n]*s}function Yi(e,t,n,s){return t[n+1]*s}function Qi(e,t,n,s){return t[n]*s*2}function Zi(e){return{scale:[new ea(t.Animation.ANIMATIONTYPE_FLOAT,`${e}.uScale`,ji,()=>2),new ea(t.Animation.ANIMATIONTYPE_FLOAT,`${e}.vScale`,Yi,()=>2)],offset:[new ea(t.Animation.ANIMATIONTYPE_FLOAT,`${e}.uOffset`,ji,()=>2),new ea(t.Animation.ANIMATIONTYPE_FLOAT,`${e}.vOffset`,Yi,()=>2)],rotation:[new ea(t.Animation.ANIMATIONTYPE_FLOAT,`${e}.wAng`,Xi,()=>1)]}}class Ji extends Es{buildAnimations(e,t,n,s){return[{babylonAnimatable:e._babylonCamera,babylonAnimation:this._buildAnimation(t,n,s)}]}}class ea extends Es{buildAnimations(e,t,n,s){const o=[];for(const r in e._data)o.push({babylonAnimatable:e._data[r].babylonMaterial,babylonAnimation:this._buildAnimation(t,n,s)});return o}}class ta extends Es{buildAnimations(e,t,n,s){return[{babylonAnimatable:e._babylonLight,babylonAnimation:this._buildAnimation(t,n,s)}]}}ys("/cameras/{}/orthographic/xmag",[new Ji(t.Animation.ANIMATIONTYPE_FLOAT,"orthoLeft",Xi,()=>1),new Ji(t.Animation.ANIMATIONTYPE_FLOAT,"orthoRight",Yi,()=>1)]),ys("/cameras/{}/orthographic/ymag",[new Ji(t.Animation.ANIMATIONTYPE_FLOAT,"orthoBottom",Xi,()=>1),new Ji(t.Animation.ANIMATIONTYPE_FLOAT,"orthoTop",Yi,()=>1)]),ys("/cameras/{}/orthographic/zfar",[new Ji(t.Animation.ANIMATIONTYPE_FLOAT,"maxZ",ji,()=>1)]),ys("/cameras/{}/orthographic/znear",[new Ji(t.Animation.ANIMATIONTYPE_FLOAT,"minZ",ji,()=>1)]),ys("/cameras/{}/perspective/yfov",[new Ji(t.Animation.ANIMATIONTYPE_FLOAT,"fov",ji,()=>1)]),ys("/cameras/{}/perspective/zfar",[new Ji(t.Animation.ANIMATIONTYPE_FLOAT,"maxZ",ji,()=>1)]),ys("/cameras/{}/perspective/znear",[new Ji(t.Animation.ANIMATIONTYPE_FLOAT,"minZ",ji,()=>1)]),ys("/materials/{}/pbrMetallicRoughness/baseColorFactor",[new ea(t.Animation.ANIMATIONTYPE_COLOR3,"albedoColor",zi,()=>4),new ea(t.Animation.ANIMATIONTYPE_FLOAT,"alpha",function(e,t,n,s){return t[n+3]*s},()=>4)]),ys("/materials/{}/pbrMetallicRoughness/metallicFactor",[new ea(t.Animation.ANIMATIONTYPE_FLOAT,"metallic",ji,()=>1)]),ys("/materials/{}/pbrMetallicRoughness/metallicFactor",[new ea(t.Animation.ANIMATIONTYPE_FLOAT,"roughness",ji,()=>1)]);const na=Zi("albedoTexture");ys("/materials/{}/pbrMetallicRoughness/baseColorTexture/extensions/KHR_texture_transform/scale",na.scale),ys("/materials/{}/pbrMetallicRoughness/baseColorTexture/extensions/KHR_texture_transform/offset",na.offset),ys("/materials/{}/pbrMetallicRoughness/baseColorTexture/extensions/KHR_texture_transform/rotation",na.rotation);const sa=Zi("metallicTexture");ys("//materials/{}/pbrMetallicRoughness/metallicRoughnessTexture/scale",sa.scale),ys("//materials/{}/pbrMetallicRoughness/metallicRoughnessTexture/offset",sa.offset),ys("//materials/{}/pbrMetallicRoughness/metallicRoughnessTexture/rotation",sa.rotation),ys("/materials/{}/emissiveFactor",[new ea(t.Animation.ANIMATIONTYPE_COLOR3,"emissiveColor",zi,()=>3)]);const oa=Zi("bumpTexture");ys("/materials/{}/normalTexture/scale",[new ea(t.Animation.ANIMATIONTYPE_FLOAT,"bumpTexture.level",ji,()=>1)]),ys("/materials/{}/normalTexture/extensions/KHR_texture_transform/scale",oa.scale),ys("/materials/{}/normalTexture/extensions/KHR_texture_transform/offset",oa.offset),ys("/materials/{}/normalTexture/extensions/KHR_texture_transform/rotation",oa.rotation),ys("/materials/{}/occlusionTexture/strength",[new ea(t.Animation.ANIMATIONTYPE_FLOAT,"ambientTextureStrength",ji,()=>1)]);const ra=Zi("ambientTexture");ys("/materials/{}/occlusionTexture/extensions/KHR_texture_transform/scale",ra.scale),ys("/materials/{}/occlusionTexture/extensions/KHR_texture_transform/offset",ra.offset),ys("/materials/{}/occlusionTexture/extensions/KHR_texture_transform/rotation",ra.rotation);const ia=Zi("emissiveTexture");ys("/materials/{}/emissiveTexture/extensions/KHR_texture_transform/scale",ia.scale),ys("/materials/{}/emissiveTexture/extensions/KHR_texture_transform/offset",ia.offset),ys("/materials/{}/emissiveTexture/extensions/KHR_texture_transform/rotation",ia.rotation),ys("/materials/{}/extensions/KHR_materials_anisotropy/anisotropyStrength",[new ea(t.Animation.ANIMATIONTYPE_FLOAT,"anisotropy.intensity",ji,()=>1)]),ys("/materials/{}/extensions/KHR_materials_anisotropy/anisotropyRotation",[new ea(t.Animation.ANIMATIONTYPE_FLOAT,"anisotropy.angle",ji,()=>1)]);const aa=Zi("anisotropy.texture");ys("/materials/{}/extensions/KHR_materials_anisotropy/anisotropyTexture/extensions/KHR_texture_transform/scale",aa.scale),ys("/materials/{}/extensions/KHR_materials_anisotropy/anisotropyTexture/extensions/KHR_texture_transform/offset",aa.offset),ys("/materials/{}/extensions/KHR_materials_anisotropy/anisotropyTexture/extensions/KHR_texture_transform/rotation",aa.rotation),ys("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatFactor",[new ea(t.Animation.ANIMATIONTYPE_FLOAT,"clearCoat.intensity",ji,()=>1)]),ys("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatRoughnessFactor",[new ea(t.Animation.ANIMATIONTYPE_FLOAT,"clearCoat.roughness",ji,()=>1)]);const la=Zi("clearCoat.texture");ys("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatTexture/extensions/KHR_texture_transform/scale",la.scale),ys("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatTexture/extensions/KHR_texture_transform/offset",la.offset),ys("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatTexture/extensions/KHR_texture_transform/rotation",la.rotation);const ua=Zi("clearCoat.bumpTexture");ys("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatNormalTexture/scale",[new ea(t.Animation.ANIMATIONTYPE_FLOAT,"clearCoat.bumpTexture.level",ji,()=>1)]),ys("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatNormalTexture/extensions/KHR_texture_transform/scale",ua.scale),ys("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatNormalTexture/extensions/KHR_texture_transform/offset",ua.offset),ys("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatNormalTexture/extensions/KHR_texture_transform/rotation",ua.rotation);const ca=Zi("clearCoat.textureRoughness");ys("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatRoughnessTexture/extensions/KHR_texture_transform/scale",ca.scale),ys("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatRoughnessTexture/extensions/KHR_texture_transform/offset",ca.offset),ys("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatRoughnessTexture/extensions/KHR_texture_transform/rotation",ca.rotation),ys("/materials/{}/extensions/KHR_materials_dispersion/dispersionFactor",[new ea(t.Animation.ANIMATIONTYPE_FLOAT,"subSurface.dispersion",ji,()=>1)]),ys("/materials/{}/extensions/KHR_materials_emissive_strength/emissiveStrength",[new ea(t.Animation.ANIMATIONTYPE_FLOAT,"emissiveIntensity",ji,()=>1)]),ys("/materials/{}/extensions/KHR_materials_ior/ior",[new ea(t.Animation.ANIMATIONTYPE_FLOAT,"indexOfRefraction",ji,()=>1)]),ys("/materials/{}/extensions/KHR_materials_iridescence/iridescenceFactor",[new ea(t.Animation.ANIMATIONTYPE_FLOAT,"iridescence.intensity",ji,()=>1)]),ys("/materials/{}/extensions/KHR_materials_iridescence/iridescenceIor",[new ea(t.Animation.ANIMATIONTYPE_FLOAT,"iridescence.indexOfRefraction",ji,()=>1)]),ys("/materials/{}/extensions/KHR_materials_iridescence/iridescenceThicknessMinimum",[new ea(t.Animation.ANIMATIONTYPE_FLOAT,"iridescence.minimumThickness",ji,()=>1)]),ys("/materials/{}/extensions/KHR_materials_iridescence/iridescenceThicknessMaximum",[new ea(t.Animation.ANIMATIONTYPE_FLOAT,"iridescence.maximumThickness",ji,()=>1)]);const da=Zi("iridescence.texture");ys("/materials/{}/extensions/KHR_materials_iridescence/iridescenceTexture/extensions/KHR_texture_transform/scale",da.scale),ys("/materials/{}/extensions/KHR_materials_iridescence/iridescenceTexture/extensions/KHR_texture_transform/offset",da.offset),ys("/materials/{}/extensions/KHR_materials_iridescence/iridescenceTexture/extensions/KHR_texture_transform/rotation",da.rotation);const ha=Zi("iridescence.thicknessTexture");ys("/materials/{}/extensions/KHR_materials_iridescence/iridescenceThicknessTexture/extensions/KHR_texture_transform/scale",ha.scale),ys("/materials/{}/extensions/KHR_materials_iridescence/iridescenceThicknessTexture/extensions/KHR_texture_transform/offset",ha.offset),ys("/materials/{}/extensions/KHR_materials_iridescence/iridescenceThicknessTexture/extensions/KHR_texture_transform/rotation",ha.rotation),ys("/materials/{}/extensions/KHR_materials_sheen/sheenColorFactor",[new ea(t.Animation.ANIMATIONTYPE_COLOR3,"sheen.color",zi,()=>3)]),ys("/materials/{}/extensions/KHR_materials_sheen/sheenRoughnessFactor",[new ea(t.Animation.ANIMATIONTYPE_FLOAT,"sheen.roughness",ji,()=>1)]);const ma=Zi("sheen.texture");ys("/materials/{}/extensions/KHR_materials_sheen/sheenColorTexture/extensions/KHR_texture_transform/scale",ma.scale),ys("/materials/{}/extensions/KHR_materials_sheen/sheenColorTexture/extensions/KHR_texture_transform/offset",ma.offset),ys("/materials/{}/extensions/KHR_materials_sheen/sheenColorTexture/extensions/KHR_texture_transform/rotation",ma.rotation);const fa=Zi("sheen.textureRoughness");ys("/materials/{}/extensions/KHR_materials_sheen/sheenRoughnessTexture/extensions/KHR_texture_transform/scale",fa.scale),ys("/materials/{}/extensions/KHR_materials_sheen/sheenRoughnessTexture/extensions/KHR_texture_transform/offset",fa.offset),ys("/materials/{}/extensions/KHR_materials_sheen/sheenRoughnessTexture/extensions/KHR_texture_transform/rotation",fa.rotation),ys("/materials/{}/extensions/KHR_materials_specular/specularFactor",[new ea(t.Animation.ANIMATIONTYPE_FLOAT,"metallicF0Factor",ji,()=>1)]),ys("/materials/{}/extensions/KHR_materials_specular/specularColorFactor",[new ea(t.Animation.ANIMATIONTYPE_COLOR3,"metallicReflectanceColor",zi,()=>3)]);const pa=Zi("metallicReflectanceTexture");ys("/materials/{}/extensions/KHR_materials_specular/specularTexture/extensions/KHR_texture_transform/scale",pa.scale),ys("/materials/{}/extensions/KHR_materials_specular/specularTexture/extensions/KHR_texture_transform/offset",pa.offset),ys("/materials/{}/extensions/KHR_materials_specular/specularTexture/extensions/KHR_texture_transform/rotation",pa.rotation);const _a=Zi("reflectanceTexture");ys("/materials/{}/extensions/KHR_materials_specular/specularColorTexture/extensions/KHR_texture_transform/scale",_a.scale),ys("/materials/{}/extensions/KHR_materials_specular/specularColorTexture/extensions/KHR_texture_transform/offset",_a.offset),ys("/materials/{}/extensions/KHR_materials_specular/specularColorTexture/extensions/KHR_texture_transform/rotation",_a.rotation),ys("/materials/{}/extensions/KHR_materials_transmission/transmissionFactor",[new ea(t.Animation.ANIMATIONTYPE_FLOAT,"subSurface.refractionIntensity",ji,()=>1)]);const ga=Zi("subSurface.refractionIntensityTexture");ys("/materials/{}/extensions/KHR_materials_transmission/transmissionTexture/extensions/KHR_texture_transform/scale",ga.scale),ys("/materials/{}/extensions/KHR_materials_transmission/transmissionTexture/extensions/KHR_texture_transform/offset",ga.offset),ys("/materials/{}/extensions/KHR_materials_transmission/transmissionTexture/extensions/KHR_texture_transform/rotation",ga.rotation),ys("/materials/{}/extensions/KHR_materials_volume/attenuationColor",[new ea(t.Animation.ANIMATIONTYPE_COLOR3,"subSurface.tintColor",zi,()=>3)]),ys("/materials/{}/extensions/KHR_materials_volume/attenuationDistance",[new ea(t.Animation.ANIMATIONTYPE_FLOAT,"subSurface.tintColorAtDistance",ji,()=>1)]),ys("/materials/{}/extensions/KHR_materials_volume/thicknessFactor",[new ea(t.Animation.ANIMATIONTYPE_FLOAT,"subSurface.maximumThickness",ji,()=>1)]);const ya=Zi("subSurface.thicknessTexture");ys("/materials/{}/extensions/KHR_materials_volume/thicknessTexture/extensions/KHR_texture_transform/scale",ya.scale),ys("/materials/{}/extensions/KHR_materials_volume/thicknessTexture/extensions/KHR_texture_transform/offset",ya.offset),ys("/materials/{}/extensions/KHR_materials_volume/thicknessTexture/extensions/KHR_texture_transform/rotation",ya.rotation),ys("/materials/{}/extensions/KHR_materials_diffuse_transmission/diffuseTransmissionFactor",[new ea(t.Animation.ANIMATIONTYPE_FLOAT,"subSurface.translucencyIntensity",ji,()=>1)]);const va=Zi("subSurface.translucencyIntensityTexture");ys("materials/{}/extensions/KHR_materials_diffuse_transmission/diffuseTransmissionTexture/extensions/KHR_texture_transform/scale",va.scale),ys("materials/{}/extensions/KHR_materials_diffuse_transmission/diffuseTransmissionTexture/extensions/KHR_texture_transform/offset",va.offset),ys("materials/{}/extensions/KHR_materials_diffuse_transmission/diffuseTransmissionTexture/extensions/KHR_texture_transform/rotation",va.rotation),ys("/materials/{}/extensions/KHR_materials_diffuse_transmission/diffuseTransmissionColorFactor",[new ea(t.Animation.ANIMATIONTYPE_COLOR3,"subSurface.translucencyColor",zi,()=>3)]);const ba=Zi("subSurface.translucencyColorTexture");ys("materials/{}/extensions/KHR_materials_diffuse_transmission/diffuseTransmissionColorTexture/extensions/KHR_texture_transform/scale",ba.scale),ys("materials/{}/extensions/KHR_materials_diffuse_transmission/diffuseTransmissionColorTexture/extensions/KHR_texture_transform/offset",ba.offset),ys("materials/{}/extensions/KHR_materials_diffuse_transmission/diffuseTransmissionColorTexture/extensions/KHR_texture_transform/rotation",ba.rotation),ys("/extensions/KHR_lights_punctual/lights/{}/color",[new ta(t.Animation.ANIMATIONTYPE_COLOR3,"diffuse",zi,()=>3)]),ys("/extensions/KHR_lights_punctual/lights/{}/intensity",[new ta(t.Animation.ANIMATIONTYPE_FLOAT,"intensity",ji,()=>1)]),ys("/extensions/KHR_lights_punctual/lights/{}/range",[new ta(t.Animation.ANIMATIONTYPE_FLOAT,"range",ji,()=>1)]),ys("/extensions/KHR_lights_punctual/lights/{}/spot/innerConeAngle",[new ta(t.Animation.ANIMATIONTYPE_FLOAT,"innerAngle",Qi,()=>1)]),ys("/extensions/KHR_lights_punctual/lights/{}/spot/outerConeAngle",[new ta(t.Animation.ANIMATIONTYPE_FLOAT,"angle",Qi,()=>1)]),ys("/extensions/EXT_lights_area/lights/{}/color",[new ta(t.Animation.ANIMATIONTYPE_COLOR3,"diffuse",zi,()=>3)]),ys("/extensions/EXT_lights_area/lights/{}/intensity",[new ta(t.Animation.ANIMATIONTYPE_FLOAT,"intensity",ji,()=>1)]),ys("/extensions/EXT_lights_area/lights/{}/size",[new ta(t.Animation.ANIMATIONTYPE_FLOAT,"radius",ji,()=>1)]),ys("/extensions/EXT_lights_area/lights/{}/rect/aspect",[new ta(t.Animation.ANIMATIONTYPE_FLOAT,"radius",ji,()=>1)]),ys("/nodes/{}/extensions/EXT_lights_ies/color",[new ta(t.Animation.ANIMATIONTYPE_COLOR3,"diffuse",zi,()=>3)]),ys("/nodes/{}/extensions/EXT_lights_ies/multiplier",[new ta(t.Animation.ANIMATIONTYPE_FLOAT,"intensity",ji,()=>1)]),ys("/nodes/{}/extensions/KHR_node_visibility/visible",[new class extends Es{buildAnimations(e,t,n,s){return e._primitiveBabylonMeshes?e._primitiveBabylonMeshes.map(e=>({babylonAnimatable:e,babylonAnimation:this._buildAnimation(t,n,s)})):[]}}(t.Animation.ANIMATIONTYPE_FLOAT,"isVisible",ji,()=>1)]),Wi();var xa={__proto__:null,KHR_animation_pointer:Ui,RegisterKHR_animation_pointer:Wi};const Ta="MSFT_audio_emitter";let Aa=class{constructor(e){this.name=Ta,this._loader=e,this.enabled=this._loader.isExtensionUsed(Ta)}dispose(){this._loader=null,this._clips=null,this._emitters=null}onLoading(){const e=this._loader.gltf.extensions;if(e&&e[this.name]){const t=e[this.name];this._clips=t.clips,this._emitters=t.emitters,Ts.Assign(this._clips),Ts.Assign(this._emitters)}}loadSceneAsync(e,t){return Ms.LoadExtensionAsync(e,t,this.name,(n,s)=>b(this,void 0,void 0,function*(){const o=new Array;o.push(this._loader.loadSceneAsync(e,t));for(const e of s.emitters){const t=Ts.Get(`${n}/emitters`,this._emitters,e);if(null!=t.refDistance||null!=t.maxDistance||null!=t.rolloffFactor||null!=t.distanceModel||null!=t.innerAngle||null!=t.outerAngle)throw new Error(`${n}: Direction or Distance properties are not allowed on emitters attached to a scene`);o.push(this._loadEmitterAsync(`${n}/emitters/${t.index}`,t))}yield Promise.all(o)}))}loadNodeAsync(e,n,s){return Ms.LoadExtensionAsync(e,n,this.name,(e,o)=>b(this,void 0,void 0,function*(){const r=new Array,i=yield this._loader.loadNodeAsync(e,n,n=>{for(const s of o.emitters){const o=Ts.Get(`${e}/emitters`,this._emitters,s);r.push(this._loadEmitterAsync(`${e}/emitters/${o.index}`,o).then(()=>{for(const e of o._babylonSounds)e.attachToMesh(n),null==o.innerAngle&&null==o.outerAngle||(e.setLocalDirectionToMesh(t.Vector3.Forward()),e.setDirectionalCone(2*t.Tools.ToDegrees(null==o.innerAngle?Math.PI:o.innerAngle),2*t.Tools.ToDegrees(null==o.outerAngle?Math.PI:o.outerAngle),0))}))}s(n)});return yield Promise.all(r),i}))}loadAnimationAsync(e,t){return Ms.LoadExtensionAsync(e,t,this.name,(n,s)=>b(this,void 0,void 0,function*(){const o=yield this._loader.loadAnimationAsync(e,t),r=new Array;Ts.Assign(s.events);for(const i of s.events)r.push(this._loadAnimationEventAsync(`${n}/events/${i.index}`,e,t,i,o));return yield Promise.all(r),o}))}_loadClipAsync(e,n){if(n._objectURL)return n._objectURL;let s;if(n.uri)s=this._loader.loadUriAsync(e,n,n.uri);else{const t=Ts.Get(`${e}/bufferView`,this._loader.gltf.bufferViews,n.bufferView);s=this._loader.loadBufferViewAsync(`/bufferViews/${t.index}`,t)}return n._objectURL=s.then(e=>{const s=t.GetBlobBufferSource(e);return URL.createObjectURL(new Blob([s],{type:n.mimeType}))}),n._objectURL}_loadEmitterAsync(e,n){if(n._babylonSounds=n._babylonSounds||[],!n._babylonData){const e=new Array,s=n.name||`emitter${n.index}`,o={loop:!1,autoplay:!1,volume:null==n.volume?1:n.volume};for(let r=0;r<n.clips.length;r++){const i=`/extensions/${this.name}/clips`,a=Ts.Get(i,this._clips,n.clips[r].clip);e.push(this._loadClipAsync(`${i}/${n.clips[r].clip}`,a).then(e=>{const i=n._babylonSounds[r]=new t.Sound(s,e,this._loader.babylonScene,null,o);i.refDistance=n.refDistance||1,i.maxDistance=n.maxDistance||256,i.rolloffFactor=n.rolloffFactor||1,i.distanceModel=n.distanceModel||"exponential"}))}const r=Promise.all(e).then(()=>{const e=n.clips.map(e=>e.weight||1),s=new t.WeightedSound(n.loop||!1,n._babylonSounds,e);n.innerAngle&&(s.directionalConeInnerAngle=2*t.Tools.ToDegrees(n.innerAngle)),n.outerAngle&&(s.directionalConeOuterAngle=2*t.Tools.ToDegrees(n.outerAngle)),n.volume&&(s.volume=n.volume),n._babylonData.sound=s});n._babylonData={loaded:r}}return n._babylonData.loaded}_getEventAction(e,t,n,s,o){switch(n){case"play":return e=>{const n=(o||0)+(e-s);t.play(n)};case"stop":return()=>{t.stop()};case"pause":return()=>{t.pause()};default:throw new Error(`${e}: Unsupported action ${n}`)}}_loadAnimationEventAsync(e,n,s,o,r){if(0==r.targetedAnimations.length)return Promise.resolve();const i=r.targetedAnimations[0],a=o.emitter,l=Ts.Get(`/extensions/${this.name}/emitters`,this._emitters,a);return this._loadEmitterAsync(e,l).then(()=>{const n=l._babylonData.sound;if(n){const s=new t.AnimationEvent(o.time,this._getEventAction(e,n,o.action,o.time,o.startOffset));i.animation.addEvent(s),r.onAnimationGroupEndObservable.add(()=>{n.stop()}),r.onAnimationGroupPauseObservable.add(()=>{n.pause()})}})}},Ma=!1;function wa(){Ma||(Ma=!0,ns(Ta),ts(Ta,!0,e=>new Aa(e)))}wa();var Ca={__proto__:null,MSFT_audio_emitter:Aa,RegisterMSFT_audio_emitter:wa};const Ra="MSFT_lod";let Sa=class{constructor(e){var n,s;this.name=Ra,this.order=100,this.maxLODsToLoad=10,this.onNodeLODsLoadedObservable=new t.Observable,this.onMaterialLODsLoadedObservable=new t.Observable,this._bufferLODs=new Array,this._nodeIndexLOD=null,this._nodeSignalLODs=new Array,this._nodePromiseLODs=new Array,this._nodeBufferLODs=new Array,this._materialIndexLOD=null,this._materialSignalLODs=new Array,this._materialPromiseLODs=new Array,this._materialBufferLODs=new Array,this._loader=e,this.maxLODsToLoad=null!==(s=null===(n=this._loader.parent.extensionOptions[Ra])||void 0===n?void 0:n.maxLODsToLoad)&&void 0!==s?s:this.maxLODsToLoad,this.enabled=this._loader.isExtensionUsed(Ra)}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++){const t=Promise.all(this._nodePromiseLODs[e]).then(()=>{0!==e&&(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++){const t=Promise.all(this._materialPromiseLODs[e]).then(()=>{0!==e&&(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){const n=this._loader.loadSceneAsync(e,t);return this._loadBufferLOD(this._bufferLODs,0),n}loadNodeAsync(e,n,s){return Ms.LoadExtensionAsync(e,n,this.name,(e,o)=>b(this,void 0,void 0,function*(){let r;const i=this._getLODs(e,n,this._loader.gltf.nodes,o.ids);this._loader.logOpen(`${e}`);for(let e=0;e<i.length;e++){const n=i[e];0!==e&&(this._nodeIndexLOD=e,this._nodeSignalLODs[e]=this._nodeSignalLODs[e]||new t.Deferred);const o=e=>{s(e),e.setEnabled(!1)},a=this._loader.loadNodeAsync(`/nodes/${n.index}`,n,o).then(t=>{if(0!==e){const t=i[e-1];t._babylonTransformNode&&(this._disposeTransformNode(t._babylonTransformNode),delete t._babylonTransformNode)}return t.setEnabled(!0),t});this._nodePromiseLODs[e]=this._nodePromiseLODs[e]||[],0===e?r=a:(this._nodeIndexLOD=null,this._nodePromiseLODs[e].push(a))}return this._loader.logClose(),yield r}))}_loadMaterialAsync(e,t,n,s,o){return this._nodeIndexLOD?null:Ms.LoadExtensionAsync(e,t,this.name,(e,r)=>b(this,void 0,void 0,function*(){let i;const a=this._getLODs(e,t,this._loader.gltf.materials,r.ids);this._loader.logOpen(`${e}`);for(let e=0;e<a.length;e++){const t=a[e];0!==e&&(this._materialIndexLOD=e);const r=this._loader._loadMaterialAsync(`/materials/${t.index}`,t,n,s,t=>{0===e&&o(t)}).then(t=>{if(0!==e){o(t);const n=a[e-1]._data;n[s]&&(this._disposeMaterials([n[s].babylonMaterial]),delete n[s])}return t});this._materialPromiseLODs[e]=this._materialPromiseLODs[e]||[],0===e?i=r:(this._materialIndexLOD=null,this._materialPromiseLODs[e].push(r))}return this._loader.logClose(),yield i}))}_loadUriAsync(e,n,s){if(null!==this._nodeIndexLOD){this._loader.log("deferred");const o=this._nodeIndexLOD-1;return this._nodeSignalLODs[o]=this._nodeSignalLODs[o]||new t.Deferred,this._nodeSignalLODs[this._nodeIndexLOD-1].promise.then(()=>b(this,void 0,void 0,function*(){return yield this._loader.loadUriAsync(e,n,s)}))}if(null!==this._materialIndexLOD){this._loader.log("deferred");const o=this._materialIndexLOD-1;return this._materialSignalLODs[o]=this._materialSignalLODs[o]||new t.Deferred,this._materialSignalLODs[o].promise.then(()=>b(this,void 0,void 0,function*(){return yield this._loader.loadUriAsync(e,n,s)}))}return null}loadBufferAsync(e,n,s,o){if(this._loader.parent.useRangeRequests&&!n.uri){if(!this._loader.bin)throw new Error(`${e}: Uri is missing or the binary glTF is missing its binary chunk`);const n=(e,n)=>b(this,void 0,void 0,function*(){const r=s,i=r+o-1;let a=e[n];return a?(a.start=Math.min(a.start,r),a.end=Math.max(a.end,i)):(a={start:r,end:i,loaded:new t.Deferred},e[n]=a),yield a.loaded.promise.then(e=>new Uint8Array(e.buffer,e.byteOffset+s-a.start,o))});return this._loader.log("deferred"),null!==this._nodeIndexLOD?n(this._nodeBufferLODs,this._nodeIndexLOD):null!==this._materialIndexLOD?n(this._materialBufferLODs,this._materialIndexLOD):n(this._bufferLODs,0)}return null}_loadBufferLOD(e,t){const 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,s){if(this.maxLODsToLoad<=0)throw new Error("maxLODsToLoad must be greater than zero");const o=[];for(let t=s.length-1;t>=0;t--)if(o.push(Ts.Get(`${e}/ids/${s[t]}`,n,s[t])),o.length===this.maxLODsToLoad)return o;return o.push(t),o}_disposeTransformNode(e){const t=[],n=e.material;n&&t.push(n);for(const n of e.getChildMeshes())n.material&&t.push(n.material);e.dispose();const s=t.filter(e=>this._loader.babylonScene.meshes.every(t=>t.material!=e));this._disposeMaterials(s)}_disposeMaterials(e){const t={};for(const n of e){for(const e of n.getActiveTextures())t[e.uniqueId]=e;n.dispose()}for(const e in t)for(const n of this._loader.babylonScene.materials)n.hasTexture(t[e])&&delete t[e];for(const e in t)t[e].dispose()}},Oa=!1;function Fa(){Oa||(Oa=!0,ns(Ra),ts(Ra,!0,e=>new Sa(e)))}Fa();var Ea={__proto__:null,MSFT_lod:Sa,RegisterMSFT_lod:Fa};const Ia="MSFT_minecraftMesh";let La=class{constructor(e){this.name=Ia,this._loader=e,this.enabled=this._loader.isExtensionUsed(Ia)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return Ms.LoadExtraAsync(e,t,this.name,(s,o)=>b(this,void 0,void 0,function*(){if(o){if(!this._loader._pbrMaterialImpls.get("pbr"))throw new Error(`${s}: Material type not supported`);const o=this._loader.loadMaterialPropertiesAsync(e,t,n);return n.needAlphaBlending()&&(n.forceDepthWrite=!0,n.separateCullingPass=!0),n.backFaceCulling=n.forceDepthWrite,n.twoSidedLighting=!0,yield o}}))}},Pa=!1;function Ba(){Pa||(Pa=!0,ns(Ia),ts(Ia,!0,e=>new La(e)))}Ba();var Na={__proto__:null,MSFT_minecraftMesh:La,RegisterMSFT_minecraftMesh:Ba};const ka="MSFT_sRGBFactors";let Da=class{constructor(e){this.name=ka,this._loader=e,this.enabled=this._loader.isExtensionUsed(ka)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return Ms.LoadExtraAsync(e,t,this.name,(s,o)=>b(this,void 0,void 0,function*(){if(o){const s=this._loader._getOrCreateMaterialAdapter(n),o=this._loader.loadMaterialPropertiesAsync(e,t,n),r=n.getScene().getEngine().useExactSrgbConversions;return s.baseColorTexture||s.baseColor.toLinearSpaceToRef(s.baseColor,r),s.specularColorTexture||s.specularColor.toLinearSpaceToRef(s.specularColor,r),yield o}}))}},Ga=!1;function Va(){Ga||(Ga=!0,ns(ka),ts(ka,!0,e=>new Da(e)))}Va();var Ha={__proto__:null,MSFT_sRGBFactors:Da,RegisterMSFT_sRGBFactors:Va};function Ka(e){const[t,n]=e.split(":");return $a({op:t,extension:n})}function $a(e,n=!0){var s;const o=e.extension?null===(s=qa[e.extension])||void 0===s?void 0:s[e.op]:Wa[e.op];if(!o&&(t.Logger.Warn(`No mapping found for operation ${e.op} and extension ${e.extension||"KHR_interactivity"}`),n)){const t={},n={flows:{}};if(e.inputValueSockets){t.values={};for(const n in e.inputValueSockets)t.values[n]={name:n}}return e.outputValueSockets&&(n.values={},Object.keys(e.outputValueSockets).forEach(e=>{n.values[e]={name:e}})),{blocks:[],inputs:t,outputs:n}}return o}function Ua(e,t,n){qa[t]||(qa[t]={}),qa[t][e]=n}const qa={BABYLON:{"flow/log":{blocks:["FlowGraphConsoleLogBlock"],inputs:{values:{message:{name:"message"}}}}}},Wa={"event/onStart":{blocks:["FlowGraphSceneReadyEventBlock"],outputs:{values:{event:{name:"event"}},flows:{out:{name:"done"}}}},"event/onTick":{blocks:["FlowGraphSceneTickEventBlock"],inputs:{},outputs:{values:{timeSinceLastTick:{name:"deltaTime",gltfType:"number"},event:{name:"event"}},flows:{out:{name:"done"}}}},"event/send":{blocks:["FlowGraphSendCustomEventBlock"],extraProcessor(e,t,n,s,o){var r;if("event/send"!==t.op||!e.configuration||1!==Object.keys(e.configuration).length)throw new Error("Receive event should have a single configuration object, the event itself");const i=null===(r=e.configuration.event.value)||void 0===r?void 0:r[0];if("number"!=typeof i)throw new Error("Event id should be a number");const a=s.arrays.events[i],l=o[0];return l.config||(l.config={}),l.config.eventId=a.eventId,l.config.eventData=a.eventData,o}},"event/receive":{blocks:["FlowGraphReceiveCustomEventBlock"],outputs:{values:{event:{name:"event"}},flows:{out:{name:"done"}}},validation(e,n){var s,o;if(!e.configuration)return t.Logger.Error("Receive event should have a configuration object"),{valid:!1,error:"Receive event should have a configuration object"};const r=e.configuration.event;if(!r)return t.Logger.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"};const i=null===(s=r.value)||void 0===s?void 0:s[0];return"number"!=typeof i?(t.Logger.Error("Event id should be a number"),{valid:!1,error:"Event id should be a number"}):(null===(o=n.events)||void 0===o?void 0:o[i])?{valid:!0}:(t.Logger.Error(`Event with id ${i} not found`),{valid:!1,error:`Event with id ${i} not found`})},extraProcessor(e,t,n,s,o){var r;if("event/receive"!==t.op||!e.configuration||1!==Object.keys(e.configuration).length)throw new Error("Receive event should have a single configuration object, the event itself");const i=null===(r=e.configuration.event.value)||void 0===r?void 0:r[0];if("number"!=typeof i)throw new Error("Event id should be a number");const a=s.arrays.events[i],l=o[0];return l.config||(l.config={}),l.config.eventId=a.eventId,l.config.eventData=a.eventData,o}},"event/stopPropagation":{blocks:["FlowGraphStopEventPropagationBlock"],inputs:{values:{event:{name:"event"},stopImmediate:{name:"stopImmediate"}},flows:{in:{name:"in"}}},outputs:{flows:{out:{name:"out"}}}},"math/E":za("FlowGraphEBlock"),"math/Pi":za("FlowGraphPIBlock"),"math/Tau":za("FlowGraphTauBlock"),"math/Inf":za("FlowGraphInfBlock"),"math/NaN":za("FlowGraphNaNBlock"),"math/abs":za("FlowGraphAbsBlock"),"math/sign":za("FlowGraphSignBlock"),"math/trunc":za("FlowGraphTruncBlock"),"math/floor":za("FlowGraphFloorBlock"),"math/ceil":za("FlowGraphCeilBlock"),"math/round":{blocks:["FlowGraphRoundBlock"],configuration:{},inputs:{values:{a:{name:"a"}}},outputs:{values:{value:{name:"value"}}},extraProcessor(e,t,n,s,o){var r;return(r=o[0]).config||(r.config={}),o[0].config.roundHalfAwayFromZero=!0,o}},"math/fract":za("FlowGraphFractBlock"),"math/neg":za("FlowGraphNegationBlock"),"math/add":za("FlowGraphAddBlock",["a","b"],!0),"math/sub":za("FlowGraphSubtractBlock",["a","b"],!0),"math/mul":{blocks:["FlowGraphMultiplyBlock"],extraProcessor(e,t,n,s,o){var r;(r=o[0]).config||(r.config={}),o[0].config.useMatrixPerComponent=!0,o[0].config.preventIntegerFloatArithmetic=!0;let i=-1;return Object.keys(e.values||{}).find(t=>{var n;return void 0!==(null===(n=e.values)||void 0===n?void 0:n[t].type)&&(i=e.values[t].type,!0)}),-1!==i&&(o[0].config.type=s.arrays.types[i].flowGraphType),o},validation:e=>e.values?ja(e):{valid:!0}},"math/div":za("FlowGraphDivideBlock",["a","b"],!0),"math/rem":za("FlowGraphModuloBlock",["a","b"]),"math/min":za("FlowGraphMinBlock",["a","b"]),"math/max":za("FlowGraphMaxBlock",["a","b"]),"math/clamp":za("FlowGraphClampBlock",["a","b","c"]),"math/saturate":za("FlowGraphSaturateBlock"),"math/mix":za("FlowGraphMathInterpolationBlock",["a","b","c"]),"math/smoothStep":za("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":za("FlowGraphMathSlerpBlock",["a","b","c"]),"math/slerp":za("FlowGraphVectorSlerpBlock",["a","b","c"]),"math/eq":za("FlowGraphEqualityBlock",["a","b"]),"ref/eq":za("FlowGraphEqualityBlock",["a","b"]),"math/lt":za("FlowGraphLessThanBlock",["a","b"]),"math/le":za("FlowGraphLessThanOrEqualBlock",["a","b"]),"math/gt":za("FlowGraphGreaterThanBlock",["a","b"]),"math/ge":za("FlowGraphGreaterThanOrEqualBlock",["a","b"]),"math/isNaN":za("FlowGraphIsNaNBlock"),"math/isInf":za("FlowGraphIsInfBlock"),"math/select":{blocks:["FlowGraphConditionalBlock"],inputs:{values:{condition:{name:"condition"},a:{name:"onTrue"},b:{name:"onFalse"}}},outputs:{values:{value:{name:"output"}}}},"math/random":{blocks:["FlowGraphRandomBlock"],outputs:{values:{value:{name:"value"}}}},"math/sin":za("FlowGraphSinBlock"),"math/cos":za("FlowGraphCosBlock"),"math/tan":za("FlowGraphTanBlock"),"math/asin":za("FlowGraphASinBlock"),"math/acos":za("FlowGraphACosBlock"),"math/atan":za("FlowGraphATanBlock"),"math/atan2":za("FlowGraphATan2Block",["a","b"]),"math/sinh":za("FlowGraphSinhBlock"),"math/cosh":za("FlowGraphCoshBlock"),"math/tanh":za("FlowGraphTanhBlock"),"math/asinh":za("FlowGraphASinhBlock"),"math/acosh":za("FlowGraphACoshBlock"),"math/atanh":za("FlowGraphATanhBlock"),"math/exp":za("FlowGraphExponentialBlock"),"math/log":za("FlowGraphLogBlock"),"math/log2":za("FlowGraphLog2Block"),"math/log10":za("FlowGraphLog10Block"),"math/sqrt":za("FlowGraphSquareRootBlock"),"math/cbrt":za("FlowGraphCubeRootBlock"),"math/pow":za("FlowGraphPowerBlock",["a","b"]),"math/length":za("FlowGraphLengthBlock"),"math/normalize":za("FlowGraphNormalizeBlock"),"math/dot":za("FlowGraphDotBlock",["a","b"]),"math/cross":za("FlowGraphCrossBlock",["a","b"]),"math/rotate2D":{blocks:["FlowGraphRotate2DBlock"],inputs:{values:{a:{name:"a"},angle:{name:"b"}}},outputs:{values:{value:{name:"value"}}}},"math/rotate3D":{blocks:["FlowGraphRotate3DBlock"],inputs:{values:{a:{name:"a"},rotation:{name:"b"}}},outputs:{values:{value:{name:"value"}}}},"math/transform":{blocks:["FlowGraphTransformVectorBlock"],inputs:{values:{a:{name:"a"},b:{name:"b"}}},outputs:{values:{value:{name:"value"}}}},"math/combine2":{blocks:["FlowGraphCombineVector2Block"],inputs:{values:{a:{name:"input_0",gltfType:"number"},b:{name:"input_1",gltfType:"number"}}},outputs:{values:{value:{name:"value"}}}},"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"}}}},"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"}}}},"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":za("FlowGraphTransposeBlock"),"math/determinant":za("FlowGraphDeterminantBlock"),"math/inverse":za("FlowGraphInvertMatrixBlock"),"math/matMul":za("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"}}},extraProcessor(e,t,n,s,o,r){const i=o[0].dataInputs.find(e=>"rotationQuaternion"===e.name);if(!i)throw new Error("Rotation quaternion input not found");return r._connectionValues[i.uniqueId]&&(r._connectionValues[i.uniqueId].type="Quaternion"),o}},"math/matDecompose":{blocks:["FlowGraphMatrixDecompose"],inputs:{values:{a:{name:"input",gltfType:"number"}}},outputs:{values:{translation:{name:"position"},rotation:{name:"rotationQuaternion"},scale:{name:"scaling"}}},extraProcessor(e,t,n,s,o){var r;return(r=o[0]).config||(r.config={}),o[0].config.keepDegenerateComponents=!0,o}},"math/quatConjugate":za("FlowGraphConjugateBlock",["a"]),"math/quatMul":{blocks:["FlowGraphMultiplyBlock"],inputs:{values:{a:{name:"a",gltfType:"vector4"},b:{name:"b",gltfType:"vector4"}}},outputs:{values:{value:{name:"value"}}},extraProcessor(e,t,n,s,o){var r;return(r=o[0]).config||(r.config={}),o[0].config.type="Quaternion",o}},"math/quatAngleBetween":za("FlowGraphAngleBetweenBlock",["a","b"]),"math/quatFromAxisAngle":{blocks:["FlowGraphQuaternionFromAxisAngleBlock"],inputs:{values:{axis:{name:"a",gltfType:"float3"},angle:{name:"b",gltfType:"number"}}},outputs:{values:{value:{name:"value"}}}},"math/quatToAxisAngle":za("FlowGraphAxisAngleFromQuaternionBlock",["a"]),"math/quatFromDirections":za("FlowGraphQuaternionFromDirectionsBlock",["a","b"]),"math/quatFromUpForward":{blocks:["FlowGraphQuaternionFromUpForwardBlock"],inputs:{values:{up:{name:"a",gltfType:"float3"},forward:{name:"b",gltfType:"float3"}}},outputs:{values:{value:{name:"value"}}}},"math/quatFromAngles":{blocks:["FlowGraphQuaternionFromAnglesBlock"],configuration:{order:{name:"order",defaultValue:["yxz"]}},inputs:{values:{x:{name:"a",gltfType:"number"},y:{name:"b",gltfType:"number"},z:{name:"c",gltfType:"number"}}},outputs:{values:{value:{name:"value"}}}},"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"}}}},"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"}}}},"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"},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"}}}},"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"}}},extraProcessor(e,t,n,s,o,r){var i,a,l;(l=o[0]).config||(l.config={});const u=o[0].dataInputs[0];return o[0].config.valueType=null!==(a=null===(i=r._connectionValues[u.uniqueId])||void 0===i?void 0:i.type)&&void 0!==a?a:"FlowGraphInteger",o}},"math/and":{blocks:["FlowGraphBitwiseAndBlock"],inputs:{values:{a:{name:"a"},b:{name:"b"}}},outputs:{values:{value:{name:"value"}}},extraProcessor(e,t,n,s,o,r){var i,a,l,u,c;(c=o[0]).config||(c.config={});const d=o[0].dataInputs[0],h=o[0].dataInputs[1];return o[0].config.valueType=null!==(u=null!==(a=null===(i=r._connectionValues[d.uniqueId])||void 0===i?void 0:i.type)&&void 0!==a?a:null===(l=r._connectionValues[h.uniqueId])||void 0===l?void 0:l.type)&&void 0!==u?u:"FlowGraphInteger",o}},"math/or":{blocks:["FlowGraphBitwiseOrBlock"],inputs:{values:{a:{name:"a"},b:{name:"b"}}},outputs:{values:{value:{name:"value"}}},extraProcessor(e,t,n,s,o,r){var i,a,l,u,c;(c=o[0]).config||(c.config={});const d=o[0].dataInputs[0],h=o[0].dataInputs[1];return o[0].config.valueType=null!==(u=null!==(a=null===(i=r._connectionValues[d.uniqueId])||void 0===i?void 0:i.type)&&void 0!==a?a:null===(l=r._connectionValues[h.uniqueId])||void 0===l?void 0:l.type)&&void 0!==u?u:"FlowGraphInteger",o}},"math/xor":{blocks:["FlowGraphBitwiseXorBlock"],inputs:{values:{a:{name:"a"},b:{name:"b"}}},outputs:{values:{value:{name:"value"}}},extraProcessor(e,t,n,s,o,r){var i,a,l,u,c;(c=o[0]).config||(c.config={});const d=o[0].dataInputs[0],h=o[0].dataInputs[1];return o[0].config.valueType=null!==(u=null!==(a=null===(i=r._connectionValues[d.uniqueId])||void 0===i?void 0:i.type)&&void 0!==a?a:null===(l=r._connectionValues[h.uniqueId])||void 0===l?void 0:l.type)&&void 0!==u?u:"FlowGraphInteger",o}},"math/asr":za("FlowGraphBitwiseRightShiftBlock",["a","b"]),"math/lsl":za("FlowGraphBitwiseLeftShiftBlock",["a","b"]),"math/clz":za("FlowGraphLeadingZerosBlock"),"math/ctz":za("FlowGraphTrailingZerosBlock"),"math/popcnt":za("FlowGraphOneBitsCounterBlock"),"math/rad":za("FlowGraphDegToRadBlock"),"math/deg":za("FlowGraphRadToDegBlock"),"type/boolToInt":za("FlowGraphBooleanToInt"),"type/boolToFloat":za("FlowGraphBooleanToFloat"),"type/intToBool":za("FlowGraphIntToBoolean"),"type/intToFloat":za("FlowGraphIntToFloat"),"type/floatToInt":za("FlowGraphFloatToInt"),"type/floatToBool":za("FlowGraphFloatToBoolean"),"flow/sequence":{blocks:["FlowGraphSequenceBlock"],extraProcessor(e,t,n,s,o){const r=o[0];return r.config||(r.config={}),r.config.outputSignalCount=Object.keys(e.flows||[]).length,r.signalOutputs.forEach((e,t)=>{e.name="out_"+t}),o}},"flow/branch":{blocks:["FlowGraphBranchBlock"],outputs:{flows:{true:{name:"onTrue"},false:{name:"onFalse"}}}},"flow/switch":{blocks:["FlowGraphSwitchBlock"],configuration:{cases:{name:"cases",isArray:!0,inOptions:!0,defaultValue:[]}},inputs:{values:{selection:{name:"case"},default:{name:"default"}}},validation(e){var n;const s=null===(n=e.configuration)||void 0===n?void 0:n.cases;if(s&&s.value){if(!s.value.every(e=>"number"==typeof e&&/^-?\d+$/.test(e.toString())))return t.Logger.Warn("Switch cases should be integers. Using empty array instead."),s.value=[],{valid:!0};const e=new Set(s.value);s.value=Array.from(e)}return{valid:!0}},extraProcessor(e,t,n,s,o){if("flow/switch"!==t.op||!e.flows||0===Object.keys(e.flows).length)throw new Error("Switch should have a single configuration object, the cases array");return o[0].signalOutputs.forEach(e=>{"default"!==e.name&&(e.name="out_"+e.name)}),o}},"flow/while":{blocks:["FlowGraphWhileLoopBlock"],outputs:{flows:{loopBody:{name:"executionFlow"}}}},"flow/for":{blocks:["FlowGraphForLoopBlock"],configuration:{initialIndex:{name:"initialIndex",gltfType:"number",inOptions:!0,defaultValue:0}},inputs:{values:{startIndex:{name:"startIndex",gltfType:"number"},endIndex:{name:"endIndex",gltfType:"number"}}},outputs:{values:{index:{name:"index"}},flows:{loopBody:{name:"executionFlow"}}},extraProcessor(e,t,n,s,o){const r=o[0];return r.config||(r.config={}),r.config.incrementIndexWhenLoopDone=!0,r.config.maxLoopIterations=2e4,o}},"flow/doN":{blocks:["FlowGraphDoNBlock"],configuration:{},inputs:{values:{n:{name:"maxExecutions",gltfType:"number"}}},outputs:{values:{currentCount:{name:"executionCount"}}}},"flow/multiGate":{blocks:["FlowGraphMultiGateBlock"],configuration:{isRandom:{name:"isRandom",gltfType:"boolean",inOptions:!0,defaultValue:!1},isLoop:{name:"isLoop",gltfType:"boolean",inOptions:!0,defaultValue:!1}},extraProcessor(e,t,n,s,o){if("flow/multiGate"!==t.op||!e.flows||0===Object.keys(e.flows).length)throw new Error("MultiGate should have a single configuration object, the number of output flows");const r=o[0];return r.config||(r.config={}),r.config.outputSignalCount=Object.keys(e.flows).length,r.signalOutputs.forEach((e,t)=>{e.name="out_"+t}),o}},"flow/waitAll":{blocks:["FlowGraphWaitAllBlock"],configuration:{inputFlows:{name:"inputSignalCount",gltfType:"number",inOptions:!0,defaultValue:0}},inputs:{flows:{reset:{name:"reset"},"[segment]":{name:"in_$1"}}},validation(e){var t,n,s;return"number"!=typeof(null===(s=null===(n=null===(t=e.configuration)||void 0===t?void 0:t.inputFlows)||void 0===n?void 0:n.value)||void 0===s?void 0:s[0])&&(e.configuration=e.configuration||{inputFlows:{value:[0]}},e.configuration.inputFlows.value=[0]),{valid:!0}}},"flow/throttle":{blocks:["FlowGraphThrottleBlock"],outputs:{flows:{err:{name:"error"}}}},"flow/setDelay":{blocks:["FlowGraphSetDelayBlock"],outputs:{flows:{err:{name:"error"}},values:{lastDelay:{name:"lastDelayIndex"}}}},"flow/cancelDelay":{blocks:["FlowGraphCancelDelayBlock"],inputs:{values:{delay:{name:"delayIndex"}}}},"variable/get":{blocks:["FlowGraphGetVariableBlock"],validation(e){var n,s;return(null===(s=null===(n=e.configuration)||void 0===n?void 0:n.variable)||void 0===s?void 0:s.value)?{valid:!0}:(t.Logger.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",flowGraphType:"string",inOptions:!0,isVariable:!0,dataTransformer:(e,t)=>t.getVariableName(e)}}},"variable/set":{blocks:["FlowGraphSetVariableBlock"],configuration:{variables:{name:"variables",gltfType:"number",flowGraphType:"string",inOptions:!0,isArray:!0,dataTransformer:(e,t)=>e.map(e=>t.getVariableName(e))}},extraProcessor:(e,t,n,s,o)=>(o[0].dataInputs.forEach(e=>{e.name=s.getVariableName(+e.name)}),o)},"variable/interpolate":{blocks:["FlowGraphInterpolationBlock","FlowGraphContextBlock","FlowGraphPlayAnimationBlock","FlowGraphBezierCurveEasing","FlowGraphGetVariableBlock"],configuration:{variable:{name:"propertyName",inOptions:!0,isVariable:!0,dataTransformer:(e,t)=>t.getVariableName(e)},useSlerp:{name:"animationType",inOptions:!0,defaultValue:!1,dataTransformer:e=>!0===e?"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,n,s,o,r){var i,a,l,u,c,d;const h=r[0],m=null===(a=null===(i=e.configuration)||void 0===i?void 0:i.variable.value)||void 0===a?void 0:a[0];if("number"!=typeof m)throw t.Logger.Error("Variable index is not defined for variable interpolation block"),new Error("Variable index is not defined for variable interpolation block");const f=o.arrays.staticVariables[m];void 0===(null===(u=null===(l=h.config)||void 0===l?void 0:l.animationType)||void 0===u?void 0:u.value)&&(h.config||(h.config={}),(c=h.config).animationType||(c.animationType={}),h.config.animationType.value=t.getAnimationTypeByFlowGraphType(f.type));const p=r[4];return p.config||(p.config={}),(d=p.config).variable||(d.variable={}),p.config.variable.value=o.getVariableName(m),r}},"pointer/get":{blocks:["FlowGraphGetPropertyBlock","FlowGraphJsonPointerParserBlock"],validation:Ya,configuration:{pointer:{name:"jsonPointer",toBlock:"FlowGraphJsonPointerParserBlock"}},inputs:{values:{"[segment]":{name:"$1",toBlock:"FlowGraphJsonPointerParserBlock"}}},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}],extraProcessor:(e,t,n,s,o)=>(o.forEach(e=>{"FlowGraphJsonPointerParserBlock"===e.className&&(e.config||(e.config={}),e.config.outputValue=!0)}),o)},"pointer/set":{blocks:["FlowGraphSetPropertyBlock","FlowGraphJsonPointerParserBlock"],validation:Ya,configuration:{pointer:{name:"jsonPointer",toBlock:"FlowGraphJsonPointerParserBlock"}},inputs:{values:{value:{name:"value"},"[segment]":{name:"$1",toBlock:"FlowGraphJsonPointerParserBlock"}}},outputs:{flows:{err:{name:"error"}}},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,s,o)=>(o.forEach(e=>{"FlowGraphJsonPointerParserBlock"===e.className&&(e.config||(e.config={}),e.config.outputValue=!0)}),o)},"pointer/interpolate":{blocks:["FlowGraphInterpolationBlock","FlowGraphJsonPointerParserBlock","FlowGraphPlayAnimationBlock","FlowGraphBezierCurveEasing"],validation:Ya,configuration:{pointer:{name:"jsonPointer",toBlock:"FlowGraphJsonPointerParserBlock"}},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,s,o)=>(o.forEach(t=>{"FlowGraphJsonPointerParserBlock"===t.className?(t.config||(t.config={}),t.config.outputValue=!0):"FlowGraphInterpolationBlock"===t.className&&(t.config||(t.config={}),Object.keys(e.values||[]).forEach(n=>{var o;const r=null===(o=e.values)||void 0===o?void 0:o[n];if("value"===n&&r){const e=r.type;void 0!==e&&(t.config.animationType=s.arrays.types[e].flowGraphType)}}))}),o)},"animation/start":{blocks:["FlowGraphPlayAnimationBlock","FlowGraphArrayIndexBlock","KHR_interactivity/FlowGraphGLTFDataProvider"],inputs:{values:{animation:{name:"index",gltfType:"number",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:{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,s,o,r,i){const a=o[o.length-1];return a.config||(a.config={}),a.config.glTF=i,o}},"animation/stop":{blocks:["FlowGraphStopAnimationBlock","FlowGraphArrayIndexBlock","KHR_interactivity/FlowGraphGLTFDataProvider"],inputs:{values:{animation:{name:"index",gltfType:"number",toBlock:"FlowGraphArrayIndexBlock"}}},outputs:{flows:{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,s,o,r,i){const a=o[o.length-1];return a.config||(a.config={}),a.config.glTF=i,o}},"animation/stopAt":{blocks:["FlowGraphStopAnimationBlock","FlowGraphArrayIndexBlock","KHR_interactivity/FlowGraphGLTFDataProvider"],configuration:{},inputs:{values:{animation:{name:"index",gltfType:"number",toBlock:"FlowGraphArrayIndexBlock"},stopTime:{name:"stopAtFrame",gltfType:"number",convertConnectedTimeToFrames:!0,dataTransformer:(e,t)=>[e[0]*t._animationTargetFps]}}},outputs:{flows:{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,s,o,r,i){const a=o[o.length-1];return a.config||(a.config={}),a.config.glTF=i,o}},"math/switch":{blocks:["FlowGraphDataSwitchBlock"],configuration:{cases:{name:"cases",isArray:!0,inOptions:!0,defaultValue:[]}},inputs:{values:{selection:{name:"case"}}},validation(e){var n;const s=null===(n=e.configuration)||void 0===n?void 0:n.cases;if(s&&s.value){if(!s.value.every(e=>"number"==typeof e&&/^-?\d+$/.test(e.toString())))return t.Logger.Warn("Switch cases should be integers. Using empty array instead."),s.value=[],{valid:!0};const e=new Set(s.value);s.value=Array.from(e)}return{valid:!0}},extraProcessor(e,t,n,s,o){const r=o[0];return r.dataInputs.forEach(e=>{"default"!==e.name&&"case"!==e.name&&(e.name="in_"+e.name)}),r.config||(r.config={}),r.config.treatCasesAsIntegers=!0,o}},"debug/log":{blocks:["FlowGraphConsoleLogBlock"],configuration:{message:{name:"messageTemplate",inOptions:!0}}}};function za(e,t=["a"],n){return{blocks:[e],inputs:{values:t.reduce((e,t)=>(e[t]={name:t},e),{})},outputs:{values:{value:{name:"value"}}},extraProcessor(e,t,s,o,r){var i;if(n){(i=r[0]).config||(i.config={}),r[0].config.preventIntegerFloatArithmetic=!0;let t=-1;Object.keys(e.values||{}).find(n=>{var s;return void 0!==(null===(s=e.values)||void 0===s?void 0:s[n].type)&&(t=e.values[n].type,!0)}),-1!==t&&(r[0].config.type=o.arrays.types[t].flowGraphType)}return r},validation:e=>n?ja(e):{valid:!0}}}function ja(e){if(e.values){const t=Object.keys(e.values).map(t=>e.values[t].type).filter(e=>void 0!==e);if(!t.every(e=>e===t[0]))return{valid:!1,error:"All inputs must be of the same type"}}return{valid:!0}}function Xa(e){for(let t=0;t<e.length;t++){const n=e[t];if(-1==="[]{}".indexOf(n))continue;let s=1;for(;e[t+s]===n;)s++;if(s%2!=0)return!0;t+=s-1}return!1}function Ya(e){var t,n,s;const o=null===(s=null===(n=null===(t=e.configuration)||void 0===t?void 0:t.pointer)||void 0===n?void 0:n.value)||void 0===s?void 0:s[0];if("string"!=typeof o)return{valid:!1,error:"A pointer operation requires a string `pointer` configuration value"};if(0!==o.length&&"/"!==o[0])return{valid:!1,error:`The JSON Pointer Template "${o}" is not a syntactically valid JSON Pointer`};const r=e=>({valid:!1,error:`The JSON Pointer Template "${o}" is invalid: ${e}`}),i=new Set;for(const e of o.split("/")){const t="["===e[0]&&"["!==e[1],n="{"===e[0]&&"{"!==e[1];if(!t&&!n){if(Xa(e))return r(`the path segment "${e}" contains an odd number of consecutive brackets`);continue}const s=t?"]":"}",o=e.substring(1,e.length-1);if(e.length<3||e[e.length-1]!==s||/[[{]/.test(o)||/[\]}]/.test(o))return r(`the template parameter path segment "${e}" is malformed`);const a=o.replace(/~1/g,"/").replace(/~0/g,"~");if(i.has(a))return r(`the template parameter "${a}" is used more than once`);i.add(a)}return{valid:!0}}function Qa(){return Object.keys(Wa)}const Za={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"}};class Ja{constructor(e,t,n=60){this._interactivityGraph=e,this._gltf=t,this._animationTargetFps=n,this._types=[],this._mappings=[],this._staticVariables=[],this._events=[],this._internalEventsCounter=0,this._nodes=[],this._insertedBlocks=[],this._parseTypes(),this._parseDeclarations(),this._parseVariables(),this._parseEvents(),this._parseNodes()}get arrays(){return{types:this._types,mappings:this._mappings,staticVariables:this._staticVariables,events:this._events,nodes:this._nodes}}_parseTypes(){if(this._interactivityGraph.types)for(const e of this._interactivityGraph.types)this._types.push(Za[e.signature])}_parseDeclarations(){if(this._interactivityGraph.declarations)for(const e of this._interactivityGraph.declarations){const n=$a(e);if(!n)throw t.Logger.Error(["No mapping found for declaration",e]),new Error("Error parsing declarations");this._mappings.push({flowGraphMapping:n,fullOperationName:e.extension?e.op+":"+e.extension:e.op})}}_parseVariables(){if(this._interactivityGraph.variables)for(const e of this._interactivityGraph.variables){const t=this._parseVariable(e);this._staticVariables.push(t)}}_parseVariable(e,n){const s=this._types[e.type];if(!s)throw t.Logger.Error(["No type found for variable",e]),new Error("Error parsing variables");if(e.value&&e.value.length!==s.length)throw t.Logger.Error(["Invalid value length for variable",e,s]),new Error("Error parsing variables");const o=e.value||[];if(!o.length)switch(s.flowGraphType){case"boolean":o.push(!1);break;case"FlowGraphInteger":o.push(0);break;case"number":o.push(NaN);break;case"string":o.push("");break;case"Vector2":o.push(NaN,NaN);break;case"Vector3":o.push(NaN,NaN,NaN);break;case"Vector4":case"Matrix2D":case"Quaternion":o.fill(NaN,0,4);break;case"Matrix":o.fill(NaN,0,16);break;case"Matrix3D":o.fill(NaN,0,9)}return"number"===s.elementType&&"string"==typeof o[0]&&(o[0]=parseFloat(o[0])),{type:s.flowGraphType,value:n?n(o,this):o}}_parseEvents(){if(this._interactivityGraph.events)for(const e of this._interactivityGraph.events){const n={eventId:e.id||"internalEvent_"+this._internalEventsCounter++};e.values&&(n.eventData=Object.keys(e.values).map(n=>{var s;const o=null===(s=e.values)||void 0===s?void 0:s[n];if(!o)throw t.Logger.Error(["No value found for event key",n]),new Error("Error parsing events");const r=this._types[o.type];if(!r)throw t.Logger.Error(["No type found for event value",o]),new Error("Error parsing events");const i=void 0!==o.value?this._parseVariable(o):void 0;return{id:n,type:r.flowGraphType,eventData:!0,value:i}})),this._events.push(n)}}_parseNodes(){var e;if(this._interactivityGraph.nodes)for(const n of this._interactivityGraph.nodes){if("number"!=typeof n.declaration)throw t.Logger.Error(["No declaration found for node",n]),new Error("Error parsing nodes");const s=this._mappings[n.declaration];if(!s)throw t.Logger.Error(["No mapping found for node",n]),new Error("Error parsing nodes");if(s.flowGraphMapping.validation){const t=s.flowGraphMapping.validation(n,this._interactivityGraph,this._gltf);if(!t.valid)throw new Error(`Error validating interactivity node ${null===(e=this._interactivityGraph.declarations)||void 0===e?void 0:e[n.declaration].op} - ${t.error}`)}const o=[];for(const e of s.flowGraphMapping.blocks){const t=this._getEmptyBlock(e,s.fullOperationName);this._parseNodeConfiguration(n,t,s.flowGraphMapping,e),o.push(t)}this._nodes.push({blocks:o,fullOperationName:s.fullOperationName})}}_getEmptyBlock(e,n){return{uniqueId:t.RandomGUID(),className:e,dataInputs:[],dataOutputs:[],signalInputs:[],signalOutputs:[],config:{},type:n,metadata:{}}}_parseNodeConfiguration(e,n,s,o){var r;const i=e.configuration;if(i)for(const e in i){const a=i[e];if(!a)throw new Error("Error parsing node configuration");const l=null===(r=s.configuration)||void 0===r?void 0:r[e];if(l&&l.toBlock?l.toBlock===o:0===s.blocks.indexOf(o)){let s=null==l?void 0:l.defaultValue;(null==a?void 0:a.value)&&(s=a.value),(null==l?void 0:l.isArray)||(1!==s.length&&t.Logger.Warn(`Invalid non-array value length: ${s.length}`),s=s[0]),(null==l?void 0:l.dataTransformer)&&(s=l.dataTransformer(s,this)),void 0!==s&&(n.config[(null==l?void 0:l.name)||e]={value:s})}}}_parseNodeConnections(e){var n,s,o,r,i,a,l,u,c,d,h,m,f,p,_,g,y,v,b;for(let x=0;x<this._nodes.length;x++){const T=null===(n=this._interactivityGraph.nodes)||void 0===n?void 0:n[x];if(!T)throw t.Logger.Error(["No node found for interactivity node",this._nodes[x]]),new Error("Error parsing node connections");const A=this._nodes[x],M=this._mappings[T.declaration];if(!M)throw t.Logger.Error(["No mapping found for node",T]),new Error("Error parsing node connections");if(0===A.blocks.length){t.Logger.Warn(`Skipping connections for no-op node #${x} (unsupported operation: ${A.fullOperationName})`);continue}const w=T.flows||{},C=Object.keys(w).sort();for(const e of C){const n=w[e],c=null===(o=null===(s=M.flowGraphMapping.outputs)||void 0===s?void 0:s.flows)||void 0===o?void 0:o[e],d=(null==c?void 0:c.name)||e,h=n.node,m=this._nodes[h];if(!m)throw t.Logger.Error(["No node found for input node id",h]),new Error("Error parsing node connections");if(0===m.blocks.length){t.Logger.Warn(`Dropping flow connection from node #${x} "${e}" to no-op node #${h} (unsupported operation: ${m.fullOperationName})`);continue}const f=this._createNewSocketConnection(d,!0);(c&&c.toBlock&&A.blocks.find(e=>e.className===c.toBlock)||A.blocks[0]).signalOutputs.push(f);const p=Ka(m.fullOperationName);if(!p)throw t.Logger.Error(["No mapping found for input node",m]),new Error("Error parsing node connections");let _=null===(i=null===(r=p.inputs)||void 0===r?void 0:r.flows)||void 0===i?void 0:i[n.socket||"in"],g=!1;if(!_)for(const e in null===(a=p.inputs)||void 0===a?void 0:a.flows)e.startsWith("[")&&e.endsWith("]")&&(g=!0,_=null===(u=null===(l=p.inputs)||void 0===l?void 0:l.flows)||void 0===u?void 0:u[e]);const y=_?g?_.name.replace("$1",n.socket||""):_.name:n.socket||"in",v=_&&_.toBlock&&m.blocks.find(e=>e.className===_.toBlock)||m.blocks[0];let b=v.signalInputs.find(e=>e.name===y);b||(b=this._createNewSocketConnection(y),v.signalInputs.push(b)),b.connectedPointIds.push(f.uniqueId),f.connectedPointIds.push(b.uniqueId)}const R=T.values||{},S=Object.keys(R);for(const n of S){const s=R[n];let o=null===(d=null===(c=M.flowGraphMapping.inputs)||void 0===c?void 0:c.values)||void 0===d?void 0:d[n],r=!1;if(!o)for(const e in null===(h=M.flowGraphMapping.inputs)||void 0===h?void 0:h.values)e.startsWith("[")&&e.endsWith("]")&&(r=!0,o=null===(f=null===(m=M.flowGraphMapping.inputs)||void 0===m?void 0:m.values)||void 0===f?void 0:f[e]);const i=o?r?o.name.replace("$1",n):o.name:n,a=this._createNewSocketConnection(i);(o&&o.toBlock&&A.blocks.find(e=>e.className===o.toBlock)||A.blocks[0]).dataInputs.push(a);const l=!!(null==o?void 0:o.convertConnectedTimeToFrames);if(void 0!==s.value){const t=this._parseVariable(s,o&&o.dataTransformer);e._connectionValues[a.uniqueId]=t}else{if(void 0===s.node)throw t.Logger.Error(["Invalid value for value connection",s]),new Error("Error parsing node connections");{const o=s.node,r=s.socket||"value",i=this._nodes[o];if(!i)throw t.Logger.Error(["No node found for output socket reference",s]),new Error("Error parsing node connections");if(0===i.blocks.length){t.Logger.Warn(`Dropping value connection from no-op node #${o} (unsupported operation: ${i.fullOperationName}) into node #${x} "${n}"; consumer will use type-default value`);continue}const u=Ka(i.fullOperationName);if(!u)throw t.Logger.Error(["No mapping found for output socket reference",s]),new Error("Error parsing node connections");let c=null===(_=null===(p=u.outputs)||void 0===p?void 0:p.values)||void 0===_?void 0:_[r],d=!1;if(!c)for(const e in null===(g=u.outputs)||void 0===g?void 0:g.values)e.startsWith("[")&&e.endsWith("]")&&(d=!0,c=null===(v=null===(y=u.outputs)||void 0===y?void 0:y.values)||void 0===v?void 0:v[e]);const h=c?d?c.name.replace("$1",r):null==c?void 0:c.name:r,m=c&&c.toBlock&&i.blocks.find(e=>e.className===c.toBlock)||i.blocks[0];let f=m.dataOutputs.find(e=>e.name===h);f||(f=this._createNewSocketConnection(h,!0),m.dataOutputs.push(f)),l?this._connectWithSecondsToFramesConversion(e,f,a):(a.connectedPointIds.push(f.uniqueId),f.connectedPointIds.push(a.uniqueId))}}}if(M.flowGraphMapping.interBlockConnectors)for(const e of M.flowGraphMapping.interBlockConnectors){const t=e.input,n=e.output,s=e.isVariable;this._connectFlowGraphNodes(t,n,A.blocks[e.inputBlockIndex],A.blocks[e.outputBlockIndex],s)}if(M.flowGraphMapping.extraProcessor){const n=null===(b=this._interactivityGraph.declarations)||void 0===b?void 0:b[T.declaration];if(!n)throw t.Logger.Error(["No declaration found for extra processor",T]),new Error("Error parsing node connections");A.blocks=M.flowGraphMapping.extraProcessor(T,n,M.flowGraphMapping,this,A.blocks,e,this._gltf)}}}_createNewSocketConnection(e,n){return{uniqueId:t.RandomGUID(),name:e,_connectionType:n?1:0,connectedPointIds:[]}}_connectWithSecondsToFramesConversion(e,t,n){const s=this._getEmptyBlock("FlowGraphMultiplyBlock","FlowGraphMultiplyBlock");s.config={type:"number"};const o=this._createNewSocketConnection("a"),r=this._createNewSocketConnection("b"),i=this._createNewSocketConnection("value",!0);s.dataInputs.push(o,r),s.dataOutputs.push(i),e._connectionValues[r.uniqueId]={type:"number",value:[this._animationTargetFps]},o.connectedPointIds.push(t.uniqueId),t.connectedPointIds.push(o.uniqueId),n.connectedPointIds.push(i.uniqueId),i.connectedPointIds.push(n.uniqueId),this._insertedBlocks.push(s)}_connectFlowGraphNodes(e,t,n,s,o){const r=o?n.dataInputs:n.signalInputs,i=o?s.dataOutputs:s.signalOutputs,a=r.find(t=>t.name===e)||this._createNewSocketConnection(e),l=i.find(e=>e.name===t)||this._createNewSocketConnection(t,!0);r.find(t=>t.name===e)||r.push(a),i.find(e=>e.name===t)||i.push(l),a.connectedPointIds.push(l.uniqueId),l.connectedPointIds.push(a.uniqueId)}getVariableName(e){return"staticVariable_"+e}serializeToFlowGraph(){const e={uniqueId:t.RandomGUID(),_userVariables:{},_connectionValues:{}};this._parseNodeConnections(e);for(let t=0;t<this._staticVariables.length;t++){const n=this._staticVariables[t];e._userVariables[this.getVariableName(t)]=n}return{rightHanded:!0,allBlocks:this._nodes.reduce((e,t)=>e.concat(t.blocks),[]).concat(this._insertedBlocks),executionContexts:[e]}}}class el{constructor(e,t){this._prefixes=e,this._fallback=t}addPrefix(e){this._prefixes.unshift(e)}convert(e){for(const{prefix:t,converter:n}of this._prefixes)if(e.startsWith(t))return n.convert(e);return this._fallback.convert(e)}}const tl="/extensions/BABYLON_scene_objects/";class nl{constructor(e,t){this._scene=e,this._tree=t}convert(e){if(!e.startsWith(tl))throw new Error(`BabylonScenePathToObjectConverter: path "${e}" does not start with the expected prefix "${tl}".`);const t=e.slice(34).split("/").filter(e=>e.length>0);if(0===t.length)throw new Error(`BabylonScenePathToObjectConverter: path "${e}" is missing a collection name.`);const n=t[0],s=this._tree[n];if(!s)throw new Error(`BabylonScenePathToObjectConverter: unknown collection "${n}" in path "${e}".`);if(2===t.length&&"length"===t[1])return{object:this._getCollectionArray(n),info:s.length};if(t.length<2)throw new Error(`BabylonScenePathToObjectConverter: path "${e}" is missing an instance id.`);if(!/^\d+$/.test(t[1]))throw new Error(`BabylonScenePathToObjectConverter: invalid uniqueId "${t[1]}" in path "${e}".`);const o=parseInt(t[1],10);if(!Number.isFinite(o)||o<0)throw new Error(`BabylonScenePathToObjectConverter: invalid uniqueId "${t[1]}" in path "${e}".`);const r=this._lookupInstanceByUniqueId(n,o);if(!r)throw new Error(`BabylonScenePathToObjectConverter: no ${n} instance found with uniqueId ${o} (path "${e}").`);if(2===t.length)return{object:r,info:this._buildIdentityAccessor(r)};if(t.length>3)throw new Error(`BabylonScenePathToObjectConverter: nested property paths are not yet supported (path "${e}").`);const i=t[2],a=s.__array__[i];if(!a||"boolean"==typeof a)throw new Error(`BabylonScenePathToObjectConverter: property "${i}" is not registered on ${n} (path "${e}").`);return{object:r,info:a}}_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}}}const sl="/extensions/KHR_interactivity/events/";const ol={isKhrInteractivityRef:!0};class rl{convert(e){const n=e.endsWith("/")?e.slice(0,-1):e;if(n.startsWith(sl)){const e=n.substring(37);return{object:ol,info:{type:"object",isReadOnly:!0,get:()=>e.length>0?n:void 0,getTarget:()=>ol}}}const s=n.substring(37),o=/^\d+$/.test(s)?parseInt(s,10):NaN;return{object:ol,info:{type:"object",isReadOnly:!0,get:(e,n,s)=>{const r=s;if(!(!r||isNaN(o)||o<0))return t.IsDelayActive(r,o)?new t.FlowGraphInteger(o):void 0},getTarget:()=>ol}}}}const il="/extensions/KHR_interactivity/limits/",al={major:2,minor:0},ll=2147483647,ul={maxActiveAnimations:ll,maxActiveDelays:ll,maxActivePropertyInterpolations:ll,maxActiveVariableInterpolations:ll},cl={isKhrInteractivityAssetCapability:!0};class dl{constructor(e,t){this._gltf=e,this._isExtensionEnabled=t}convert(e){const t=e.endsWith("/")?e.slice(0,-1):e;if(t.startsWith(il)){const n=ul[t.substring(37)];if(void 0===n)throw new Error(`Path ${e} is invalid`);return this._createAccessor("number",()=>n)}const n=t.substring(36);if("majorVersion"===n||"minorVersion"===n)return this._createAccessor("number",()=>{var e;return function(e){const[t,n]=(null!=e?e:"").split("."),s=parseInt(t,10),o=parseInt(n,10);return isNaN(s)?al:s!==al.major?s<al.major?{major:s,minor:isNaN(o)?0:o}:al:{major:s,minor:Math.min(isNaN(o)?0:o,al.minor)}}(null===(e=this._gltf.asset)||void 0===e?void 0:e.version)["majorVersion"===n?"major":"minor"]});const s=n.split("/");if(3===s.length&&"extensions"===s[0]&&"enabled"===s[2]){const e=s[1];return this._createAccessor("boolean",()=>this._isExtensionEnabled(e))}throw new Error(`Path ${e} is invalid`)}_createAccessor(e,t){return{object:cl,info:{type:e,isReadOnly:!0,get:t,getTarget:()=>cl}}}}class hl{encodeEventReference(e){return function(e){return sl+e}(e)}decodeEventReference(e){return function(e){return"string"==typeof(t=e)&&t.startsWith(sl)?e.substring(37):void 0;var t}(e)}decodeIndexReference(e){if(0===e.length||"/"!==e[0])return;const t=e.substring(e.lastIndexOf("/")+1);return/^(0|[1-9]\d*)$/.test(t)?parseInt(t,10):void 0}getObjectReference(e,t){var n,s;const o=null===(s=null===(n=e._internalMetadata)||void 0===n?void 0:n.gltf)||void 0===s?void 0:s.pointers;if(!Array.isArray(o))return;const r=o.filter(e=>"string"==typeof e);if(0!==r.length){if(t){const e=r.find(e=>e.split("/")[1]===t);if(e)return e}return r[0]}}}const ml="KHR_interactivity";let fl=class{constructor(e){var n;this._loader=e,this.name=ml,this.enabled=this._loader.isExtensionUsed(ml),this._gltfPathConverter=_s(this._loader.gltf);const s=e.babylonScene;if(this._gltfPathConverter){const e=[];s&&e.push({prefix:tl,converter:new nl(s,{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=>{var n;return null!==(n=e.rotationQuaternion)&&void 0!==n?n:t.Quaternion.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}}}})});const o=new rl;e.push({prefix:sl,converter:o}),e.push({prefix:"/extensions/KHR_interactivity/delays/",converter:o});const r=new Set((null!==(n=this._loader.gltf.extensionsUsed)&&void 0!==n?n:[]).filter(e=>{var t;return es.has(e)&&!1!==(null===(t=this._loader.parent.extensionOptions[e])||void 0===t?void 0:t.enabled)})),i=new dl(this._loader.gltf,e=>r.has(e));e.push({prefix:"/extensions/KHR_interactivity/asset/",converter:i}),e.push({prefix:il,converter:i}),this._pathConverter=new el(e,this._gltfPathConverter)}e._skipStartAnimationStep=!0,s&&pl(s)}dispose(){this._loader=null,delete this._gltfPathConverter,delete this._pathConverter}onReady(){return b(this,void 0,void 0,function*(){var e;if(!this._loader.babylonScene||!this._pathConverter)return;const n=this._loader.babylonScene,s=null===(e=this._loader.gltf.extensions)||void 0===e?void 0:e.KHR_interactivity;s&&(yield Promise.all(s.graphs.map((e,s)=>b(this,void 0,void 0,function*(){var o;const r=new t.FlowGraphCoordinator({scene:n,hostResolver:new hl});r.dispatchEventsSynchronously=!1;try{const n=new Ja(e,this._loader.gltf,this._loader.parent.targetFps);yield t.ParseFlowGraphAsync(n.serializeToFlowGraph(),{coordinator:r,pathConverter:this._pathConverter}),r.start()}catch(e){t.Logger.Error(`KHR_interactivity: rejecting behavior graph #${s}: ${null!==(o=null==e?void 0:e.message)&&void 0!==o?o:e}`),r.dispose()}}))))})}};function pl(e){vs("/extensions/KHR_interactivity/?/activeCamera/rotation",{get:()=>{if(!e.activeCamera)return new t.Quaternion(NaN,NaN,NaN,NaN);const n=t.Quaternion.FromRotationMatrix(e.activeCamera.getWorldMatrix()).normalize();return e.useRightHandedSystem||(n.w*=-1,n.x*=-1),n},type:"Quaternion",getTarget:()=>e.activeCamera}),vs("/extensions/KHR_interactivity/?/activeCamera/position",{get:()=>{if(!e.activeCamera)return new t.Vector3(NaN,NaN,NaN);const n=e.activeCamera.getWorldMatrix().getTranslation();return e.useRightHandedSystem||(n.x*=-1),n},type:"Vector3",getTarget:()=>e.activeCamera});const n=n=>{const s=e.activeCamera;return s&&s.mode!==t.Constants.ORTHOGRAPHIC_CAMERA?n(s):NaN},s=n=>{const s=e.activeCamera;return s&&s.mode===t.Constants.ORTHOGRAPHIC_CAMERA?n(s):NaN};vs("/extensions/KHR_interactivity/?/activeCamera/perspective/aspectRatio",{get:()=>n(e=>e.getEngine().getAspectRatio(e)),type:"number",getTarget:()=>e.activeCamera}),vs("/extensions/KHR_interactivity/?/activeCamera/perspective/yfov",{get:()=>n(e=>{if(e.fovMode===t.Constants.FOVMODE_VERTICAL_FIXED)return e.fov;const n=e.getEngine().getAspectRatio(e);return n?2*Math.atan(Math.tan(e.fov/2)/n):e.fov}),type:"number",getTarget:()=>e.activeCamera}),vs("/extensions/KHR_interactivity/?/activeCamera/perspective/znear",{get:()=>n(e=>e.minZ),type:"number",getTarget:()=>e.activeCamera}),vs("/extensions/KHR_interactivity/?/activeCamera/perspective/zfar",{get:()=>n(e=>0===e.maxZ?1/0:e.maxZ),type:"number",getTarget:()=>e.activeCamera}),vs("/extensions/KHR_interactivity/?/activeCamera/orthographic/xmag",{get:()=>s(e=>{var t,n;const s=e.getEngine().getRenderWidth()/2;return((null!==(t=e.orthoRight)&&void 0!==t?t:s)-(null!==(n=e.orthoLeft)&&void 0!==n?n:-s))/2}),type:"number",getTarget:()=>e.activeCamera}),vs("/extensions/KHR_interactivity/?/activeCamera/orthographic/ymag",{get:()=>s(e=>{var t,n;const s=e.getEngine().getRenderHeight()/2;return((null!==(t=e.orthoTop)&&void 0!==t?t:s)-(null!==(n=e.orthoBottom)&&void 0!==n?n:-s))/2}),type:"number",getTarget:()=>e.activeCamera}),vs("/extensions/KHR_interactivity/?/activeCamera/orthographic/znear",{get:()=>s(e=>e.minZ),type:"number",getTarget:()=>e.activeCamera}),vs("/extensions/KHR_interactivity/?/activeCamera/orthographic/zfar",{get:()=>s(e=>e.maxZ),type:"number",getTarget:()=>e.activeCamera}),vs("/animations/{}/extensions/KHR_interactivity/isPlaying",{get:e=>{var t,n;return null!==(n=null===(t=e._babylonAnimationGroup)||void 0===t?void 0:t.isPlaying)&&void 0!==n&&n},type:"boolean",getTarget:e=>e._babylonAnimationGroup}),vs("/animations/{}/extensions/KHR_interactivity/minTime",{get:e=>{var t,n;return(null!==(n=null===(t=e._babylonAnimationGroup)||void 0===t?void 0:t.from)&&void 0!==n?n:0)/60},type:"number",getTarget:e=>e._babylonAnimationGroup}),vs("/animations/{}/extensions/KHR_interactivity/maxTime",{get:e=>{var t,n;return(null!==(n=null===(t=e._babylonAnimationGroup)||void 0===t?void 0:t.to)&&void 0!==n?n:0)/60},type:"number",getTarget:e=>e._babylonAnimationGroup}),vs("/animations/{}/extensions/KHR_interactivity/playhead",{get:e=>{var t,n;return(null!==(n=null===(t=e._babylonAnimationGroup)||void 0===t?void 0:t.getCurrentFrame())&&void 0!==n?n:0)/60},type:"number",getTarget:e=>e._babylonAnimationGroup}),vs("/animations/{}/extensions/KHR_interactivity/virtualPlayhead",{get:e=>{var t,n;return(null!==(n=null===(t=e._babylonAnimationGroup)||void 0===t?void 0:t.getCurrentFrame())&&void 0!==n?n:0)/60},type:"number",getTarget:e=>e._babylonAnimationGroup})}let _l=!1;function gl(){_l||(_l=!0,t.addToBlockFactory(ml,"FlowGraphGLTFDataProvider",()=>b(this,void 0,void 0,function*(){return(yield Promise.resolve().then(function(){return Kl})).FlowGraphGLTFDataProvider})),ns(ml),ts(ml,!0,e=>new fl(e)))}gl();var yl={__proto__:null,KHR_interactivity:fl,RegisterKHR_interactivity:gl,_AddInteractivityObjectModel:pl};const vl="KHR_node_visibility";let bl=class{constructor(e){this.name=vl,this._loader=e,this.enabled=e.isExtensionUsed(vl)}onReady(){var e;if(!this._loader)return;const t=this._loader.gltf.nodes;if(t)for(const n of t){const t=n._babylonTransformNode;t&&(t.inheritVisibility=!0,n.extensions&&n.extensions.KHR_node_visibility&&!1===n.extensions.KHR_node_visibility.visible&&(t.isVisible=!1,null===(e=n._primitiveBabylonMeshes)||void 0===e||e.forEach(e=>{e.inheritVisibility=!0,e.isVisible=!1})))}}dispose(){delete this._loader}},xl=!1;function Tl(){xl||(xl=!0,vs("/nodes/{}/extensions/KHR_node_visibility/visible",{get:e=>{const t=e._babylonTransformNode;return!t||void 0===t.isVisible||t.isVisible},set:(e,t)=>{var n,s;null===(n=t._primitiveBabylonMeshes)||void 0===n||n.forEach(e=>{e.inheritVisibility=!0}),t._babylonTransformNode&&(t._babylonTransformNode.isVisible=e),null===(s=t._primitiveBabylonMeshes)||void 0===s||s.forEach(t=>{t.isVisible=e})},getTarget:e=>e._babylonTransformNode,getPropertyName:[()=>"isVisible"],type:"boolean"}),ns(vl),ts(vl,!0,e=>new bl(e)))}Tl();var Al={__proto__:null,KHR_node_visibility:bl,RegisterKHR_node_visibility:Tl};const Ml="KHR_node_selectability";let wl=class{constructor(e){this.name=Ml,this._loader=e,this.enabled=e.isExtensionUsed(Ml)}onReady(){return b(this,void 0,void 0,function*(){var e;null===(e=this._loader.gltf.nodes)||void 0===e||e.forEach(e=>{var t,n,s;(null===(t=e.extensions)||void 0===t?void 0:t.KHR_node_selectability)&&!1===(null===(n=e.extensions)||void 0===n?void 0:n.KHR_node_selectability.selectable)&&(null===(s=e._babylonTransformNode)||void 0===s||s.getChildMeshes().forEach(e=>{e.isPickable=!1}))})})}dispose(){this._loader=null}},Cl=!1;function Rl(){Cl||(Cl=!0,Ua("event/onSelect",Ml,{blocks:["FlowGraphMeshPickEventBlock","FlowGraphGetVariableBlock","FlowGraphIndexOfBlock","KHR_interactivity/FlowGraphGLTFDataProvider"],configuration:{stopPropagation:{name:"stopPropagation"},nodeIndex:{name:"variable",toBlock:"FlowGraphGetVariableBlock",dataTransformer:e=>"pickedMesh_"+e}},outputs:{values:{selectedNodeIndex:{name:"index",toBlock:"FlowGraphIndexOfBlock"},selectedNode:{name:"pickedMesh",toBlock:"FlowGraphMeshPickEventBlock"},controllerIndex:{name:"pointerId"},selectionPoint:{name:"pickedPoint"},selectionRayOrigin:{name:"pickOrigin"}},flows:{out:{name:"done"}}},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}],extraProcessor(e,t,n,s,o,r,i){var a,l,u,c,d,h,m;const f=o[o.length-1];f.config=f.config||{},f.config.glTF=i;const p=null===(u=null===(l=null===(a=e.configuration)||void 0===a?void 0:a.nodeIndex)||void 0===l?void 0:l.value)||void 0===u?void 0:u[0];if(void 0===p||"number"!=typeof p)throw new Error("nodeIndex not found in configuration");const _="pickedMesh_"+p;return o[1].config.variable=_,r._userVariables[_]={className:"Mesh",id:null===(d=null===(c=null==i?void 0:i.nodes)||void 0===c?void 0:c[p]._babylonTransformNode)||void 0===d?void 0:d.id,uniqueId:null===(m=null===(h=null==i?void 0:i.nodes)||void 0===h?void 0:h[p]._babylonTransformNode)||void 0===m?void 0:m.uniqueId},o}}),vs("/nodes/{}/extensions/KHR_node_selectability/selectable",{get:e=>{const t=e._babylonTransformNode;return!t||void 0===t.isPickable||t.isPickable},set:(e,t)=>{var n;null===(n=t._primitiveBabylonMeshes)||void 0===n||n.forEach(t=>{t.isPickable=e})},getTarget:e=>e._babylonTransformNode,getPropertyName:[()=>"isPickable"],type:"boolean"}),ns(Ml),ts(Ml,!0,e=>new wl(e)))}Rl();var Sl={__proto__:null,KHR_node_selectability:wl,RegisterKHR_node_selectability:Rl};const Ol="KHR_node_hoverability",Fl="targetMeshPointerOver_",El="targetMeshPointerOut_";let Il=class{constructor(e){this.name=Ol,this._loader=e,this.enabled=e.isExtensionUsed(Ol)}onReady(){return b(this,void 0,void 0,function*(){var e;null===(e=this._loader.gltf.nodes)||void 0===e||e.forEach(e=>{var t,n,s;(null===(t=e.extensions)||void 0===t?void 0:t.KHR_node_hoverability)&&!1===(null===(n=e.extensions)||void 0===n?void 0:n.KHR_node_hoverability.hoverable)&&(null===(s=e._babylonTransformNode)||void 0===s||s.getChildMeshes().forEach(e=>{e.pointerOverDisableMeshTesting=!0}))})})}dispose(){this._loader=null}},Ll=!1;function Pl(){Ll||(Ll=!0,Ua("event/onHoverIn",Ol,{blocks:["FlowGraphPointerOverEventBlock","FlowGraphGetVariableBlock","FlowGraphIndexOfBlock","KHR_interactivity/FlowGraphGLTFDataProvider"],configuration:{stopPropagation:{name:"stopPropagation"},nodeIndex:{name:"variable",toBlock:"FlowGraphGetVariableBlock",dataTransformer:e=>Fl+e}},outputs:{values:{hoverNodeIndex:{name:"index",toBlock:"FlowGraphIndexOfBlock"},hoveredNode:{name:"meshUnderPointer",toBlock:"FlowGraphPointerOverEventBlock"},controllerIndex:{name:"pointerId"}},flows:{out:{name:"done"}}},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}],extraProcessor(e,t,n,s,o,r,i){var a,l,u,c,d,h,m;const f=o[o.length-1];f.config=f.config||{},f.config.glTF=i;const p=null===(u=null===(l=null===(a=e.configuration)||void 0===a?void 0:a.nodeIndex)||void 0===l?void 0:l.value)||void 0===u?void 0:u[0];if(void 0===p||"number"!=typeof p)throw new Error("nodeIndex not found in configuration");const _=Fl+p;return o[1].config.variable=_,r._userVariables[_]={className:"Mesh",id:null===(d=null===(c=null==i?void 0:i.nodes)||void 0===c?void 0:c[p]._babylonTransformNode)||void 0===d?void 0:d.id,uniqueId:null===(m=null===(h=null==i?void 0:i.nodes)||void 0===h?void 0:h[p]._babylonTransformNode)||void 0===m?void 0:m.uniqueId},o}}),Ua("event/onHoverOut",Ol,{blocks:["FlowGraphPointerOutEventBlock","FlowGraphGetVariableBlock","FlowGraphIndexOfBlock","KHR_interactivity/FlowGraphGLTFDataProvider"],configuration:{stopPropagation:{name:"stopPropagation"},nodeIndex:{name:"variable",toBlock:"FlowGraphGetVariableBlock",dataTransformer:e=>El+e}},outputs:{values:{hoverNodeIndex:{name:"index",toBlock:"FlowGraphIndexOfBlock"},hoveredNode:{name:"meshOutOfPointer",toBlock:"FlowGraphPointerOutEventBlock"},controllerIndex:{name:"pointerId"}},flows:{out:{name:"done"}}},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}],extraProcessor(e,t,n,s,o,r,i){var a,l,u,c,d,h,m;const f=o[o.length-1];f.config=f.config||{},f.config.glTF=i;const p=null===(u=null===(l=null===(a=e.configuration)||void 0===a?void 0:a.nodeIndex)||void 0===l?void 0:l.value)||void 0===u?void 0:u[0];if(void 0===p||"number"!=typeof p)throw new Error("nodeIndex not found in configuration");const _=El+p;return o[1].config.variable=_,r._userVariables[_]={className:"Mesh",id:null===(d=null===(c=null==i?void 0:i.nodes)||void 0===c?void 0:c[p]._babylonTransformNode)||void 0===d?void 0:d.id,uniqueId:null===(m=null===(h=null==i?void 0:i.nodes)||void 0===h?void 0:h[p]._babylonTransformNode)||void 0===m?void 0:m.uniqueId},o}}),vs("/nodes/{}/extensions/KHR_node_hoverability/hoverable",{get:e=>{const t=e._babylonTransformNode;return!t||void 0===t.pointerOverDisableMeshTesting||t.pointerOverDisableMeshTesting},set:(e,t)=>{var n;null===(n=t._primitiveBabylonMeshes)||void 0===n||n.forEach(t=>{t.pointerOverDisableMeshTesting=!e})},getTarget:e=>e._babylonTransformNode,getPropertyName:[()=>"pointerOverDisableMeshTesting"],type:"boolean"}),ns(Ol),ts(Ol,!0,e=>new Il(e)))}Pl();var Bl={__proto__:null,KHR_node_hoverability:Il,RegisterKHR_node_hoverability:Pl};const Nl="ExtrasAsMetadata";let kl=class{_assignExtras(e,t){if(t.extras&&Object.keys(t.extras).length>0){const n=e.metadata=e.metadata||{};(n.gltf=n.gltf||{}).extras=t.extras}}constructor(e){this.name=Nl,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){const s=this._loader.createMaterial(e,t,n);return this._assignExtras(s,t),s}loadAnimationAsync(e,t){return this._loader.loadAnimationAsync(e,t).then(e=>(this._assignExtras(e,t),e))}},Dl=!1;function Gl(){Dl||(Dl=!0,ns(Nl),ts(Nl,!1,e=>new kl(e)))}Gl();var Vl={__proto__:null,ExtrasAsMetadata:kl,RegisterExtrasAsMetadata:Gl};class Hl extends t.FlowGraphBlock{constructor(e){var n,s;super(e);const o=e.glTF,r=(null===(n=null==o?void 0:o.animations)||void 0===n?void 0:n.map(e=>e._babylonAnimationGroup))||[];this.animationGroups=this.registerDataOutput("animationGroups",t.RichTypeAny,r);const i=(null===(s=null==o?void 0:o.nodes)||void 0===s?void 0:s.map(e=>e._babylonTransformNode))||[];this.nodes=this.registerDataOutput("nodes",t.RichTypeAny,i)}getClassName(){return"FlowGraphGLTFDataProvider"}}var Kl={__proto__:null,FlowGraphGLTFDataProvider:Hl},$l={__proto__:null,AddObjectAccessorToKey:vs,EXT_lights_area:Bo,EXT_lights_ies:ho,EXT_lights_image_based:Vs,EXT_mesh_gpu_instancing:qs,EXT_meshopt_compression:Ys,EXT_texture_avif:io,EXT_texture_webp:to,ExtrasAsMetadata:kl,FlowGraphGLTFDataProvider:Hl,GetMappingForKey:gs,GetPathToObjectConverter:_s,InteractivityGraphToFlowGraphParser:Ja,KHR_animation_pointer:Ui,KHR_draco_mesh_compression:go,KHR_gaussian_splatting:wo,KHR_interactivity:fl,KHR_lights:Fo,KHR_materials_anisotropy:dr,KHR_materials_clearcoat:Yo,KHR_materials_coat:tr,KHR_materials_diffuse_roughness:vi,KHR_materials_diffuse_transmission:Jr,KHR_materials_dispersion:fi,KHR_materials_emissive_strength:_r,KHR_materials_fuzz:Cr,KHR_materials_ior:Nr,KHR_materials_iridescence:ir,KHR_materials_pbrSpecularGlossiness:Vo,KHR_materials_sheen:xr,KHR_materials_specular:Er,KHR_materials_transmission:jr,KHR_materials_unlit:qo,KHR_materials_variants:Hr,KHR_materials_volume:oi,KHR_materials_volume_scatter:ui,KHR_mesh_quantization:Mi,KHR_node_hoverability:Il,KHR_node_selectability:wl,KHR_node_visibility:bl,KHR_texture_basisu:Oi,KHR_texture_transform:Pi,KHR_xmp_json_ld:Gi,MSFT_audio_emitter:Aa,MSFT_lod:Sa,MSFT_minecraftMesh:La,MSFT_sRGBFactors:Da,RegisterEXT_lights_area:ko,RegisterEXT_lights_ies:fo,RegisterEXT_lights_image_based:Ks,RegisterEXT_mesh_gpu_instancing:zs,RegisterEXT_meshopt_compression:Zs,RegisterEXT_texture_avif:lo,RegisterEXT_texture_webp:so,RegisterExtrasAsMetadata:Gl,RegisterKHR_animation_pointer:Wi,RegisterKHR_draco_mesh_compression:vo,RegisterKHR_gaussian_splatting:Ro,RegisterKHR_interactivity:gl,RegisterKHR_lights:Io,RegisterKHR_materials_anisotropy:mr,RegisterKHR_materials_clearcoat:Zo,RegisterKHR_materials_coat:sr,RegisterKHR_materials_diffuse_roughness:xi,RegisterKHR_materials_diffuse_transmission:ti,RegisterKHR_materials_dispersion:_i,RegisterKHR_materials_emissive_strength:yr,RegisterKHR_materials_fuzz:Sr,RegisterKHR_materials_ior:Dr,RegisterKHR_materials_iridescence:lr,RegisterKHR_materials_pbrSpecularGlossiness:Ko,RegisterKHR_materials_sheen:Ar,RegisterKHR_materials_specular:Lr,RegisterKHR_materials_transmission:Yr,RegisterKHR_materials_unlit:zo,RegisterKHR_materials_variants:$r,RegisterKHR_materials_volume:ii,RegisterKHR_materials_volume_scatter:di,RegisterKHR_mesh_quantization:Ci,RegisterKHR_node_hoverability:Pl,RegisterKHR_node_selectability:Rl,RegisterKHR_node_visibility:Tl,RegisterKHR_texture_basisu:Ei,RegisterKHR_texture_transform:Ni,RegisterKHR_xmp_json_ld:Hi,RegisterMSFT_audio_emitter:wa,RegisterMSFT_lod:Fa,RegisterMSFT_minecraftMesh:Ba,RegisterMSFT_sRGBFactors:Va,SetInterpolationForKey:ys,TransmissionHelper:qr,_AddInteractivityObjectModel:pl,addNewInteractivityFlowGraphMapping:Ua,ensureTransmissionHelper:Wr,getAllSupportedNativeNodeTypes:Qa,getMappingForDeclaration:$a,getMappingForFullOperationName:Ka,gltfTypeToBabylonType:Za},Ul={__proto__:null,AddObjectAccessorToKey:vs,AnimationPropertyInfo:Es,ArrayItem:Ts,EXT_lights_area:Bo,EXT_lights_ies:ho,EXT_lights_image_based:Vs,EXT_mesh_gpu_instancing:qs,EXT_meshopt_compression:Ys,EXT_texture_avif:io,EXT_texture_webp:to,ExtrasAsMetadata:kl,FlowGraphGLTFDataProvider:Hl,GLTFFileLoader:mn,GLTFLoader:Ms,GetMappingForKey:gs,GetPathToObjectConverter:_s,InteractivityGraphToFlowGraphParser:Ja,KHR_animation_pointer:Ui,KHR_draco_mesh_compression:go,KHR_gaussian_splatting:wo,KHR_interactivity:fl,KHR_lights:Fo,KHR_materials_anisotropy:dr,KHR_materials_clearcoat:Yo,KHR_materials_coat:tr,KHR_materials_diffuse_roughness:vi,KHR_materials_diffuse_transmission:Jr,KHR_materials_dispersion:fi,KHR_materials_emissive_strength:_r,KHR_materials_fuzz:Cr,KHR_materials_ior:Nr,KHR_materials_iridescence:ir,KHR_materials_pbrSpecularGlossiness:Vo,KHR_materials_sheen:xr,KHR_materials_specular:Er,KHR_materials_transmission:jr,KHR_materials_unlit:qo,KHR_materials_variants:Hr,KHR_materials_volume:oi,KHR_materials_volume_scatter:ui,KHR_mesh_quantization:Mi,KHR_node_hoverability:Il,KHR_node_selectability:wl,KHR_node_visibility:bl,KHR_texture_basisu:Oi,KHR_texture_transform:Pi,KHR_xmp_json_ld:Gi,LoadBoundingInfoFromPositionAccessor:As,MSFT_audio_emitter:Aa,MSFT_lod:Sa,MSFT_minecraftMesh:La,MSFT_sRGBFactors:Da,OpenPBRMaterialLoadingAdapter:Bs,PBRMaterialLoadingAdapter:ks,RegisterEXT_lights_area:ko,RegisterEXT_lights_ies:fo,RegisterEXT_lights_image_based:Ks,RegisterEXT_mesh_gpu_instancing:zs,RegisterEXT_meshopt_compression:Zs,RegisterEXT_texture_avif:lo,RegisterEXT_texture_webp:so,RegisterExtrasAsMetadata:Gl,RegisterGLTF2Loader:Cs,RegisterKHR_animation_pointer:Wi,RegisterKHR_draco_mesh_compression:vo,RegisterKHR_gaussian_splatting:Ro,RegisterKHR_interactivity:gl,RegisterKHR_lights:Io,RegisterKHR_materials_anisotropy:mr,RegisterKHR_materials_clearcoat:Zo,RegisterKHR_materials_coat:sr,RegisterKHR_materials_diffuse_roughness:xi,RegisterKHR_materials_diffuse_transmission:ti,RegisterKHR_materials_dispersion:_i,RegisterKHR_materials_emissive_strength:yr,RegisterKHR_materials_fuzz:Sr,RegisterKHR_materials_ior:Dr,RegisterKHR_materials_iridescence:lr,RegisterKHR_materials_pbrSpecularGlossiness:Ko,RegisterKHR_materials_sheen:Ar,RegisterKHR_materials_specular:Lr,RegisterKHR_materials_transmission:Yr,RegisterKHR_materials_unlit:zo,RegisterKHR_materials_variants:$r,RegisterKHR_materials_volume:ii,RegisterKHR_materials_volume_scatter:di,RegisterKHR_mesh_quantization:Ci,RegisterKHR_node_hoverability:Pl,RegisterKHR_node_selectability:Rl,RegisterKHR_node_visibility:Tl,RegisterKHR_texture_basisu:Ei,RegisterKHR_texture_transform:Ni,RegisterKHR_xmp_json_ld:Hi,RegisterMSFT_audio_emitter:wa,RegisterMSFT_lod:Fa,RegisterMSFT_minecraftMesh:Ba,RegisterMSFT_sRGBFactors:Va,SetInterpolationForKey:ys,TransformNodeAnimationPropertyInfo:Is,TransmissionHelper:qr,WeightAnimationPropertyInfo:Ls,_AddInteractivityObjectModel:pl,addNewInteractivityFlowGraphMapping:Ua,ensureTransmissionHelper:Wr,getAllSupportedNativeNodeTypes:Qa,getMappingForDeclaration:$a,getMappingForFullOperationName:Ka,getQuaternion:Os,getVector3:Ss,getWeights:Fs,gltfTypeToBabylonType:Za,registerGLTFExtension:ts,registeredGLTFExtensions:es,unregisterGLTFExtension:ns};class ql{constructor(){this.materials=[]}parseMTL(e,n,s,o){if(n instanceof ArrayBuffer)return;const r=n.split("\n"),i=/\s+/;let a,l=null;for(let n=0;n<r.length;n++){const u=r[n].trim();if(0===u.length||"#"===u.charAt(0))continue;const c=u.indexOf(" ");let d=c>=0?u.substring(0,c):u;d=d.toLowerCase();const h=c>=0?u.substring(c+1).trim():"";if("newmtl"===d)l&&this.materials.push(l),e._blockEntityCollection=!!o,l=new t.StandardMaterial(h,e),l._parentContainer=o,e._blockEntityCollection=!1;else if("kd"===d&&l)a=h.split(i,3).map(parseFloat),l.diffuseColor=t.Color3.FromArray(a);else if("ka"===d&&l)a=h.split(i,3).map(parseFloat),l.ambientColor=t.Color3.FromArray(a);else if("ks"===d&&l)a=h.split(i,3).map(parseFloat),l.specularColor=t.Color3.FromArray(a);else if("ke"===d&&l)a=h.split(i,3).map(parseFloat),l.emissiveColor=t.Color3.FromArray(a);else if("ns"===d&&l)l.specularPower=parseFloat(h);else if("d"===d&&l)l.alpha=parseFloat(h);else if("map_ka"===d&&l)l.ambientTexture=ql._GetTexture(s,h,e);else if("map_kd"===d&&l)l.diffuseTexture=ql._GetTexture(s,h,e);else if("map_ks"===d&&l)l.specularTexture=ql._GetTexture(s,h,e);else if("map_ns"===d);else if("map_bump"===d&&l){const t=h.split(i),n=t.indexOf("-bm");let o=null;n>=0&&(o=t[n+1],t.splice(n,2)),l.bumpTexture=ql._GetTexture(s,t.join(" "),e),l.bumpTexture&&null!==o&&(l.bumpTexture.level=parseFloat(o))}else"map_d"===d&&l&&(l.opacityTexture=ql._GetTexture(s,h,e))}l&&this.materials.push(l)}static _GetTexture(e,n,s){if(!n)return null;let o=e;if("file:"===e){let e=n.lastIndexOf("\\");-1===e&&(e=n.lastIndexOf("/")),o+=e>-1?n.substring(e+1):n}else o+=n;return new t.Texture(o,s,!1,ql.INVERT_TEXTURE_Y)}}ql.INVERT_TEXTURE_Y=!0;class Wl{constructor(e,n,s){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 t.Color4(.5,.5,.5,1),this._hasLineData=!1,this._materialToUse=e,this._babylonMeshesArray=n,this._loadingOptions=s}_isInArray(e,t){e[t[0]]||(e[t[0]]={normals:[],idx:[]});const n=e[t[0]].normals.indexOf(t[1]);return-1===n?-1:e[t[0]].idx[n]}_isInArrayUV(e,t){e[t[0]]||(e[t[0]]={normals:[],idx:[],uv:[]});const n=e[t[0]].normals.indexOf(t[1]);return 1!=n&&t[2]===e[t[0]].uv[n]?e[t[0]].idx[n]:-1}_setData(e){var t,n;let s;null!==(t=e.indiceUvsFromObj)&&void 0!==t||(e.indiceUvsFromObj=-1),null!==(n=e.indiceNormalFromObj)&&void 0!==n||(e.indiceNormalFromObj=-1),s=this._loadingOptions.optimizeWithUV?this._isInArrayUV(this._tuplePosNorm,[e.indicePositionFromObj,e.indiceNormalFromObj,e.indiceUvsFromObj]):this._isInArray(this._tuplePosNorm,[e.indicePositionFromObj,e.indiceNormalFromObj]),-1===s?(this._indicesForBabylon.push(this._wrappedPositionForBabylon.length),this._wrappedPositionForBabylon.push(e.positionVectorFromOBJ),void 0!==e.textureVectorFromOBJ&&this._wrappedUvsForBabylon.push(e.textureVectorFromOBJ),void 0!==e.normalsVectorFromOBJ&&this._wrappedNormalsForBabylon.push(e.normalsVectorFromOBJ),void 0!==e.positionColorsFromOBJ&&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(s)}_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 new 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){var t;return this._loadingOptions.importVertexColors?null!==(t=this._extColors[e])&&void 0!==t?t:this._colors[e]:void 0}_setDataForCurrentFaceWithPattern1(e,t){this._getTriangles(e,t);for(let e=0;e<this._triangles.length;e++){const 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++){const t=this._triangles[e].split("/"),n=parseInt(t[0])-1,s=parseInt(t[1])-1;this._setData({indicePositionFromObj:n,indiceUvsFromObj:s,positionVectorFromOBJ:this._positions[n],textureVectorFromOBJ:this._uvs[s],positionColorsFromOBJ:this._getColor(n)})}this._triangles.length=0}_setDataForCurrentFaceWithPattern3(e,t){this._getTriangles(e,t);for(let e=0;e<this._triangles.length;e++){const t=this._triangles[e].split("/"),n=parseInt(t[0])-1,s=parseInt(t[1])-1,o=parseInt(t[2])-1;this._setData({indicePositionFromObj:n,indiceUvsFromObj:s,indiceNormalFromObj:o,positionVectorFromOBJ:this._positions[n],textureVectorFromOBJ:this._uvs[s],normalsVectorFromOBJ:this._normals[o]})}this._triangles.length=0}_setDataForCurrentFaceWithPattern4(e,t){this._getTriangles(e,t);for(let e=0;e<this._triangles.length;e++){const t=this._triangles[e].split("//"),n=parseInt(t[0])-1,s=parseInt(t[1])-1;this._setData({indicePositionFromObj:n,indiceNormalFromObj:s,positionVectorFromOBJ:this._positions[n],normalsVectorFromOBJ:this._normals[s],positionColorsFromOBJ:this._getColor(n)})}this._triangles.length=0}_setDataForCurrentFaceWithPattern5(e,t){this._getTriangles(e,t);for(let e=0;e<this._triangles.length;e++){const t=this._triangles[e].split("/"),n=this._positions.length+parseInt(t[0]),s=this._uvs.length+parseInt(t[1]),o=this._normals.length+parseInt(t[2]);this._setData({indicePositionFromObj:n,indiceUvsFromObj:s,indiceNormalFromObj:o,positionVectorFromOBJ:this._positions[n],textureVectorFromOBJ:this._uvs[s],normalsVectorFromOBJ:this._normals[o],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){const n=e.getVerticesData(t.VertexBuffer.PositionKind),s=e.getVerticesData(t.VertexBuffer.NormalKind),o={};if(!n||!s)return;for(let e=0;e<n.length/3;e++){const t=n[3*e+0]+"_"+n[3*e+1]+"_"+n[3*e+2];let s=o[t];s||(s=[],o[t]=s),s.push(e)}const r=new t.Vector3;for(const e in o){const t=o[e];if(t.length<2)continue;const n=t[0];for(let e=1;e<t.length;++e){const o=t[e];s[3*n+0]+=s[3*o+0],s[3*n+1]+=s[3*o+1],s[3*n+2]+=s[3*o+2]}r.copyFromFloats(s[3*n+0],s[3*n+1],s[3*n+2]),r.normalize();for(let e=0;e<t.length;++e){const n=t[e];s[3*n+0]=r.x,s[3*n+1]=r.y,s[3*n+2]=r.z}}e.setVerticesData(t.VertexBuffer.NormalKind,s)}static _IsLineElement(e){return e.startsWith("l")}static _IsObjectElement(e){return e.startsWith("o")}static _IsGroupElement(e){return e.startsWith("g")}static _GetZbrushMRGB(e,n){if(!e.startsWith("mrgb"))return null;if(e=e.replace("mrgb","").trim(),n)return[];const s=e.match(/[a-z0-9]/g);if(!s||s.length%8!=0)return[];const o=[];for(let e=0;e<s.length/8;e++){const n=s[8*e+2]+s[8*e+3],r=s[8*e+4]+s[8*e+5],i=s[8*e+6]+s[8*e+7];o.push(new t.Color4(parseInt(n,16)/255,parseInt(r,16)/255,parseInt(i,16)/255,1))}return o}parse(e,n,s,o,r){var i,a,l,u,c;n=(n=n.replace(/#MRGB/g,"mrgb")).replace(/#.*$/gm,"").trim(),this._loadingOptions.useLegacyBehavior?(this._pushTriangle=(e,t)=>this._triangles.push(e[0],e[t],e[t+1]),this._handednessSign=1):s.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);const d=n.split("\n"),h=[];let m=[];h.push(m);for(let e=0;e<d.length;e++){const t=d[e].trim().replace(/\s\s/g," ");if(0!==t.length&&"#"!==t.charAt(0))if((Wl._IsGroupElement(t)||Wl._IsObjectElement(t))&&(m=[],h.push(m)),Wl._IsLineElement(t)){const e=t.split(" ");for(let t=1;t<e.length-1;t++)m.push(`l ${e[t]} ${e[t+1]}`)}else m.push(t)}const f=h.flat();for(let e=0;e<f.length;e++){const n=f[e].trim().replace(/\s\s/g," ");let s;if(0!==n.length&&"#"!==n.charAt(0))if(Wl.VertexPattern.test(n)){if(s=n.match(/[^ ]+/g),this._positions.push(new t.Vector3(parseFloat(s[1]),parseFloat(s[2]),parseFloat(s[3]))),this._loadingOptions.importVertexColors)if(s.length>=7){const e=parseFloat(s[4]),n=parseFloat(s[5]),o=parseFloat(s[6]);this._colors.push(new t.Color4(e>1?e/255:e,n>1?n/255:n,o>1?o/255:o,7===s.length||void 0===s[7]?1:parseFloat(s[7])))}else this._colors.push(this._grayColor)}else if(null!==(s=Wl.NormalPattern.exec(n)))this._normals.push(new t.Vector3(parseFloat(s[1]),parseFloat(s[2]),parseFloat(s[3])));else if(null!==(s=Wl.UVPattern.exec(n)))this._uvs.push(new t.Vector2(parseFloat(s[1])*this._loadingOptions.UVScaling.x,parseFloat(s[2])*this._loadingOptions.UVScaling.y));else if(null!==(s=Wl.FacePattern3.exec(n)))this._setDataForCurrentFaceWithPattern3(s[1].trim().split(" "),1);else if(null!==(s=Wl.FacePattern4.exec(n)))this._setDataForCurrentFaceWithPattern4(s[1].trim().split(" "),1);else if(null!==(s=Wl.FacePattern5.exec(n)))this._setDataForCurrentFaceWithPattern5(s[1].trim().split(" "),1);else if(null!==(s=Wl.FacePattern2.exec(n)))this._setDataForCurrentFaceWithPattern2(s[1].trim().split(" "),1);else if(null!==(s=Wl.FacePattern1.exec(n)))this._setDataForCurrentFaceWithPattern1(s[1].trim().split(" "),1);else if(null!==(s=Wl.LinePattern1.exec(n)))this._setDataForCurrentFaceWithPattern1(s[1].trim().split(" "),0),this._hasLineData=!0;else if(null!==(s=Wl.LinePattern2.exec(n)))this._setDataForCurrentFaceWithPattern2(s[1].trim().split(" "),0),this._hasLineData=!0;else if(s=Wl._GetZbrushMRGB(n,!this._loadingOptions.importVertexColors))for(const e of s)this._extColors.push(e);else if(null!==(s=Wl.LinePattern3.exec(n)))this._setDataForCurrentFaceWithPattern3(s[1].trim().split(" "),0),this._hasLineData=!0;else if(Wl.GroupDescriptor.test(n)||Wl.ObjectDescriptor.test(n)){const e={name:n.substring(2).trim(),indices:null,positions:null,normals:null,uvs:null,colors:null,materialName:this._materialNameFromObj,isObject:Wl.ObjectDescriptor.test(n)};this._addPreviousObjMesh(),this._meshesFromObj.push(e),this._hasMeshes=!0,this._isFirstMaterial=!0,this._increment=1}else if(Wl.UseMtlDescriptor.test(n)){if(this._materialNameFromObj=n.substring(7).trim(),!this._isFirstMaterial||!this._hasMeshes){this._addPreviousObjMesh();const 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 Wl.MtlLibGroupDescriptor.test(n)?r(n.substring(7).trim()):Wl.SmoothDescriptor.test(n)||t.Logger.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(const e of this._positions)this._unwrappedPositionsForBabylon.push(e.x,e.y,e.z);if(this._normals.length)for(const e of this._normals)this._unwrappedNormalsForBabylon.push(e.x,e.y,e.z);if(this._uvs.length)for(const e of this._uvs)this._unwrappedUVForBabylon.push(e.x,e.y);if(this._extColors.length)for(const e of this._extColors)this._unwrappedColorsForBabylon.push(e.r,e.g,e.b,e.a);else if(this._colors.length)for(const e of this._colors)this._unwrappedColorsForBabylon.push(e.r,e.g,e.b,e.a);this._materialNameFromObj||(e=new t.StandardMaterial(t.Geometry.RandomId(),s),e.pointsCloud=!0,this._materialNameFromObj=e.name,this._normals.length||(e.disableLighting=!0,e.emissiveColor=t.Color3.White()))}this._meshesFromObj.push({name:t.Geometry.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 n=0;n<this._meshesFromObj.length;n++){if(e&&this._meshesFromObj[n].name)if(e instanceof Array){if(-1===e.indexOf(this._meshesFromObj[n].name))continue}else if(this._meshesFromObj[n].name!==e)continue;this._handledMesh=this._meshesFromObj[n],s._blockEntityCollection=!!o;const r=new t.Mesh(this._meshesFromObj[n].name,s);if(r._parentContainer=o,s._blockEntityCollection=!1,this._handledMesh._babylonMesh=r,!this._handledMesh.isObject)for(let e=n-1;e>=0;--e)if(this._meshesFromObj[e].isObject&&this._meshesFromObj[e]._babylonMesh){r.parent=this._meshesFromObj[e]._babylonMesh;break}if(this._materialToUse.push(this._meshesFromObj[n].materialName),this._handledMesh.hasLines&&(null!==(i=r._internalMetadata)&&void 0!==i||(r._internalMetadata={}),r._internalMetadata._isLine=!0),0===(null===(a=this._handledMesh.positions)||void 0===a?void 0:a.length)){this._babylonMeshesArray.push(r);continue}const d=new t.VertexData;if(d.indices=this._handledMesh.indices,d.positions=this._handledMesh.positions,this._loadingOptions.computeNormals||!(null===(l=this._handledMesh.normals)||void 0===l?void 0:l.length)){const e=new Array;t.VertexData.ComputeNormals(this._handledMesh.positions,this._handledMesh.indices,e),d.normals=e}else d.normals=this._handledMesh.normals;(null===(u=this._handledMesh.uvs)||void 0===u?void 0:u.length)&&(d.uvs=this._handledMesh.uvs),(null===(c=this._handledMesh.colors)||void 0===c?void 0:c.length)&&(d.colors=this._handledMesh.colors),d.applyToMesh(r),this._loadingOptions.invertY&&(r.scaling.y*=-1),this._loadingOptions.optimizeNormals&&this._optimizeNormals(r),this._babylonMeshesArray.push(r),this._handledMesh.directMaterial&&(r.material=this._handledMesh.directMaterial)}}}Wl.ObjectDescriptor=/^o/,Wl.GroupDescriptor=/^g/,Wl.MtlLibGroupDescriptor=/^mtllib /,Wl.UseMtlDescriptor=/^usemtl /,Wl.SmoothDescriptor=/^s /,Wl.VertexPattern=/^v(\s+[\d|.|+|\-|e|E]+){3,7}/,Wl.NormalPattern=/^vn(\s+[\d|.|+|\-|e|E]+)( +[\d|.|+|\-|e|E]+)( +[\d|.|+|\-|e|E]+)/,Wl.UVPattern=/^vt(\s+[\d|.|+|\-|e|E]+)( +[\d|.|+|\-|e|E]+)/,Wl.FacePattern1=/^f\s+(([\d]{1,}[\s]?){3,})+/,Wl.FacePattern2=/^f\s+((([\d]{1,}\/[\d]{1,}[\s]?){3,})+)/,Wl.FacePattern3=/^f\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){3,})+)/,Wl.FacePattern4=/^f\s+((([\d]{1,}\/\/[\d]{1,}[\s]?){3,})+)/,Wl.FacePattern5=/^f\s+(((-[\d]{1,}\/-[\d]{1,}\/-[\d]{1,}[\s]?){3,})+)/,Wl.LinePattern1=/^l\s+(([\d]{1,}[\s]?){2,})+/,Wl.LinePattern2=/^l\s+((([\d]{1,}\/[\d]{1,}[\s]?){2,})+)/,Wl.LinePattern3=/^l\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){2,})+)/;const zl={name:"obj",extensions:".obj"};class jl{static get INVERT_TEXTURE_Y(){return ql.INVERT_TEXTURE_Y}static set INVERT_TEXTURE_Y(e){ql.INVERT_TEXTURE_Y=e}constructor(e){this.name=zl.name,this.extensions=zl.extensions,this._assetContainer=null,this._loadingOptions=Object.assign(Object.assign({},jl._DefaultLoadingOptions),null!=e?e:{})}static get _DefaultLoadingOptions(){return{computeNormals:jl.COMPUTE_NORMALS,optimizeNormals:jl.OPTIMIZE_NORMALS,importVertexColors:jl.IMPORT_VERTEX_COLORS,invertY:jl.INVERT_Y,invertTextureY:jl.INVERT_TEXTURE_Y,UVScaling:jl.UV_SCALING,materialLoadingFailsSilently:jl.MATERIAL_LOADING_FAILS_SILENTLY,optimizeWithUV:jl.OPTIMIZE_WITH_UV,skipMaterials:jl.SKIP_MATERIALS,useLegacyBehavior:jl.USE_LEGACY_BEHAVIOR}}_loadMTL(e,n,s,o){const r=n+e;t.Tools.LoadFile(r,s,void 0,void 0,!1,(e,t)=>{o(r,t)})}createPlugin(e){return new jl(e[zl.name])}canDirectLoad(){return!1}importMeshAsync(e,t,n,s){return this._parseSolidAsync(e,t,n,s).then(e=>({meshes:e,particleSystems:[],skeletons:[],animationGroups:[],transformNodes:[],geometries:[],lights:[],spriteManagers:[]}))}loadAsync(e,t,n){return this.importMeshAsync(null,e,t,n).then(()=>{})}loadAssetContainerAsync(e,n,s){const o=new t.AssetContainer(e);return this._assetContainer=o,this.importMeshAsync(null,e,n,s).then(e=>(e.meshes.forEach(e=>o.meshes.push(e)),e.meshes.forEach(e=>{const t=e.material;t&&-1==o.materials.indexOf(t)&&(o.materials.push(t),t.getActiveTextures().forEach(e=>{-1==o.textures.indexOf(e)&&o.textures.push(e)}))}),this._assetContainer=null,o)).catch(e=>{throw this._assetContainer=null,e})}_parseSolidAsync(e,n,s,o){let r="";const i=new ql,a=[],l=[];s=s.replace(/#.*$/gm,"").trim(),new Wl(a,l,this._loadingOptions).parse(e,s,n,this._assetContainer,e=>{r=e});const u=[];return""===r||this._loadingOptions.skipMaterials||u.push(new Promise((e,s)=>{this._loadMTL(r,o,u=>{try{i.parseMTL(n,u,o,this._assetContainer);for(let e=0;e<i.materials.length;e++){let t=0;const n=[];let s;for(;(s=a.indexOf(i.materials[e].name,t))>-1;)n.push(s),t=s+1;if(-1===s&&0===n.length)i.materials[e].dispose();else for(let t=0;t<n.length;t++){const s=l[n[t]],o=i.materials[e];s.material=o,s.getTotalIndices()||(o.pointsCloud=!0)}}e()}catch(n){t.Tools.Warn(`Error processing MTL file: '${r}'`),this._loadingOptions.materialLoadingFailsSilently?e():s(n)}},(n,o)=>{t.Tools.Warn(`Error downloading MTL file: '${r}'`),this._loadingOptions.materialLoadingFailsSilently?e():s(o)})})),Promise.all(u).then(()=>{const e=e=>{var t,n;return Boolean(null!==(n=null===(t=e._internalMetadata)||void 0===t?void 0:t._isLine)&&void 0!==n&&n)};return l.forEach(s=>{var o,r;if(e(s)){let i=null!==(o=s.material)&&void 0!==o?o:new t.StandardMaterial(s.name+"_line",n);i.getBindedMeshes().filter(t=>!e(t)).length>0&&(i=null!==(r=i.clone(i.name+"_line"))&&void 0!==r?r:i),i.wireframe=!0,s.material=i,s._internalMetadata&&(s._internalMetadata._isLine=void 0)}}),l})}}jl.OPTIMIZE_WITH_UV=!0,jl.INVERT_Y=!1,jl.IMPORT_VERTEX_COLORS=!1,jl.COMPUTE_NORMALS=!1,jl.OPTIMIZE_NORMALS=!1,jl.UV_SCALING=new t.Vector2(1,1),jl.SKIP_MATERIALS=!1,jl.MATERIAL_LOADING_FAILS_SILENTLY=!0,jl.USE_LEGACY_BEHAVIOR=!1;let Xl=!1;function Yl(){Xl||(Xl=!0,t.RegisterSceneLoaderPlugin(new jl))}Yl();var Ql={__proto__:null,OBJFileLoader:jl,RegisterOBJFileLoader:Yl},Zl={__proto__:null,MTLFileLoader:ql,OBJFileLoader:jl,RegisterOBJFileLoader:Yl,SolidParser:Wl};const Jl={name:"stl",extensions:{".stl":{isBinary:!0}}};class eu{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=Jl.name,this.extensions=Jl.extensions}importMesh(e,n,s,o,r){let i;if("string"!=typeof s){if(this._isBinary(s)){const e=new t.Mesh("stlmesh",n);return this._parseBinary(e,s),r&&r.push(e),!0}s=(new TextDecoder).decode(new Uint8Array(s))}for(;i=this.solidPattern.exec(s);){let s=i[1];const o=i[3];if(o&&s!=o)return t.Tools.Error("Error in STL, solid name != endsolid name"),!1;if(e&&s)if(e instanceof Array){if(!e.indexOf(s))continue}else if(s!==e)continue;s=s||"stlmesh";const a=new t.Mesh(s,n);this._parseASCII(a,i[2]),r&&r.push(a)}return!0}load(e,t,n){return this.importMesh(null,e,t,n,null)}loadAssetContainer(e,n,s){const o=new t.AssetContainer(e);return e._blockEntityCollection=!0,this.importMesh(null,e,n,s,o.meshes),e._blockEntityCollection=!1,o}_isBinary(e){const t=new DataView(e);if(t.byteLength<=80)return!1;if(84+50*t.getUint32(80,!0)===t.byteLength)return!0;const n=[115,111,108,105,100];for(let e=0;e<5;e++)if(t.getUint8(e)!==n[e])return!0;return!1}_parseBinary(e,n){const s=new DataView(n),o=s.getUint32(80,!0);let r=0;const i=new Float32Array(3*o*3),a=new Float32Array(3*o*3),l=new Uint32Array(3*o);let u=0;for(let e=0;e<o;e++){const t=84+50*e,n=s.getFloat32(t,!0),o=s.getFloat32(t+4,!0),c=s.getFloat32(t+8,!0);for(let e=1;e<=3;e++){const l=t+12*e;i[r]=s.getFloat32(l,!0),a[r]=n,eu.DO_NOT_ALTER_FILE_COORDINATES?(i[r+1]=s.getFloat32(l+4,!0),i[r+2]=s.getFloat32(l+8,!0),a[r+1]=o,a[r+2]=c):(i[r+2]=s.getFloat32(l+4,!0),i[r+1]=s.getFloat32(l+8,!0),a[r+2]=o,a[r+1]=c),r+=3}eu.DO_NOT_ALTER_FILE_COORDINATES?(l[u]=u,l[u+1]=u+2,l[u+2]=u+1,u+=3):(l[u]=u++,l[u]=u++,l[u]=u++)}e.setVerticesData(t.VertexBuffer.PositionKind,i),e.setVerticesData(t.VertexBuffer.NormalKind,a),e.setIndices(l),e.computeWorldMatrix(!0)}_parseASCII(e,n){const s=[],o=[],r=[];let i,a=0;for(;i=this.facetsPattern.exec(n);){const e=i[1],t=this.normalPattern.exec(e);if(this.normalPattern.lastIndex=0,!t)continue;const n=[Number(t[1]),Number(t[5]),Number(t[3])];let l;for(;l=this.vertexPattern.exec(e);)eu.DO_NOT_ALTER_FILE_COORDINATES?(s.push(Number(l[1]),Number(l[3]),Number(l[5])),o.push(n[0],n[2],n[1])):(s.push(Number(l[1]),Number(l[5]),Number(l[3])),o.push(n[0],n[1],n[2]));eu.DO_NOT_ALTER_FILE_COORDINATES?(r.push(a,a+2,a+1),a+=3):r.push(a++,a++,a++),this.vertexPattern.lastIndex=0}this.facetsPattern.lastIndex=0,e.setVerticesData(t.VertexBuffer.PositionKind,s),e.setVerticesData(t.VertexBuffer.NormalKind,o),e.setIndices(r),e.computeWorldMatrix(!0)}}eu.DO_NOT_ALTER_FILE_COORDINATES=!1;let tu=!1;function nu(){tu||(tu=!0,t.RegisterSceneLoaderPlugin(new eu))}nu();var su={__proto__:null,RegisterSTLFileLoader:nu,STLFileLoader:eu},ou={__proto__:null,RegisterSTLFileLoader:nu,STLFileLoader:eu};const ru={name:"splat",extensions:{".splat":{isBinary:!0},".ply":{isBinary:!0},".spz":{isBinary:!0},".json":{isBinary:!1},".sog":{isBinary:!0}}},iu=.28209479177387814;function au(e,t,n){return b(this,void 0,void 0,function*(){const s=new Promise((s,o)=>{const r=n.createCanvasImage();if(!r)throw new Error("Failed to create ImageBitmap");let i;if(r.onload=()=>{try{const e=n.createCanvas(r.width,r.height);if(!e)throw new Error("Failed to create canvas");const t=e.getContext("2d");if(!t)throw new Error("Failed to get 2D context");t.drawImage(r,0,0);const o=t.getImageData(0,0,e.width,e.height);s({bits:new Uint8Array(o.data.buffer),width:o.width,height:o.height})}catch(e){o(`Error loading image ${r.src} with exception: ${e}`)}},r.onerror=e=>{o(`Error loading image ${r.src} with exception: ${e}`)},r.crossOrigin="anonymous","string"==typeof e){if(!t)throw new Error("filename is required when using a URL");r.src=e+t}else{const t=new Blob([e],{type:"image/webp"});i=URL.createObjectURL(t),r.src=i}});return yield s})}function lu(e,n,s){return b(this,void 0,void 0,function*(){let o,r;if(e instanceof Map){r=e;const t=r.get("meta.json");if(!t)throw new Error("meta.json not found in files Map");o=JSON.parse((new TextDecoder).decode(t))}else o=e;const i=[...o.means.files,...o.scales.files,...o.quats.files,...o.sh0.files];o.shN&&i.push(...o.shN.files);const a=yield Promise.all(i.map(e=>b(this,void 0,void 0,function*(){if(r&&r.has(e)){const t=r.get(e);return yield au(t,e,s.getEngine())}return yield au(n,e,s.getEngine())})));return yield function(e,n,s){return b(this,void 0,void 0,function*(){const o=e.count?e.count:e.means.shape[0],r=new ArrayBuffer(32*o),i=new Float32Array(r),a=new Float32Array(r),l=new Uint8ClampedArray(r),u=new Uint8ClampedArray(r),c=e=>Math.sign(e)*(Math.exp(Math.abs(e))-1),d=n[0].bits,h=n[1].bits;if(!Array.isArray(e.means.mins)||!Array.isArray(e.means.maxs))throw new Error("Missing arrays in SOG data.");for(let n=0;n<o;n++){const s=4*n;for(let o=0;o<3;o++){const r=e.means.mins[o],a=e.means.maxs[o],l=h[s+o]<<8|d[s+o],u=t.Scalar.Lerp(r,a,l/65535);i[8*n+o]=c(u)}}const m=n[2].bits;if(2===e.version){if(!e.scales.codebook)throw new Error("Missing codebook in SOG version 2 scales data.");for(let t=0;t<o;t++){const n=4*t;for(let s=0;s<3;s++){const o=e.scales.codebook[m[n+s]],r=Math.exp(o);a[8*t+3+s]=r}}}else{if(!Array.isArray(e.scales.mins)||!Array.isArray(e.scales.maxs))throw new Error("Missing arrays in SOG scales data.");for(let n=0;n<o;n++){const s=4*n;for(let o=0;o<3;o++){const r=m[s+o],i=t.Scalar.Lerp(e.scales.mins[o],e.scales.maxs[o],r/255),l=Math.exp(i);a[8*n+3+o]=l}}}const f=n[4].bits;if(2===e.version){if(!e.sh0.codebook)throw new Error("Missing codebook in SOG version 2 sh0 data.");for(let t=0;t<o;t++){const n=4*t;for(let s=0;s<3;s++){const o=.5+e.sh0.codebook[f[n+s]]*iu;l[32*t+24+s]=Math.max(0,Math.min(255,Math.round(255*o)))}l[32*t+24+3]=f[n+3]}}else{if(!Array.isArray(e.sh0.mins)||!Array.isArray(e.sh0.maxs))throw new Error("Missing arrays in SOG sh0 data.");for(let n=0;n<o;n++){const s=4*n;for(let o=0;o<4;o++){const r=e.sh0.mins[o],i=e.sh0.maxs[o],a=f[s+o],u=t.Scalar.Lerp(r,i,a/255);let c;c=o<3?.5+u*iu:1/(1+Math.exp(-u)),l[32*n+24+o]=Math.max(0,Math.min(255,Math.round(255*c)))}}}const p=e=>2*(e/255-.5)/Math.SQRT2,_=n[3].bits;for(let e=0;e<o;e++){const t=_[4*e+0],n=_[4*e+1],s=_[4*e+2],o=_[4*e+3],r=p(t),i=p(n),a=p(s),l=o-252,c=r*r+i*i+a*a,d=Math.sqrt(Math.max(0,1-c));let h;switch(l){case 0:h=[d,r,i,a];break;case 1:h=[r,d,i,a];break;case 2:h=[r,i,d,a];break;case 3:h=[r,i,a,d];break;default:throw new Error("Invalid quaternion mode")}u[32*e+28+0]=127.5*h[0]+127.5,u[32*e+28+1]=127.5*h[1]+127.5,u[32*e+28+2]=127.5*h[2]+127.5,u[32*e+28+3]=127.5*h[3]+127.5}if(e.shN){const i=e.shN.bands?Math.pow(e.shN.bands+1,2)-1:e.shN.shape[1]/3,a=void 0!==e.shN.bands&&null!==e.shN.bands?e.shN.bands:Math.round(Math.sqrt(i+1)-1),l=n[5].bits,u=n[6].bits,c=n[5].width,d=3*i,h=Math.ceil(d/16),m=s.getEngine().getCaps().maxTextureSize,f=Math.ceil(o/m),p=t.AllocateShBuffers(h,f*m*4*4);if(2===e.version){if(!e.shN.codebook)throw new Error("Missing codebook in SOG version 2 shN data.");for(let t=0;t<o;t++){const n=u[4*t+0]+(u[4*t+1]<<8),s=n%64*i,o=Math.floor(n/64);for(let n=0;n<i;n++)for(let r=0;r<3;r++){const i=3*n+r,a=Math.floor(i/16),u=p[a],d=i%16,h=16*t,m=127.5*e.shN.codebook[l[4*(s+n)+r+o*c*4]]+127.5;u[d+h]=Math.max(0,Math.min(255,m))}}}else for(let n=0;n<o;n++){const s=u[4*n+0]+(u[4*n+1]<<8),o=s%64*i,r=Math.floor(s/64),a=e.shN.mins,d=e.shN.maxs;for(let e=0;e<3;e++)for(let s=0;s<i/3;s++){const i=3*s+e,u=Math.floor(i/16),h=p[u],m=i%16,f=16*n,_=127.5*t.Scalar.Lerp(a,d,l[4*(o+s)+e+r*c*4]/255)+127.5;h[m+f]=Math.max(0,Math.min(255,_))}}return yield new Promise(e=>{e({mode:0,data:r,hasVertexColors:!1,sh:p,shDegree:a})})}return yield new Promise(e=>{e({mode:0,data:r,hasVertexColors:!1})})})}(o,a,s)})}function uu(e,n){return function(e,n,s,o){const r=new t.RawTexture(n,s,o,t.Constants.TEXTUREFORMAT_RGBA,e,!1,!1,t.Constants.TEXTURE_NEAREST_SAMPLINGMODE,t.Constants.TEXTURETYPE_UNSIGNED_BYTE);return r.wrapU=t.Constants.TEXTURE_CLAMP_ADDRESSMODE,r.wrapV=t.Constants.TEXTURE_CLAMP_ADDRESSMODE,r}(e,n.bits,n.width,n.height)}function cu(e,n,s){return b(this,void 0,void 0,function*(){const o=s.getEngine();if("function"==typeof createImageBitmap)try{const r=n.toLowerCase().endsWith(".png")?"image/png":"image/webp";let i;if("string"==typeof e){const s=yield t.Tools.LoadFileAsync(e+n,!0);i=new Blob([s],{type:r})}else i=new Blob([e],{type:r});const a=yield createImageBitmap(i,{premultiplyAlpha:"none",colorSpaceConversion:"none"});try{const e=new t.RawTexture(null,a.width,a.height,t.Constants.TEXTUREFORMAT_RGBA,s,!1,!1,t.Constants.TEXTURE_NEAREST_SAMPLINGMODE,t.Constants.TEXTURETYPE_UNSIGNED_BYTE);e.wrapU=t.Constants.TEXTURE_CLAMP_ADDRESSMODE,e.wrapV=t.Constants.TEXTURE_CLAMP_ADDRESSMODE;const n=e.getInternalTexture();return n&&o.updateDynamicTexture(n,a,!1,!1),e}finally{a.close()}}catch(e){}const r=yield au(e,n,o);return uu(s,r)})}function du(e,n,s,o){const r=e=>Math.sign(e)*(Math.exp(Math.abs(e))-1);if(!Array.isArray(e.means.mins)||!Array.isArray(e.means.maxs))throw new Error("Missing arrays in SOG data.");const i=new Float32Array(4*o);for(let a=0;a<o;a++){const o=4*a;for(let l=0;l<3;l++){const u=s[o+l]<<8|n[o+l],c=t.Scalar.Lerp(e.means.mins[l],e.means.maxs[l],u/65535);i[4*a+l]=r(c)}i[4*a+3]=1}return i}function hu(e,n,s){return b(this,arguments,void 0,function*(e,n,s,o=!0,r,i){var a,l,u,c,d,h,m;let f,p;if(e instanceof Map){p=e;const t=p.get("meta.json");if(!t)throw new Error("meta.json not found in files Map");f=JSON.parse((new TextDecoder).decode(t))}else f=e;const _=e=>b(this,void 0,void 0,function*(){if(p&&p.has(e))return yield au(p.get(e),e,s.getEngine());if(r){const t=new Uint8Array(yield r.loadFileAsync(n+e,i));return yield au(t,e,s.getEngine())}return yield au(n,e,s.getEngine())}),g=e=>b(this,void 0,void 0,function*(){if(p&&p.has(e))return yield cu(p.get(e),e,s);if(r){const t=new Uint8Array(yield r.loadFileAsync(n+e,i));return yield cu(t,e,s)}return yield cu(n,e,s)}),y=[...f.scales.files,...f.quats.files,...f.sh0.files,...null!==(l=null===(a=f.shN)||void 0===a?void 0:a.files)&&void 0!==l?l:[]];let v,x,T,A,M,w=null;if(o){const[e,t]=yield Promise.all([Promise.all(f.means.files.map(_)),Promise.all(y.map(g))]);w=[e[0],e[1]],M=t,v=uu(s,e[0]),x=uu(s,e[1]),T=e[0].width,A=e[0].height}else{const[e,t]=yield Promise.all([Promise.all(f.means.files.map(g)),Promise.all(y.map(g))]);M=t,v=e[0],x=e[1];const n=v.getSize();T=n.width,A=n.height}const C=null!==(u=f.count)&&void 0!==u?u:f.means.shape[0],R=T*A;if(R<C)throw new Error(`SOG texture contains ${R} texels, but metadata references ${C} splats.`);const S=M[0],O=M[1],F=M[2];let E,I,L,P=0,B=0;if(f.shN&&M.length>=5&&(E=M[3],I=M[4],P=f.shN.bands?Math.pow(f.shN.bands+1,2)-1:f.shN.shape[1]/3,B=null!==(c=f.shN.bands)&&void 0!==c?c:Math.round(Math.sqrt(P+1)-1)),2===f.version){const e=256,n=new Float32Array(3*e);f.scales.codebook&&n.set(f.scales.codebook.slice(0,e),0),f.sh0.codebook&&n.set(f.sh0.codebook.slice(0,e),e),(null===(d=f.shN)||void 0===d?void 0:d.codebook)&&n.set(f.shN.codebook.slice(0,e),2*e),L=new t.RawTexture(n,3*e,1,t.Constants.TEXTUREFORMAT_R,s,!1,!1,t.Constants.TEXTURE_NEAREST_SAMPLINGMODE,t.Constants.TEXTURETYPE_FLOAT),L.wrapU=t.Constants.TEXTURE_CLAMP_ADDRESSMODE,L.wrapV=t.Constants.TEXTURE_CLAMP_ADDRESSMODE}const N=f.means.mins,k=f.means.maxs,D={version:2===f.version?2:1,splatCount:C,shDegree:B,meansTextureL:v,meansTextureU:x,scalesTexture:S,quatsTexture:O,sh0Texture:F,shCentroidsTexture:E,shLabelsTexture:I,codebookTexture:L,meansMin:[N[0],N[1],N[2]],meansMax:[k[0],k[1],k[2]],scalesMin:Array.isArray(f.scales.mins)?[f.scales.mins[0],f.scales.mins[1],f.scales.mins[2]]:void 0,scalesMax:Array.isArray(f.scales.maxs)?[f.scales.maxs[0],f.scales.maxs[1],f.scales.maxs[2]]:void 0,sh0Min:Array.isArray(f.sh0.mins)?[f.sh0.mins[0],f.sh0.mins[1],f.sh0.mins[2],f.sh0.mins[3]]:void 0,sh0Max:Array.isArray(f.sh0.maxs)?[f.sh0.maxs[0],f.sh0.maxs[1],f.sh0.maxs[2],f.sh0.maxs[3]]:void 0,shnMin:"number"==typeof(null===(h=f.shN)||void 0===h?void 0:h.mins)?f.shN.mins:void 0,shnMax:"number"==typeof(null===(m=f.shN)||void 0===m?void 0:m.maxs)?f.shN.maxs:void 0,shCoeffCount:P,positions:w?du(f,w[0].bits,w[1].bits,C):new Float32Array(0)};return{mode:0,data:new ArrayBuffer(0),hasVertexColors:!1,shDegree:B,sogTextures:D}})}const mu="precision highp float;\nattribute vec3 position;\nvoid main() {\n gl_Position = vec4(position.xy, 0.0, 1.0);\n}\n",fu="\nattribute position : vec3<f32>;\n@vertex\nfn main(input : VertexInputs) -> FragmentInputs {\n vertexOutputs.position = vec4<f32>(input.position.xy, 0.0, 1.0);\n}\n";class pu{get supportsAsyncCentersReadback(){var e;const t=this._scene.getEngine();if(t.isWebGPU)return!0;const n=t;return!!n._gl&&"function"==typeof n._readPixelsAsync&&(null!==(e=n.webGLVersion)&&void 0!==e?e: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,s,o){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?1:0,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)),s&&s.textureCount>0){if(s.externalMrts)this._shMrts=s.externalMrts.slice(0,s.textureCount),this._ownsShMrts=!1;else{for(let e=0;e<s.textureCount;e++)this._shMrts.push(this._createShMrt(`gsWorkBufferSh${e}`,!0));this._ownsShMrts=!0}this._shMaterial=this._createShMaterial()}o&&(o.externalMrt?(this._rotMrt=o.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&&this.isRelayoutReady()}backupRegion(){if(this._disposed||this._ownsMrt)return;if(!this.isRelayoutReady())return void t.Logger.Warn("GaussianSplattingWorkBuffer: backup skipped because the copy shaders are not ready; streamed region data may be lost on the atlas rebuild.");const e=this._textureSize,n=Math.max(1,Math.floor(this._capacity/e)),s=Math.floor(this._baseOffset/e);if(this._backupMrt||(this._backupMrt=this._createMrt("gsAtlasBackup",!1,e,n)),this._renderRelayoutPass(this._backupMrt,this._mrt.textures,this._mrt.textures[0],0,e,e,0,-s),this._shMrts.length&&this._shCopyMaterial){this._backupShMrts||(this._backupShMrts=this._shMrts.map((t,s)=>this._createShMrt(`gsShAtlasBackup${s}`,!1,e,n)));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,-s)}this._rotMrt&&this._rotCopyMaterial&&(this._backupRotMrt||(this._backupRotMrt=this._createRotMrt("gsRotAtlasBackup",!1,e,n)),this._renderRotCopyPass(this._backupRotMrt,this._rotMrt.textures,this._mrt.textures[0],0,e,e,0,-s)),this._quad.material=this._material}restoreRegion(){var e;if(this._disposed||this._ownsMrt||!this._backupMrt||!this._copyMaterial)return;const t=this._textureSize,n=Math.max(1,Math.floor(this._capacity/t)),s=Math.floor(this._baseOffset/t),o=this._scene.getEngine();o.enableScissor(0,s,t,n);try{if(this._renderRelayoutPass(this._mrt,this._backupMrt.textures,this._backupMrt.textures[0],0,t,t,0,s),this._backupShMrts&&this._shMrts.length&&this._shCopyMaterial)for(let e=0;e<this._shMrts.length&&e<this._backupShMrts.length;e++)this._renderShCopyPass(this._shMrts[e],this._backupShMrts[e].textures[0],this._mrt.textures[0],0,t,t,0,s);this._backupRotMrt&&this._rotMrt&&this._rotCopyMaterial&&this._renderRotCopyPass(this._rotMrt,this._backupRotMrt.textures,this._mrt.textures[0],0,t,t,0,s)}finally{o.disableScissor(),this._quad.material=this._material}if(this._backupMrt.dispose(),this._backupMrt=null,this._backupShMrts){for(const e of this._backupShMrts)e.dispose();this._backupShMrts=null}null===(e=this._backupRotMrt)||void 0===e||e.dispose(),this._backupRotMrt=null}_createMrt(e,n,s=this._textureSize,o=this._textureSize){const r=this._scene.getEngine()._caps.textureHalfFloatRender?t.Constants.TEXTURETYPE_HALF_FLOAT:t.Constants.TEXTURETYPE_FLOAT,i=new t.MultiRenderTarget(e,{width:s,height:o},4,this._scene,{types:[t.Constants.TEXTURETYPE_FLOAT,r,r,t.Constants.TEXTURETYPE_UNSIGNED_BYTE],samplingModes:[t.Constants.TEXTURE_NEAREST_SAMPLINGMODE,t.Constants.TEXTURE_NEAREST_SAMPLINGMODE,t.Constants.TEXTURE_NEAREST_SAMPLINGMODE,t.Constants.TEXTURE_NEAREST_SAMPLINGMODE],formats:[t.Constants.TEXTUREFORMAT_RGBA,t.Constants.TEXTUREFORMAT_RGBA,t.Constants.TEXTUREFORMAT_RGBA,t.Constants.TEXTUREFORMAT_RGBA],generateDepthBuffer:!1,generateDepthTexture:!1,generateMipMaps:!1},[`${e}Centers`,`${e}CovA`,`${e}CovB`,`${e}Colors`]);return i.clearColor=new t.Color4(0,0,0,0),i.renderList=[],n&&i.onClearObservable.add(()=>{}),i}_createShMrt(e,n,s=this._textureSize,o=this._textureSize){const r=new t.MultiRenderTarget(e,{width:s,height:o},1,this._scene,{types:[t.Constants.TEXTURETYPE_UNSIGNED_INTEGER],formats:[t.Constants.TEXTUREFORMAT_RGBA_INTEGER],samplingModes:[t.Constants.TEXTURE_NEAREST_SAMPLINGMODE],generateDepthBuffer:!1,generateDepthTexture:!1,generateMipMaps:!1},[e]);return r.clearColor=new t.Color4(0,0,0,0),r.renderList=[],n&&r.onClearObservable.add(()=>{}),r}_createRotMrt(e,n,s=this._textureSize,o=this._textureSize){const r=this._scene.getEngine()._caps.textureHalfFloatRender?t.Constants.TEXTURETYPE_HALF_FLOAT:t.Constants.TEXTURETYPE_FLOAT,i=new t.MultiRenderTarget(e,{width:s,height:o},3,this._scene,{types:[r,r,r],formats:[t.Constants.TEXTUREFORMAT_RGBA,t.Constants.TEXTUREFORMAT_RGBA,t.Constants.TEXTUREFORMAT_RGBA],samplingModes:[t.Constants.TEXTURE_NEAREST_SAMPLINGMODE,t.Constants.TEXTURE_NEAREST_SAMPLINGMODE,t.Constants.TEXTURE_NEAREST_SAMPLINGMODE],generateDepthBuffer:!1,generateDepthTexture:!1,generateMipMaps:!1},[`${e}A`,`${e}B`,`${e}Scale`]);return i.clearColor=new t.Color4(0,0,0,0),i.renderList=[],n&&i.onClearObservable.add(()=>{}),i}decodeAsync(e,t){return b(this,void 0,void 0,function*(){if(this._disposed)return;this._applyPack(e);const n=null!==this._shMaterial&&this._shMrts.length>0;n&&this._applyShPack(e);const s=null!==this._rotMaterial&&null!==this._rotMrt;s&&this._applyRotPack(e),yield new Promise(o=>{const r=()=>{if(this._disposed)return void o();if(!this._material.isReady(this._quad)||n&&!this._shMaterial.isReady(this._quad)||s&&!this._rotMaterial.isReady(this._quad))return void this._scene.onBeforeRenderObservable.addOnce(r);const i=this._textureSize,a=this._baseOffset+t;this._material.setInt("uOffset",a),n&&this._shMaterial.setInt("uOffset",a),s&&this._rotMaterial.setInt("uOffset",a);const l=Math.floor(a/i),u=Math.max(1,Math.ceil((a+e.splatCount)/i)-l),c=this._scene.getEngine();c.enableScissor(0,l,i,u);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}s&&(this._quad.material=this._rotMaterial,this._rotMrt.renderList=[this._quad],this._rotMrt.render(),this._quad.material=this._material)}finally{c.disableScissor()}o()};this._scene.onBeforeRenderObservable.addOnce(r)})})}isRelayoutReady(){if(this._disposed)return!1;this._copyMaterial||(this._copyMaterial=this._createCopyMaterial()),this._shMrts.length&&!this._shCopyMaterial&&(this._shCopyMaterial=this._createShCopyMaterial()),this._rotMrt&&!this._rotCopyMaterial&&(this._rotCopyMaterial=this._createRotCopyMaterial()),this._bindCopyMaterialsToAtlas();const e=0===this._shMrts.length||null!==this._shCopyMaterial&&this._shCopyMaterial.isReady(this._quad),t=!this._rotMrt||null!==this._rotCopyMaterial&&this._rotCopyMaterial.isReady(this._quad);return this._copyMaterial.isReady(this._quad)&&e&&t}_bindCopyMaterialsToAtlas(){const 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){const 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;const n=this._textureSize,s=n,o=this._ownsMrt?n:Math.max(1,Math.floor(this._capacity/n));this._relayoutMapData||(this._relayoutMapData=new Float32Array(s*o));const r=this._relayoutMapData;r.fill(-1),r.set(e.subarray(0,Math.min(e.length,r.length))),this._relayoutMapTexture?this._relayoutMapTexture.update(r):this._relayoutMapTexture=new t.RawTexture(r,s,o,t.Constants.TEXTUREFORMAT_R,this._scene,!1,!1,t.Constants.TEXTURE_NEAREST_SAMPLINGMODE,t.Constants.TEXTURETYPE_FLOAT);const i=this._relayoutMapTexture;if(this._ownsMrt){const e=this._createMrt("gsRelayoutTemp",!1);try{this._renderRelayoutPass(e,this._mrt.textures,i,1),this._renderRelayoutPass(this._mrt,e.textures,i,0)}finally{e.dispose()}if(this._shMrts.length&&this._shCopyMaterial)for(let e=0;e<this._shMrts.length;e++){const t=this._createShMrt("gsShRelayoutTemp",!1);try{this._renderShCopyPass(t,this._shMrts[e].textures[0],i,1),this._renderShCopyPass(this._shMrts[e],t.textures[0],i,0)}finally{t.dispose()}}if(this._rotMrt&&this._rotCopyMaterial){const e=this._createRotMrt("gsRotRelayoutTemp",!1);try{this._renderRotCopyPass(e,this._rotMrt.textures,i,1),this._renderRotCopyPass(this._rotMrt,e.textures,i,0)}finally{e.dispose()}}return void(this._quad.material=this._material)}const a=Math.floor(this._baseOffset/n),l=o,u=this._scene.getEngine(),c=this._createMrt("gsRelayoutTemp",!1,n,l),d=this._shMrts.length&&this._shCopyMaterial?this._shMrts.map((e,t)=>this._createShMrt(`gsShRelayoutTemp${t}`,!1,n,l)):[],h=this._rotMrt&&this._rotCopyMaterial?this._createRotMrt("gsRotRelayoutTemp",!1,n,l):null;try{this._renderRelayoutPass(c,this._mrt.textures,i,1,n,n,this._baseOffset,0);for(let e=0;e<d.length;e++)this._renderShCopyPass(d[e],this._shMrts[e].textures[0],i,1,n,n,this._baseOffset,0);h&&this._renderRotCopyPass(h,this._rotMrt.textures,i,1,n,n,this._baseOffset,0),u.enableScissor(0,a,n,l);try{this._renderRelayoutPass(this._mrt,c.textures,i,0,n,n,0,a);for(let e=0;e<d.length;e++)this._renderShCopyPass(this._shMrts[e],d[e].textures[0],i,0,n,n,0,a);h&&this._renderRotCopyPass(this._rotMrt,h.textures,i,0,n,n,0,a)}finally{u.disableScissor()}}finally{c.dispose();for(const e of d)e.dispose();null==h||h.dispose(),this._quad.material=this._material}}_renderRelayoutPass(e,t,n,s,o=this._textureSize,r=this._textureSize,i=0,a=0){const l=this._copyMaterial;l.setTexture("uMapTex",n),l.setTexture("uSrc0",t[0]),l.setTexture("uSrc1",t[1]),l.setTexture("uSrc2",t[2]),l.setTexture("uSrc3",t[3]),l.setInt("uDstWidth",o),l.setInt("uSrcWidth",r),l.setInt("uUseMap",s),l.setInt("uSrcBaseOffset",i),l.setInt("uDstBaseRow",a),this._quad.material=l,e.renderList=[this._quad],e.render()}_createCopyMaterial(){const e=1===this._shaderLanguage,n=new t.ShaderMaterial("gsWorkBufferRelayout",this._scene,{vertexSource:e?fu:mu,fragmentSource:e?"\nvar uMapTexSampler : sampler;\nvar uMapTex : texture_2d<f32>;\nvar uSrc0Sampler : sampler;\nvar uSrc0 : texture_2d<f32>;\nvar uSrc1Sampler : sampler;\nvar uSrc1 : texture_2d<f32>;\nvar uSrc2Sampler : sampler;\nvar uSrc2 : texture_2d<f32>;\nvar uSrc3Sampler : sampler;\nvar uSrc3 : texture_2d<f32>;\n\nuniform uDstWidth : i32;\nuniform uSrcWidth : i32;\nuniform uUseMap : i32;\n// Region-scoped relayout (hosted compound atlas), both default 0 (standalone square path unchanged).\nuniform uSrcBaseOffset : i32;\nuniform uDstBaseRow : i32;\n\n@fragment\nfn main(input : FragmentInputs) -> FragmentOutputs {\n let p : vec2<i32> = vec2<i32>(i32(fragmentInputs.position.x), i32(fragmentInputs.position.y));\n var srcIdx : i32;\n if (uniforms.uUseMap == 1) {\n let m : f32 = textureLoad(uMapTex, p, 0).r;\n if (m < 0.0) {\n discard;\n }\n srcIdx = uniforms.uSrcBaseOffset + i32(m + 0.5);\n } else {\n srcIdx = (p.y - uniforms.uDstBaseRow) * uniforms.uDstWidth + p.x;\n }\n let s : vec2<i32> = vec2<i32>(srcIdx - (srcIdx / uniforms.uSrcWidth) * uniforms.uSrcWidth, srcIdx / uniforms.uSrcWidth);\n fragmentOutputs.fragData0 = textureLoad(uSrc0, s, 0);\n fragmentOutputs.fragData1 = textureLoad(uSrc1, s, 0);\n fragmentOutputs.fragData2 = textureLoad(uSrc2, s, 0);\n fragmentOutputs.fragData3 = textureLoad(uSrc3, s, 0);\n}\n":"precision highp float;\nprecision highp int;\n\nuniform sampler2D uMapTex;\nuniform sampler2D uSrc0;\nuniform sampler2D uSrc1;\nuniform sampler2D uSrc2;\nuniform sampler2D uSrc3;\nuniform int uDstWidth;\nuniform int uSrcWidth;\nuniform int uUseMap;\n// Region-scoped relayout (hosted compound atlas), both default 0 (standalone square path unchanged):\n// uSrcBaseOffset — added to the map's (region-local) source index so pass 1 reads the correct GLOBAL atlas texel.\n// uDstBaseRow — subtracted from the atlas destination row so pass 2's identity copy reads the region-local temp.\nuniform int uSrcBaseOffset;\nuniform int uDstBaseRow;\n\nlayout(location = 0) out vec4 glFragData[4];\n\nvoid main() {\n ivec2 p = ivec2(gl_FragCoord.xy);\n int srcIdx;\n if (uUseMap == 1) {\n float m = texelFetch(uMapTex, p, 0).r;\n if (m < 0.0) {\n discard;\n }\n srcIdx = uSrcBaseOffset + int(m + 0.5);\n } else {\n srcIdx = (p.y - uDstBaseRow) * uDstWidth + p.x;\n }\n ivec2 s = ivec2(srcIdx - (srcIdx / uSrcWidth) * uSrcWidth, srcIdx / uSrcWidth);\n glFragData[0] = texelFetch(uSrc0, s, 0);\n glFragData[1] = texelFetch(uSrc1, s, 0);\n glFragData[2] = texelFetch(uSrc2, s, 0);\n glFragData[3] = texelFetch(uSrc3, s, 0);\n}\n"},{attributes:["position"],uniforms:["uDstWidth","uSrcWidth","uUseMap","uSrcBaseOffset","uDstBaseRow"],samplers:["uMapTex","uSrc0","uSrc1","uSrc2","uSrc3"],shaderLanguage:this._shaderLanguage});return n.backFaceCulling=!1,n.disableDepthWrite=!0,n}_renderShCopyPass(e,t,n,s,o=this._textureSize,r=this._textureSize,i=0,a=0){const l=this._shCopyMaterial;l.setTexture("uMapTex",n),l.setTexture("uSrcSh",t),l.setInt("uDstWidth",o),l.setInt("uSrcWidth",r),l.setInt("uUseMap",s),l.setInt("uSrcBaseOffset",i),l.setInt("uDstBaseRow",a),this._quad.material=l,e.renderList=[this._quad],e.render()}_createShCopyMaterial(){const e=1===this._shaderLanguage,n=new t.ShaderMaterial("gsWorkBufferShCopy",this._scene,{vertexSource:e?fu:mu,fragmentSource:e?'\nvar uMapTexSampler : sampler;\nvar uMapTex : texture_2d<f32>;\n// Integer source sampled via textureLoad only — NO paired sampler (a sampler on a Uint texture fails WebGPU\n// validation: "None of the supported sample types (Uint)"). Mirrors the draw shader\'s shTexture0 declaration.\nvar uSrcSh : texture_2d<u32>;\n\nuniform uDstWidth : i32;\nuniform uSrcWidth : i32;\nuniform uUseMap : i32;\nuniform uSrcBaseOffset : i32;\nuniform uDstBaseRow : i32;\n\n@fragment\nfn main(input : FragmentInputs) -> FragmentOutputs {\n let p : vec2<i32> = vec2<i32>(i32(fragmentInputs.position.x), i32(fragmentInputs.position.y));\n var srcIdx : i32;\n if (uniforms.uUseMap == 1) {\n let m : f32 = textureLoad(uMapTex, p, 0).r;\n if (m < 0.0) {\n discard;\n }\n srcIdx = uniforms.uSrcBaseOffset + i32(m + 0.5);\n } else {\n srcIdx = (p.y - uniforms.uDstBaseRow) * uniforms.uDstWidth + p.x;\n }\n let s : vec2<i32> = vec2<i32>(srcIdx - (srcIdx / uniforms.uSrcWidth) * uniforms.uSrcWidth, srcIdx / uniforms.uSrcWidth);\n // Wrap in an explicit vec4<u32> so the WGSL processor emits an integer fragData location (its detection keys\n // off a literal vec4<u32>/vec4u in the assignment; a bare textureLoad(...) would default to vec4<f32>).\n fragmentOutputs.fragData0 = vec4<u32>(textureLoad(uSrcSh, s, 0));\n}\n':"precision highp float;\nprecision highp int;\nprecision highp usampler2D;\n\nuniform sampler2D uMapTex;\nuniform usampler2D uSrcSh;\nuniform int uDstWidth;\nuniform int uSrcWidth;\nuniform int uUseMap;\nuniform int uSrcBaseOffset;\nuniform int uDstBaseRow;\n\nlayout(location = 0) out uvec4 outSh;\n\nvoid main() {\n ivec2 p = ivec2(gl_FragCoord.xy);\n int srcIdx;\n if (uUseMap == 1) {\n float m = texelFetch(uMapTex, p, 0).r;\n if (m < 0.0) {\n discard;\n }\n srcIdx = uSrcBaseOffset + int(m + 0.5);\n } else {\n srcIdx = (p.y - uDstBaseRow) * uDstWidth + p.x;\n }\n ivec2 s = ivec2(srcIdx - (srcIdx / uSrcWidth) * uSrcWidth, srcIdx / uSrcWidth);\n outSh = texelFetch(uSrcSh, s, 0);\n}\n"},{attributes:["position"],uniforms:["uDstWidth","uSrcWidth","uUseMap","uSrcBaseOffset","uDstBaseRow"],samplers:["uMapTex","uSrcSh"],shaderLanguage:this._shaderLanguage});return n.backFaceCulling=!1,n.disableDepthWrite=!0,n}_renderRotCopyPass(e,t,n,s,o=this._textureSize,r=this._textureSize,i=0,a=0){const l=this._rotCopyMaterial;l.setTexture("uMapTex",n),l.setTexture("uSrc0",t[0]),l.setTexture("uSrc1",t[1]),l.setTexture("uSrc2",t[2]),l.setInt("uDstWidth",o),l.setInt("uSrcWidth",r),l.setInt("uUseMap",s),l.setInt("uSrcBaseOffset",i),l.setInt("uDstBaseRow",a),this._quad.material=l,e.renderList=[this._quad],e.render()}_createRotCopyMaterial(){const e=1===this._shaderLanguage,n=new t.ShaderMaterial("gsWorkBufferRotCopy",this._scene,{vertexSource:e?fu:mu,fragmentSource:e?"\nvar uMapTexSampler : sampler;\nvar uMapTex : texture_2d<f32>;\nvar uSrc0Sampler : sampler;\nvar uSrc0 : texture_2d<f32>;\nvar uSrc1Sampler : sampler;\nvar uSrc1 : texture_2d<f32>;\nvar uSrc2Sampler : sampler;\nvar uSrc2 : texture_2d<f32>;\n\nuniform uDstWidth : i32;\nuniform uSrcWidth : i32;\nuniform uUseMap : i32;\nuniform uSrcBaseOffset : i32;\nuniform uDstBaseRow : i32;\n\n@fragment\nfn main(input : FragmentInputs) -> FragmentOutputs {\n let p : vec2<i32> = vec2<i32>(i32(fragmentInputs.position.x), i32(fragmentInputs.position.y));\n var srcIdx : i32;\n if (uniforms.uUseMap == 1) {\n let m : f32 = textureLoad(uMapTex, p, 0).r;\n if (m < 0.0) {\n discard;\n }\n srcIdx = uniforms.uSrcBaseOffset + i32(m + 0.5);\n } else {\n srcIdx = (p.y - uniforms.uDstBaseRow) * uniforms.uDstWidth + p.x;\n }\n let s : vec2<i32> = vec2<i32>(srcIdx - (srcIdx / uniforms.uSrcWidth) * uniforms.uSrcWidth, srcIdx / uniforms.uSrcWidth);\n fragmentOutputs.fragData0 = textureLoad(uSrc0, s, 0);\n fragmentOutputs.fragData1 = textureLoad(uSrc1, s, 0);\n fragmentOutputs.fragData2 = textureLoad(uSrc2, s, 0);\n}\n":"precision highp float;\nprecision highp int;\n\nuniform sampler2D uMapTex;\nuniform sampler2D uSrc0;\nuniform sampler2D uSrc1;\nuniform sampler2D uSrc2;\nuniform int uDstWidth;\nuniform int uSrcWidth;\nuniform int uUseMap;\nuniform int uSrcBaseOffset;\nuniform int uDstBaseRow;\n\nlayout(location = 0) out vec4 glFragData[3];\n\nvoid main() {\n ivec2 p = ivec2(gl_FragCoord.xy);\n int srcIdx;\n if (uUseMap == 1) {\n float m = texelFetch(uMapTex, p, 0).r;\n if (m < 0.0) {\n discard;\n }\n srcIdx = uSrcBaseOffset + int(m + 0.5);\n } else {\n srcIdx = (p.y - uDstBaseRow) * uDstWidth + p.x;\n }\n ivec2 s = ivec2(srcIdx - (srcIdx / uSrcWidth) * uSrcWidth, srcIdx / uSrcWidth);\n glFragData[0] = texelFetch(uSrc0, s, 0);\n glFragData[1] = texelFetch(uSrc1, s, 0);\n glFragData[2] = texelFetch(uSrc2, s, 0);\n}\n"},{attributes:["position"],uniforms:["uDstWidth","uSrcWidth","uUseMap","uSrcBaseOffset","uDstBaseRow"],samplers:["uMapTex","uSrc0","uSrc1","uSrc2"],shaderLanguage:this._shaderLanguage});return n.backFaceCulling=!1,n.disableDepthWrite=!0,n}readCentersRangeAsync(e,t){return b(this,void 0,void 0,function*(){var n,s;if(this._disposed||t<=0||!this.supportsAsyncCentersReadback)return null;const o=this._textureSize,r=this._baseOffset+e,i=Math.floor(r/o),a=Math.ceil((r+t)/o)-i,l=4*(r-i*o),u=l+4*t,c=this._mrt.textures[0],d=this._scene.getEngine();if(d.isWebGPU){const e=yield c.readPixels(0,0,null,!0,!0,0,i,o,a);if(this._disposed||!e)return null;const t=e instanceof Float32Array?e:new Float32Array(e.buffer,e.byteOffset,e.byteLength/4);return t.length>=u?t.subarray(l,u):null}const h=d,m=h._gl,f=null===(s=null===(n=c.getInternalTexture())||void 0===n?void 0:n._hardwareTexture)||void 0===s?void 0:s.underlyingResource;if(!f)return null;const p=new Float32Array(o*a*4);this._readFbo||(this._readFbo=m.createFramebuffer());const _=h._currentFramebuffer;m.bindFramebuffer(m.FRAMEBUFFER,this._readFbo),m.framebufferTexture2D(m.FRAMEBUFFER,m.COLOR_ATTACHMENT0,m.TEXTURE_2D,f,0),m.readBuffer(m.COLOR_ATTACHMENT0);const g=h._readPixelsAsync(0,i,o,a,m.RGBA,m.FLOAT,p);return m.bindFramebuffer(m.FRAMEBUFFER,_),_||m.readBuffer(m.BACK),g?(yield g,this._disposed||p.length<u?null:p.subarray(l,u)):null})}dispose(){var e,t,n,s,o,r,i,a,l,u;if(this._disposed=!0,this._readFbo&&(null===(e=this._scene.getEngine()._gl)||void 0===e||e.deleteFramebuffer(this._readFbo),this._readFbo=null),this._quad.dispose(),this._material.dispose(!0,!1),null===(t=this._shMaterial)||void 0===t||t.dispose(!0,!1),null===(n=this._rotMaterial)||void 0===n||n.dispose(!0,!1),null===(s=this._copyMaterial)||void 0===s||s.dispose(!0,!1),null===(o=this._shCopyMaterial)||void 0===o||o.dispose(!0,!1),null===(r=this._rotCopyMaterial)||void 0===r||r.dispose(!0,!1),null===(i=this._relayoutMapTexture)||void 0===i||i.dispose(),null===(a=this._backupMrt)||void 0===a||a.dispose(),this._backupMrt=null,this._backupShMrts){for(const e of this._backupShMrts)e.dispose();this._backupShMrts=null}if(null===(l=this._backupRotMrt)||void 0===l||l.dispose(),this._backupRotMrt=null,this._ownsMrt&&this._mrt.dispose(),this._ownsShMrts)for(const e of this._shMrts)e.dispose();this._shMrts=[],this._ownsRotMrt&&(null===(u=this._rotMrt)||void 0===u||u.dispose()),this._rotMrt=null}_createQuad(){const e=new t.Mesh("gsWorkBufferQuad",this._scene),n=new t.VertexData;return n.positions=[-1,-1,0,3,-1,0,-1,3,0],n.indices=[0,1,2],n.applyToMesh(e),this._scene.removeMesh(e),e}_createMaterial(){const e=1===this._shaderLanguage,n=new t.ShaderMaterial("gsSogDecode",this._scene,{vertexSource:e?fu:mu,fragmentSource:e?"\nvar sogMeansLTexSampler : sampler;\nvar sogMeansLTex : texture_2d<f32>;\nvar sogMeansUTexSampler : sampler;\nvar sogMeansUTex : texture_2d<f32>;\nvar sogScalesTexSampler : sampler;\nvar sogScalesTex : texture_2d<f32>;\nvar sogQuatsTexSampler : sampler;\nvar sogQuatsTex : texture_2d<f32>;\nvar sogSh0TexSampler : sampler;\nvar sogSh0Tex : texture_2d<f32>;\nvar sogCodebookTexSampler : sampler;\nvar sogCodebookTex : texture_2d<f32>;\n\nuniform sogMeansMin : vec3<f32>;\nuniform sogMeansMax : vec3<f32>;\nuniform sogScalesMin : vec3<f32>;\nuniform sogScalesMax : vec3<f32>;\nuniform sogSh0Min : vec4<f32>;\nuniform sogSh0Max : vec4<f32>;\nuniform uVersion : i32;\nuniform uOffset : i32;\nuniform uCount : i32;\nuniform uDestWidth : i32;\nuniform uSrcWidth : i32;\n\n@fragment\nfn main(input : FragmentInputs) -> FragmentOutputs {\n let p : vec2<i32> = vec2<i32>(i32(fragmentInputs.position.x), i32(fragmentInputs.position.y));\n let global : i32 = p.y * uniforms.uDestWidth + p.x;\n if (global < uniforms.uOffset || global >= uniforms.uOffset + uniforms.uCount) {\n discard;\n }\n let k : i32 = global - uniforms.uOffset;\n let src : vec2<i32> = vec2<i32>(k - (k / uniforms.uSrcWidth) * uniforms.uSrcWidth, k / uniforms.uSrcWidth);\n\n let mL : vec3<f32> = textureLoad(sogMeansLTex, src, 0).xyz;\n let mU : vec3<f32> = textureLoad(sogMeansUTex, src, 0).xyz;\n let sRaw : vec3<f32> = textureLoad(sogScalesTex, src, 0).xyz;\n let qRaw : vec4<f32> = textureLoad(sogQuatsTex, src, 0);\n let c0 : vec4<f32> = textureLoad(sogSh0Tex, src, 0);\n\n let q16 : vec3<f32> = (mU * 256.0 + mL) * (255.0 / 65535.0);\n let nPos : vec3<f32> = mix(uniforms.sogMeansMin, uniforms.sogMeansMax, q16);\n let center : vec3<f32> = sign(nPos) * (exp(abs(nPos)) - vec3<f32>(1.0));\n\n var splatScale : vec3<f32>;\n if (uniforms.uVersion == 2) {\n let sIdx : vec3<f32> = floor(sRaw * 255.0 + 0.5);\n splatScale.x = exp(textureLoad(sogCodebookTex, vec2<i32>(i32(sIdx.x), 0), 0).r);\n splatScale.y = exp(textureLoad(sogCodebookTex, vec2<i32>(i32(sIdx.y), 0), 0).r);\n splatScale.z = exp(textureLoad(sogCodebookTex, vec2<i32>(i32(sIdx.z), 0), 0).r);\n } else {\n splatScale = exp(mix(uniforms.sogScalesMin, uniforms.sogScalesMax, sRaw));\n }\n\n let invSqrt2 : f32 = 0.70710678118;\n let qabc : vec3<f32> = (qRaw.xyz - vec3<f32>(0.5)) * 2.0 * invSqrt2;\n let qMode : i32 = i32(qRaw.w * 255.0 + 0.5) - 252;\n let qd : f32 = sqrt(max(0.0, 1.0 - dot(qabc, qabc)));\n var quat : vec4<f32>;\n if (qMode == 0) {\n quat = vec4<f32>(qd, qabc.x, qabc.y, qabc.z);\n } else if (qMode == 1) {\n quat = vec4<f32>(qabc.x, qd, qabc.y, qabc.z);\n } else if (qMode == 2) {\n quat = vec4<f32>(qabc.x, qabc.y, qd, qabc.z);\n } else {\n quat = vec4<f32>(qabc.x, qabc.y, qabc.z, qd);\n }\n\n let qw : f32 = quat.x;\n let qx : f32 = quat.y;\n let qy : f32 = quat.z;\n let qz : f32 = quat.w;\n let R : mat3x3<f32> = mat3x3<f32>(\n 1.0 - 2.0 * (qy * qy + qz * qz), 2.0 * (qx * qy + qw * qz), 2.0 * (qx * qz - qw * qy),\n 2.0 * (qx * qy - qw * qz), 1.0 - 2.0 * (qx * qx + qz * qz), 2.0 * (qy * qz + qw * qx),\n 2.0 * (qx * qz + qw * qy), 2.0 * (qy * qz - qw * qx), 1.0 - 2.0 * (qx * qx + qy * qy)\n );\n let S2 : mat3x3<f32> = mat3x3<f32>(\n 4.0 * splatScale.x * splatScale.x, 0.0, 0.0,\n 0.0, 4.0 * splatScale.y * splatScale.y, 0.0,\n 0.0, 0.0, 4.0 * splatScale.z * splatScale.z\n );\n let Sigma : mat3x3<f32> = R * S2 * transpose(R);\n\n let SH_C0 : f32 = 0.28209479177387814;\n var colRgb : vec3<f32>;\n var colA : f32;\n if (uniforms.uVersion == 2) {\n var c3 : vec3<f32>;\n c3.x = textureLoad(sogCodebookTex, vec2<i32>(256 + i32(c0.x * 255.0 + 0.5), 0), 0).r;\n c3.y = textureLoad(sogCodebookTex, vec2<i32>(256 + i32(c0.y * 255.0 + 0.5), 0), 0).r;\n c3.z = textureLoad(sogCodebookTex, vec2<i32>(256 + i32(c0.z * 255.0 + 0.5), 0), 0).r;\n colRgb = vec3<f32>(0.5) + c3 * SH_C0;\n colA = c0.w;\n } else {\n let cLerp : vec4<f32> = mix(uniforms.sogSh0Min, uniforms.sogSh0Max, c0);\n colRgb = vec3<f32>(0.5) + cLerp.xyz * SH_C0;\n colA = 1.0 / (1.0 + exp(-cLerp.w));\n }\n\n fragmentOutputs.fragData0 = vec4<f32>(center, 1.0);\n fragmentOutputs.fragData1 = vec4<f32>(Sigma[0][0], Sigma[0][1], Sigma[0][2], Sigma[1][1]);\n fragmentOutputs.fragData2 = vec4<f32>(Sigma[1][2], Sigma[2][2], 0.0, 0.0);\n fragmentOutputs.fragData3 = vec4<f32>(colRgb, colA);\n}\n":"precision highp float;\nprecision highp int;\n\nuniform sampler2D sogMeansLTex;\nuniform sampler2D sogMeansUTex;\nuniform sampler2D sogScalesTex;\nuniform sampler2D sogQuatsTex;\nuniform sampler2D sogSh0Tex;\nuniform sampler2D sogCodebookTex;\n\nuniform vec3 sogMeansMin;\nuniform vec3 sogMeansMax;\nuniform vec3 sogScalesMin;\nuniform vec3 sogScalesMax;\nuniform vec4 sogSh0Min;\nuniform vec4 sogSh0Max;\nuniform int uVersion;\nuniform int uOffset;\nuniform int uCount;\nuniform int uDestWidth;\nuniform int uSrcWidth;\n\nlayout(location = 0) out vec4 glFragData[4];\n\nmat3 transposeM(mat3 m) {\n 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]);\n}\n\nvoid main() {\n ivec2 p = ivec2(gl_FragCoord.xy);\n int global = p.y * uDestWidth + p.x;\n if (global < uOffset || global >= uOffset + uCount) {\n discard;\n }\n int k = global - uOffset;\n ivec2 src = ivec2(k - (k / uSrcWidth) * uSrcWidth, k / uSrcWidth);\n\n vec3 mL = texelFetch(sogMeansLTex, src, 0).xyz;\n vec3 mU = texelFetch(sogMeansUTex, src, 0).xyz;\n vec3 sRaw = texelFetch(sogScalesTex, src, 0).xyz;\n vec4 qRaw = texelFetch(sogQuatsTex, src, 0);\n vec4 c0 = texelFetch(sogSh0Tex, src, 0);\n\n // Position: q16 = (u<<8)|l normalized; n = lerp(min,max,q16); pos = sign(n)*(exp(|n|)-1)\n vec3 q16 = (mU * 256.0 + mL) * (255.0 / 65535.0);\n vec3 nPos = mix(sogMeansMin, sogMeansMax, q16);\n vec3 center = sign(nPos) * (exp(abs(nPos)) - vec3(1.0));\n\n // Scale (v1: lerp+exp ; v2: codebook lookup)\n vec3 splatScale;\n if (uVersion == 2) {\n vec3 sIdx = floor(sRaw * 255.0 + 0.5);\n splatScale.x = exp(texelFetch(sogCodebookTex, ivec2(int(sIdx.x), 0), 0).r);\n splatScale.y = exp(texelFetch(sogCodebookTex, ivec2(int(sIdx.y), 0), 0).r);\n splatScale.z = exp(texelFetch(sogCodebookTex, ivec2(int(sIdx.z), 0), 0).r);\n } else {\n splatScale = exp(mix(sogScalesMin, sogScalesMax, sRaw));\n }\n\n // Quaternion (largest-omitted, mode in alpha as 252 + omitted-index)\n const float invSqrt2 = 0.70710678118;\n vec3 qabc = (qRaw.xyz - vec3(0.5)) * 2.0 * invSqrt2;\n int qMode = int(qRaw.w * 255.0 + 0.5) - 252;\n float qd = sqrt(max(0.0, 1.0 - dot(qabc, qabc)));\n vec4 quat;\n if (qMode == 0) {\n quat = vec4(qd, qabc.x, qabc.y, qabc.z);\n } else if (qMode == 1) {\n quat = vec4(qabc.x, qd, qabc.y, qabc.z);\n } else if (qMode == 2) {\n quat = vec4(qabc.x, qabc.y, qd, qabc.z);\n } else {\n quat = vec4(qabc.x, qabc.y, qabc.z, qd);\n }\n\n float qw = quat.x, qx = quat.y, qy = quat.z, qz = quat.w;\n mat3 R = mat3(\n 1.0 - 2.0 * (qy * qy + qz * qz), 2.0 * (qx * qy + qw * qz), 2.0 * (qx * qz - qw * qy),\n 2.0 * (qx * qy - qw * qz), 1.0 - 2.0 * (qx * qx + qz * qz), 2.0 * (qy * qz + qw * qx),\n 2.0 * (qx * qz + qw * qy), 2.0 * (qy * qz - qw * qx), 1.0 - 2.0 * (qx * qx + qy * qy)\n );\n mat3 S2 = mat3(\n 4.0 * splatScale.x * splatScale.x, 0.0, 0.0,\n 0.0, 4.0 * splatScale.y * splatScale.y, 0.0,\n 0.0, 0.0, 4.0 * splatScale.z * splatScale.z\n );\n mat3 Sigma = R * S2 * transposeM(R);\n\n // Color (sh0)\n const float SH_C0 = 0.28209479177387814;\n vec3 colRgb;\n float colA;\n if (uVersion == 2) {\n vec3 c3;\n c3.x = texelFetch(sogCodebookTex, ivec2(256 + int(c0.x * 255.0 + 0.5), 0), 0).r;\n c3.y = texelFetch(sogCodebookTex, ivec2(256 + int(c0.y * 255.0 + 0.5), 0), 0).r;\n c3.z = texelFetch(sogCodebookTex, ivec2(256 + int(c0.z * 255.0 + 0.5), 0), 0).r;\n colRgb = vec3(0.5) + c3 * SH_C0;\n colA = c0.w;\n } else {\n vec4 cLerp = mix(sogSh0Min, sogSh0Max, c0);\n colRgb = vec3(0.5) + cLerp.xyz * SH_C0;\n colA = 1.0 / (1.0 + exp(-cLerp.w));\n }\n\n glFragData[0] = vec4(center, 1.0);\n glFragData[1] = vec4(Sigma[0][0], Sigma[0][1], Sigma[0][2], Sigma[1][1]);\n glFragData[2] = vec4(Sigma[1][2], Sigma[2][2], 0.0, 0.0);\n glFragData[3] = vec4(colRgb, colA);\n}\n"},{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 n.backFaceCulling=!1,n.disableDepthWrite=!0,n}_applyPack(e){var n,s,o,r,i;const a=this._material,l=e.meansTextureL.getSize().width;a.setTexture("sogMeansLTex",e.meansTextureL),a.setTexture("sogMeansUTex",e.meansTextureU),a.setTexture("sogScalesTex",e.scalesTexture),a.setTexture("sogQuatsTex",e.quatsTexture),a.setTexture("sogSh0Tex",e.sh0Texture),a.setTexture("sogCodebookTex",null!==(n=e.codebookTexture)&&void 0!==n?n:e.sh0Texture),a.setVector3("sogMeansMin",new t.Vector3(e.meansMin[0],e.meansMin[1],e.meansMin[2])),a.setVector3("sogMeansMax",new t.Vector3(e.meansMax[0],e.meansMax[1],e.meansMax[2]));const u=null!==(s=e.scalesMin)&&void 0!==s?s:[0,0,0],c=null!==(o=e.scalesMax)&&void 0!==o?o:[0,0,0];a.setVector3("sogScalesMin",new t.Vector3(u[0],u[1],u[2])),a.setVector3("sogScalesMax",new t.Vector3(c[0],c[1],c[2]));const d=null!==(r=e.sh0Min)&&void 0!==r?r:[0,0,0,0],h=null!==(i=e.sh0Max)&&void 0!==i?i:[0,0,0,0];a.setVector4("sogSh0Min",new t.Vector4(d[0],d[1],d[2],d[3])),a.setVector4("sogSh0Max",new t.Vector4(h[0],h[1],h[2],h[3])),a.setInt("uVersion",e.version),a.setInt("uCount",e.splatCount),a.setInt("uDestWidth",this._textureSize),a.setInt("uSrcWidth",l)}_createShMaterial(){const e=1===this._shaderLanguage,n=new t.ShaderMaterial("gsSogShDecodeToWorkBuffer",this._scene,{vertexSource:e?fu:mu,fragmentSource:e?"\nvar sogShLabelsTexSampler : sampler;\nvar sogShLabelsTex : texture_2d<f32>;\nvar sogShCentroidsTexSampler : sampler;\nvar sogShCentroidsTex : texture_2d<f32>;\nvar sogCodebookTexSampler : sampler;\nvar sogCodebookTex : texture_2d<f32>;\n\nuniform sogShnMin : f32;\nuniform sogShnMax : f32;\nuniform uVersion : i32;\nuniform uOffset : i32;\nuniform uCount : i32;\nuniform uDestWidth : i32;\nuniform uSrcWidth : i32;\nuniform uCoeffs : i32;\nuniform uShTextureIndex : i32;\n\n@fragment\nfn main(input : FragmentInputs) -> FragmentOutputs {\n let p : vec2<i32> = vec2<i32>(i32(fragmentInputs.position.x), i32(fragmentInputs.position.y));\n let global : i32 = p.y * uniforms.uDestWidth + p.x;\n if (global < uniforms.uOffset || global >= uniforms.uOffset + uniforms.uCount) {\n discard;\n }\n let kLocal : i32 = global - uniforms.uOffset;\n\n let lsz : vec2<i32> = vec2<i32>(textureDimensions(sogShLabelsTex, 0));\n let lsrc : vec2<i32> = vec2<i32>(kLocal - (kLocal / lsz.x) * lsz.x, kLocal / lsz.x);\n let labelRaw : vec4<f32> = textureLoad(sogShLabelsTex, lsrc, 0);\n let n : i32 = i32(labelRaw.r * 255.0 + 0.5) + i32(labelRaw.g * 255.0 + 0.5) * 256;\n let u : i32 = (n - (n / 64) * 64) * uniforms.uCoeffs;\n let v : i32 = n / 64;\n\n var packed : array<u32, 4> = array<u32, 4>(0u, 0u, 0u, 0u);\n\n for (var b : i32 = 0; b < 16; b = b + 1) {\n let s : i32 = uniforms.uShTextureIndex * 16 + b;\n let kc : i32 = s / 3;\n let j : i32 = s - kc * 3;\n var byteVal : f32 = 128.0;\n if (kc < uniforms.uCoeffs) {\n let centroidRaw : vec4<f32> = textureLoad(sogShCentroidsTex, vec2<i32>(u + kc, v), 0);\n var ch : f32 = centroidRaw.b;\n if (j == 0) { ch = centroidRaw.r; } else if (j == 1) { ch = centroidRaw.g; }\n var coeff : f32;\n if (uniforms.uVersion == 2) {\n let cidx : i32 = i32(ch * 255.0 + 0.5);\n coeff = textureLoad(sogCodebookTex, vec2<i32>(512 + cidx, 0), 0).r;\n } else {\n coeff = mix(uniforms.sogShnMin, uniforms.sogShnMax, ch);\n }\n byteVal = clamp(coeff * 127.5 + 127.5, 0.0, 255.0);\n }\n let bv : u32 = u32(byteVal + 0.5);\n let comp : i32 = b / 4;\n packed[comp] = packed[comp] | (bv << u32((b - comp * 4) * 8));\n }\n fragmentOutputs.fragData0 = vec4<u32>(packed[0], packed[1], packed[2], packed[3]);\n}\n":"precision highp float;\nprecision highp int;\n\nuniform sampler2D sogShLabelsTex;\nuniform sampler2D sogShCentroidsTex;\nuniform sampler2D sogCodebookTex;\nuniform float sogShnMin;\nuniform float sogShnMax;\nuniform int uVersion;\nuniform int uOffset;\nuniform int uCount;\nuniform int uDestWidth;\nuniform int uSrcWidth;\nuniform int uCoeffs;\nuniform int uShTextureIndex;\n\nlayout(location = 0) out uvec4 outSh;\n\nvoid main() {\n ivec2 p = ivec2(gl_FragCoord.xy);\n int global = p.y * uDestWidth + p.x;\n if (global < uOffset || global >= uOffset + uCount) {\n discard;\n }\n int kLocal = global - uOffset;\n\n // 16-bit label for this source splat (LSB in r, MSB in g), indexed over the labels texture's own width.\n ivec2 lsz = textureSize(sogShLabelsTex, 0);\n ivec2 lsrc = ivec2(kLocal - (kLocal / lsz.x) * lsz.x, kLocal / lsz.x);\n vec4 labelRaw = texelFetch(sogShLabelsTex, lsrc, 0);\n int n = int(labelRaw.r * 255.0 + 0.5) + int(labelRaw.g * 255.0 + 0.5) * 256;\n int u = (n - (n / 64) * 64) * uCoeffs;\n int v = n / 64;\n\n uint packed0 = 0u;\n uint packed1 = 0u;\n uint packed2 = 0u;\n uint packed3 = 0u;\n\n for (int b = 0; b < 16; b++) {\n int s = uShTextureIndex * 16 + b; // flat SH scalar index\n int kc = s / 3; // higher-order coefficient (0-based)\n int j = s - kc * 3; // channel (0=r,1=g,2=b)\n float byteVal = 128.0; // neutral (decompose(128) ~= 0)\n if (kc < uCoeffs) {\n vec4 centroidRaw = texelFetch(sogShCentroidsTex, ivec2(u + kc, v), 0);\n float ch = (j == 0) ? centroidRaw.r : ((j == 1) ? centroidRaw.g : centroidRaw.b);\n float coeff;\n if (uVersion == 2) {\n int cidx = int(ch * 255.0 + 0.5);\n coeff = texelFetch(sogCodebookTex, ivec2(512 + cidx, 0), 0).r;\n } else {\n coeff = mix(sogShnMin, sogShnMax, ch);\n }\n byteVal = clamp(coeff * 127.5 + 127.5, 0.0, 255.0);\n }\n uint bv = uint(byteVal + 0.5);\n int comp = b / 4;\n uint contrib = bv << uint((b - comp * 4) * 8);\n if (comp == 0) { packed0 |= contrib; }\n else if (comp == 1) { packed1 |= contrib; }\n else if (comp == 2) { packed2 |= contrib; }\n else { packed3 |= contrib; }\n }\n outSh = uvec4(packed0, packed1, packed2, packed3);\n}\n"},{attributes:["position"],uniforms:["sogShnMin","sogShnMax","uVersion","uOffset","uCount","uDestWidth","uSrcWidth","uCoeffs","uShTextureIndex"],samplers:["sogShLabelsTex","sogShCentroidsTex","sogCodebookTex"],shaderLanguage:this._shaderLanguage});return n.backFaceCulling=!1,n.disableDepthWrite=!0,n}_applyShPack(e){var t,n,s,o,r;const i=this._shMaterial,a=!!e.shLabelsTexture&&!!e.shCentroidsTexture,l=null!==(t=e.shLabelsTexture)&&void 0!==t?t:e.sh0Texture,u=null!==(n=e.shCentroidsTexture)&&void 0!==n?n:e.sh0Texture;i.setTexture("sogShLabelsTex",l),i.setTexture("sogShCentroidsTex",u),i.setTexture("sogCodebookTex",null!==(s=e.codebookTexture)&&void 0!==s?s:l),i.setFloat("sogShnMin",null!==(o=e.shnMin)&&void 0!==o?o:0),i.setFloat("sogShnMax",null!==(r=e.shnMax)&&void 0!==r?r:0),i.setInt("uVersion",e.version),i.setInt("uCount",e.splatCount),i.setInt("uDestWidth",this._textureSize),i.setInt("uSrcWidth",l.getSize().width),i.setInt("uCoeffs",a?e.shCoeffCount:0)}_createRotMaterial(){const e=1===this._shaderLanguage,n=new t.ShaderMaterial("gsSogRotDecodeToWorkBuffer",this._scene,{vertexSource:e?fu:mu,fragmentSource:e?"\nvar sogScalesTexSampler : sampler;\nvar sogScalesTex : texture_2d<f32>;\nvar sogQuatsTexSampler : sampler;\nvar sogQuatsTex : texture_2d<f32>;\nvar sogCodebookTexSampler : sampler;\nvar sogCodebookTex : texture_2d<f32>;\n\nuniform sogScalesMin : vec3<f32>;\nuniform sogScalesMax : vec3<f32>;\nuniform uVersion : i32;\nuniform uOffset : i32;\nuniform uCount : i32;\nuniform uDestWidth : i32;\nuniform uSrcWidth : i32;\n\n@fragment\nfn main(input : FragmentInputs) -> FragmentOutputs {\n let p : vec2<i32> = vec2<i32>(i32(fragmentInputs.position.x), i32(fragmentInputs.position.y));\n let global : i32 = p.y * uniforms.uDestWidth + p.x;\n if (global < uniforms.uOffset || global >= uniforms.uOffset + uniforms.uCount) {\n discard;\n }\n let k : i32 = global - uniforms.uOffset;\n let src : vec2<i32> = vec2<i32>(k - (k / uniforms.uSrcWidth) * uniforms.uSrcWidth, k / uniforms.uSrcWidth);\n\n let sRaw : vec3<f32> = textureLoad(sogScalesTex, src, 0).xyz;\n let qRaw : vec4<f32> = textureLoad(sogQuatsTex, src, 0);\n\n var splatScale : vec3<f32>;\n if (uniforms.uVersion == 2) {\n let sIdx : vec3<f32> = floor(sRaw * 255.0 + 0.5);\n splatScale.x = exp(textureLoad(sogCodebookTex, vec2<i32>(i32(sIdx.x), 0), 0).r);\n splatScale.y = exp(textureLoad(sogCodebookTex, vec2<i32>(i32(sIdx.y), 0), 0).r);\n splatScale.z = exp(textureLoad(sogCodebookTex, vec2<i32>(i32(sIdx.z), 0), 0).r);\n } else {\n splatScale = exp(mix(uniforms.sogScalesMin, uniforms.sogScalesMax, sRaw));\n }\n\n let invSqrt2 : f32 = 0.70710678118;\n let qabc : vec3<f32> = (qRaw.xyz - vec3<f32>(0.5)) * 2.0 * invSqrt2;\n let qMode : i32 = i32(qRaw.w * 255.0 + 0.5) - 252;\n let qd : f32 = sqrt(max(0.0, 1.0 - dot(qabc, qabc)));\n var quat : vec4<f32>;\n if (qMode == 0) {\n quat = vec4<f32>(qd, qabc.x, qabc.y, qabc.z);\n } else if (qMode == 1) {\n quat = vec4<f32>(qabc.x, qd, qabc.y, qabc.z);\n } else if (qMode == 2) {\n quat = vec4<f32>(qabc.x, qabc.y, qd, qabc.z);\n } else {\n quat = vec4<f32>(qabc.x, qabc.y, qabc.z, qd);\n }\n\n let qw : f32 = quat.x;\n let qx : f32 = quat.y;\n let qy : f32 = quat.z;\n let qz : f32 = quat.w;\n let R : mat3x3<f32> = mat3x3<f32>(\n 1.0 - 2.0 * (qy * qy + qz * qz), 2.0 * (qx * qy + qw * qz), 2.0 * (qx * qz - qw * qy),\n 2.0 * (qx * qy - qw * qz), 1.0 - 2.0 * (qx * qx + qz * qz), 2.0 * (qy * qz + qw * qx),\n 2.0 * (qx * qz + qw * qy), 2.0 * (qy * qz - qw * qx), 1.0 - 2.0 * (qx * qx + qy * qy)\n );\n\n fragmentOutputs.fragData0 = vec4<f32>(R[0], R[1].x);\n fragmentOutputs.fragData1 = vec4<f32>(R[1].y, R[1].z, R[2].x, R[2].y);\n fragmentOutputs.fragData2 = vec4<f32>(R[2].z, 2.0 * splatScale.x, 2.0 * splatScale.y, 2.0 * splatScale.z);\n}\n":"precision highp float;\nprecision highp int;\n\nuniform sampler2D sogScalesTex;\nuniform sampler2D sogQuatsTex;\nuniform sampler2D sogCodebookTex;\n\nuniform vec3 sogScalesMin;\nuniform vec3 sogScalesMax;\nuniform int uVersion;\nuniform int uOffset;\nuniform int uCount;\nuniform int uDestWidth;\nuniform int uSrcWidth;\n\nlayout(location = 0) out vec4 glFragData[3];\n\nvoid main() {\n ivec2 p = ivec2(gl_FragCoord.xy);\n int global = p.y * uDestWidth + p.x;\n if (global < uOffset || global >= uOffset + uCount) {\n discard;\n }\n int k = global - uOffset;\n ivec2 src = ivec2(k - (k / uSrcWidth) * uSrcWidth, k / uSrcWidth);\n\n vec3 sRaw = texelFetch(sogScalesTex, src, 0).xyz;\n vec4 qRaw = texelFetch(sogQuatsTex, src, 0);\n\n vec3 splatScale;\n if (uVersion == 2) {\n vec3 sIdx = floor(sRaw * 255.0 + 0.5);\n splatScale.x = exp(texelFetch(sogCodebookTex, ivec2(int(sIdx.x), 0), 0).r);\n splatScale.y = exp(texelFetch(sogCodebookTex, ivec2(int(sIdx.y), 0), 0).r);\n splatScale.z = exp(texelFetch(sogCodebookTex, ivec2(int(sIdx.z), 0), 0).r);\n } else {\n splatScale = exp(mix(sogScalesMin, sogScalesMax, sRaw));\n }\n\n const float invSqrt2 = 0.70710678118;\n vec3 qabc = (qRaw.xyz - vec3(0.5)) * 2.0 * invSqrt2;\n int qMode = int(qRaw.w * 255.0 + 0.5) - 252;\n float qd = sqrt(max(0.0, 1.0 - dot(qabc, qabc)));\n vec4 quat;\n if (qMode == 0) {\n quat = vec4(qd, qabc.x, qabc.y, qabc.z);\n } else if (qMode == 1) {\n quat = vec4(qabc.x, qd, qabc.y, qabc.z);\n } else if (qMode == 2) {\n quat = vec4(qabc.x, qabc.y, qd, qabc.z);\n } else {\n quat = vec4(qabc.x, qabc.y, qabc.z, qd);\n }\n\n float qw = quat.x, qx = quat.y, qy = quat.z, qz = quat.w;\n mat3 R = mat3(\n 1.0 - 2.0 * (qy * qy + qz * qz), 2.0 * (qx * qy + qw * qz), 2.0 * (qx * qz - qw * qy),\n 2.0 * (qx * qy - qw * qz), 1.0 - 2.0 * (qx * qx + qz * qz), 2.0 * (qy * qz + qw * qx),\n 2.0 * (qx * qz + qw * qy), 2.0 * (qy * qz - qw * qx), 1.0 - 2.0 * (qx * qx + qy * qy)\n );\n\n glFragData[0] = vec4(R[0], R[1].x);\n glFragData[1] = vec4(R[1].y, R[1].z, R[2].x, R[2].y);\n glFragData[2] = vec4(R[2].z, 2.0 * splatScale.x, 2.0 * splatScale.y, 2.0 * splatScale.z);\n}\n"},{attributes:["position"],uniforms:["sogScalesMin","sogScalesMax","uVersion","uOffset","uCount","uDestWidth","uSrcWidth"],samplers:["sogScalesTex","sogQuatsTex","sogCodebookTex"],shaderLanguage:this._shaderLanguage});return n.backFaceCulling=!1,n.disableDepthWrite=!0,n}_applyRotPack(e){var n,s,o;const r=this._rotMaterial,i=e.scalesTexture.getSize().width;r.setTexture("sogScalesTex",e.scalesTexture),r.setTexture("sogQuatsTex",e.quatsTexture),r.setTexture("sogCodebookTex",null!==(n=e.codebookTexture)&&void 0!==n?n:e.scalesTexture);const a=null!==(s=e.scalesMin)&&void 0!==s?s:[0,0,0],l=null!==(o=e.scalesMax)&&void 0!==o?o:[0,0,0];r.setVector3("sogScalesMin",new t.Vector3(a[0],a[1],a[2])),r.setVector3("sogScalesMax",new t.Vector3(l[0],l[1],l[2])),r.setInt("uVersion",e.version),r.setInt("uCount",e.splatCount),r.setInt("uDestWidth",this._textureSize),r.setInt("uSrcWidth",i)}}class _u{constructor(e){var t,n;this._activeCount=0,this._queue=[],this._pending=new Map,this._groups=new Map,this._disposed=!1,this.maxConcurrent=Math.max(1,null!==(t=null==e?void 0:e.maxConcurrent)&&void 0!==t?t:2),this.maxRetries=Math.max(0,null!==(n=null==e?void 0:e.maxRetries)&&void 0!==n?n:2)}get isIdle(){return 0===this._pending.size}loadFileAsync(e,t){return b(this,void 0,void 0,function*(){if(this._disposed)throw new Error("GaussianSplattingDownloadManager has been disposed.");const n=this._pending.get(e);if(n)return yield n.promise;const s={url:e,groupId:t,settled:!1,cancelled:!1,started:!1,slotReleased:!1};if(s.promise=new Promise((e,t)=>{s.resolve=e,s.reject=t}),this._pending.set(e,s),void 0!==t){let n=this._groups.get(t);n||(n=new Set,this._groups.set(t,n)),n.add(e)}return this._queue.push(s),this._pump(),yield s.promise})}cancel(e){const t=this._pending.get(e);t&&this._abort(t,new Error(`GaussianSplattingDownloadManager: download cancelled (${e}).`))}cancelGroup(e){const t=this._groups.get(e);if(t){for(const e of Array.from(t))this.cancel(e);this._groups.delete(e)}}dispose(){if(!this._disposed){this._disposed=!0,this._queue.length=0;for(const e of Array.from(this._pending.values()))this._abort(e,new Error("GaussianSplattingDownloadManager has been disposed."))}}_abort(e,t){var n,s;if(e.settled)return;e.cancelled=!0;const o=this._queue.indexOf(e);-1!==o&&this._queue.splice(o,1),null===(n=e.request)||void 0===n||n.abort(),null===(s=e.cancelAttempt)||void 0===s||s.call(e,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),void 0!==e.groupId){const t=this._groups.get(e.groupId);t&&(t.delete(e.url),0===t.size&&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;){const e=this._queue.shift();e.settled||(e.started=!0,this._activeCount++,this._runTaskAsync(e).finally(()=>{this._releaseSlot(e)}))}}_runTaskAsync(e){return b(this,void 0,void 0,function*(){let t;for(let n=0;n<=this.maxRetries;n++){if(this._disposed||e.cancelled)return;try{const t=yield this._downloadAttemptAsync(e);return void this._settle(e,()=>e.resolve(t))}catch(n){if(e.cancelAttempt=void 0,this._disposed||e.cancelled)return;t=n}}this._settle(e,()=>e.reject(t))})}_downloadAttemptAsync(e){return b(this,void 0,void 0,function*(){return yield new Promise((n,s)=>{e.cancelAttempt=s,e.request=t.Tools.LoadFile(e.url,e=>n(e),void 0,void 0,!0,(t,n)=>s(n instanceof Error?n:new Error(`GaussianSplattingDownloadManager: failed to load ${e.url}.`)))})})}}class gu{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}}class yu{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;const 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;const 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;const 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;const t=e._prev,n=e._next,s=t&&t._free,o=n&&n._free;s&&o?(t._size+=e._size+n._size,this._removeFromMainList(e),this._removeFromMainList(n),this._removeFromBucket(n),this._release(e),this._release(n),this._rebucket(t)):s?(t._size+=e._size,this._removeFromMainList(e),this._release(e),this._rebucket(t)):o?(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;const 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{const 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(),0===this._freeRegionCount||(0===e?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++){const n=t[e],s=this.allocate(n);if(!s){let s=n;for(let n=e+1;n<t.length;n++)s+=t[n];const o=this._usedSize+s,r=Math.ceil(o*this._growMultiplier);r>this._capacity&&this.grow(r),this.defrag(0);for(let n=e;n<t.length;n++)t[n]=this.allocate(t[n]);return!0}t[e]=s}return!1}_bucketFor(e){return 31-Math.clz32(e)}_addToBucket(e){const 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){const 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){const s=this._pool.length>0?this._pool.pop():new gu;return s._offset=e,s._size=t,s._free=n,s._prev=null,s._next=null,s._prevFree=null,s._nextFree=null,s._bucket=-1,s}_release(e){e._prev=null,e._next=null,e._prevFree=null,e._nextFree=null,e._bucket=-1,this._pool.push(e)}_insertAfterInMainList(e,t){null===t?(e._prev=null,e._next=this._headAll,this._headAll&&(this._headAll._prev=e),this._headAll=e,this._tailAll||(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){const t=this._bucketFor(e),n=this._freeBucketHeads.length;if(t<n){let n=null,s=this._freeBucketHeads[t];for(;s&&!(s._size>=e&&(!n||s._size<n._size)&&(n=s,s._size===e));)s=s._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;){const 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;const s=this._capacity-t;if(s>0){const e=this._obtain(t,s,!0);this._insertAfterInMainList(e,this._tailAll),this._addToBucket(e)}}_defragIncremental(e,t){const n=Math.ceil(e/2),s=e-n;for(let e=0;e<n;e++){let e=this._tailAll;for(;e&&e._free;)e=e._prev;if(!e)break;const n=this._findFreeBlock(e._size);if(!n||n._offset>=e._offset)break;this._moveBlock(e,n),t.add(e)}let o=this._headAll;for(let e=0;e<s&&o;){const n=o._next;if(o._free&&n&&!n._free){const s=n,r=o;s._offset=r._offset,r._offset=s._offset+s._size;const i=r._prev,a=s._next;if(s._prev=i,s._next=r,r._prev=s,r._next=a,i?i._next=s:this._headAll=s,a?a._prev=r:this._tailAll=r,r._next&&r._next._free){const e=r._next;r._size+=e._size,this._removeFromMainList(e),this._removeFromBucket(e),this._release(e),this._rebucket(r)}t.add(s),e++,o=r._next}else o=n}}_moveBlock(e,t){const n=e._size,s=t._offset,o=e._prev;this._removeFromMainList(e);const r=this._obtain(e._offset,n,!0);if(this._insertAfterInMainList(r,o),this._addToBucket(r),r._next&&r._next._free){const e=r._next;r._size+=e._size,this._removeFromMainList(e),this._removeFromBucket(e),this._release(e),this._rebucket(r)}if(r._prev&&r._prev._free){const e=r._prev;e._size+=r._size,this._removeFromMainList(r),this._removeFromBucket(r),this._release(r),this._rebucket(e)}if(e._offset=s,t._size===n){const 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)}}class vu{constructor(e,t,n){this._blocks=new Map,this._cooldown=new Map,this._pinned=new Set,this._allocator=new yu(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){var t;return null===(t=this._blocks.get(e))||void 0===t?void 0:t.offset}allocate(e,t){const n=this._blocks.get(e);if(n)return n.offset;let s=this._allocator.allocate(t);return s||(this._evictAllCooled(),s=this._allocator.allocate(t),s)?(this._blocks.set(e,s),s.offset):null}pin(e,t){const n=this.allocate(e,t);return null!==n&&this._pinned.add(e),n}free(e){if(this._pinned.has(e))return;const t=this._blocks.get(e);t&&(this._allocator.free(t),this._blocks.delete(e),this._cooldown.delete(e))}compact(){const e=new Map;for(const[t,n]of Array.from(this._blocks))e.set(t,n.offset);this._allocator.defrag(0);const t=[];for(const[n,s]of Array.from(this._blocks)){const o=e.get(n);o!==s.offset&&t.push({file:n,oldOffset:o,newOffset:s.offset,count:s.size})}return t}getResidentBlocks(){const e=[];for(const[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(0===this._cooldown.size)return[];const e=[];for(const[t,n]of Array.from(this._cooldown))n<=1?e.push(t):this._cooldown.set(t,n-1);for(const t of e)this._evict(t);return e}dispose(){this._blocks.clear(),this._cooldown.clear(),this._pinned.clear()}_evictAllCooled(){const e=Array.from(this._cooldown.keys());for(const t of e)this._evict(t)}_evict(e){const t=this._blocks.get(e);t&&(this._allocator.free(t),this._blocks.delete(e)),this._cooldown.delete(e),this._onEvict(e)}}const bu=Math.tan(22.5*Math.PI/180),xu=new t.Matrix,Tu=new t.Vector3,Au=new t.Vector3,Mu=new t.Vector3,wu=new t.Vector3(0,0,1),Cu=[[0,1],[1,2],[2,3],[3,0],[4,5],[5,6],[6,7],[7,4],[0,4],[1,5],[2,6],[3,7]],Ru=2*Cu.length,Su=[new t.Color4(1,.2,.2,1),new t.Color4(1,.6,.1,1),new t.Color4(1,1,.2,1),new t.Color4(.3,1,.3,1),new t.Color4(.2,1,1,1),new t.Color4(.4,.5,1,1),new t.Color4(.9,.4,1,1),new t.Color4(1,1,1,1)];class Ou extends t.GaussianSplattingMesh{static IsLODMetadata(e){if("object"!=typeof e||null===e)return!1;const t=e;return"number"==typeof t.lodLevels&&Array.isArray(t.filenames)&&"object"==typeof t.tree&&null!==t.tree}constructor(e,n,s,o,r={}){var i,a,l;super(e,null,o,!1),this._leafNodes=[],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._maxDetailLod=0,this._frustumCulling=!0,this._frustumPlanes=[new t.Plane(0,0,0,0),new t.Plane(0,0,0,0),new t.Plane(0,0,0,0),new t.Plane(0,0,0,0),new t.Plane(0,0,0,0),new t.Plane(0,0,0,0)],this._cullViewProj=new t.Matrix,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._decodedFiles=new Set,this._loadingFiles=new Set,this._decodeQueue=[],this._fileRefs=new Map,this._cancelledDecodes=new Set,this._evictionEnabled=!1,this._residentBudget=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._framesSinceLodUpdate=0,this._lastLodCamPos=new t.Vector3(1/0,1/0,1/0),this._forceLodUpdate=!1,this._boundsMin=new t.Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._boundsMax=new t.Vector3(-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=s,this._streamOptions=r,this._hostCompound=null!==(i=r.hostCompound)&&void 0!==i?i:null,this._decodeSh=null===(a=r.decodeSh)||void 0===a||a,this._needsRotationScale=null!==(l=r.needsRotationScale)&&void 0!==l&&l;const u=Math.max(0,n.lodLevels-1);if(this._lodRangeMax=u,void 0!==r.lodBaseDistance&&(this._lodBaseDistance=Math.max(.1,r.lodBaseDistance)),void 0!==r.lodMultiplier&&(this._lodMultiplier=Math.max(1.2,r.lodMultiplier)),void 0!==r.lodBehindPenalty&&(this._lodBehindPenalty=Math.max(1,r.lodBehindPenalty)),void 0!==r.lodRangeMin&&(this._lodRangeMin=Math.max(0,Math.min(r.lodRangeMin,u))),void 0!==r.lodRangeMax&&(this._lodRangeMax=Math.max(this._lodRangeMin,Math.min(r.lodRangeMax,u))),void 0!==r.maxDecodesPerFrame&&(this._maxDecodesPerFrame=Math.max(1,r.maxDecodesPerFrame)),void 0!==r.lodCooldownFrames&&(this._lodCooldownFrames=Math.max(0,r.lodCooldownFrames)),void 0!==r.lodUpdateInterval&&(this._lodUpdateInterval=Math.max(1,r.lodUpdateInterval)),void 0!==r.lodUpdateDistance&&(this._lodUpdateDistance=Math.max(0,r.lodUpdateDistance)),void 0!==r.maxDetailLod&&(this._maxDetailLod=Math.max(0,Math.floor(r.maxDetailLod))),void 0!==r.frustumCulling&&(this._frustumCulling=r.frustumCulling),r.debugLodSource&&(this._debugLodSource=r.debugLodSource),void 0!==r.evictionCooldownFrames&&(this._evictionCooldownFrames=Math.max(0,Math.floor(r.evictionCooldownFrames))),void 0!==r.maxResidentSplats&&r.maxResidentSplats>0&&(this._maxResidentSplats=Math.floor(r.maxResidentSplats)),void 0!==r.memoryBudgetMb&&r.memoryBudgetMb>0&&(this._memoryBudgetMb=r.memoryBudgetMb),this._downloadManager=new _u({maxConcurrent:r.maxConcurrentDownloads,maxRetries:r.maxDownloadRetries}),this._hostCompound){this.setEnabled(!1),this.isPickable=!1,this.doNotSerialize=!0,this._partReadyPromise=new Promise((e,t)=>{this._partReadyResolve=e,this._partReadyReject=t}),this._partReadyPromise.catch(()=>{});const e=this._hostCompound.onDisposeObservable.add(()=>{this._disposed||(this._partReleasedByHost=!0,this.dispose())});this._hostUnsubDispose=()=>this._hostCompound.onDisposeObservable.remove(e)}else this.scaling.y*=-1,this.rotation.x=-Math.PI/2;this._collectLodEntries(n.tree),r.debugDisplay&&(this.debugDisplay=!0),this._streamAllAsync().then(()=>{const e=this._partReadySettled;this._rejectPartReady("GaussianSplattingStream: stream produced no splats."),e||!this._hostCompound||this._disposed||this._disposeAndReclaim()},e=>{var n,s;t.Logger.Error("GaussianSplattingStream: streaming failed: "+(null!==(n=null==e?void 0:e.message)&&void 0!==n?n:e)),this._rejectPartReady("GaussianSplattingStream: streaming failed: "+(null!==(s=null==e?void 0:e.message)&&void 0!==s?s:e)),this._hostCompound&&!this._disposed&&this._disposeAndReclaim()})}getClassName(){return"GaussianSplattingStream"}isReady(e=!1){return!!this._hostCompound||super.isReady(e)}get streamingPartProxy(){var e,t;return null!==(t=null===(e=this._host)||void 0===e?void 0:e.proxy)&&void 0!==t?t:null}whenPartReadyAsync(){return b(this,void 0,void 0,function*(){var e;yield null!==(e=this._partReadyPromise)&&void 0!==e?e:Promise.resolve()})}_resolvePartReady(){var e;this._partReadySettled||(this._partReadySettled=!0,null===(e=this._partReadyResolve)||void 0===e||e.call(this))}_rejectPartReady(e){var t;this._partReadySettled||(this._partReadySettled=!0,null===(t=this._partReadyReject)||void 0===t||t.call(this,new Error(e)))}whenSettledAsync(){return b(this,arguments,void 0,function*(e=3){if(this._disposed)return;this._forceLodUpdate=!0;const t=Math.max(1,e),n=this._scene;let s=0;const o=()=>this._isLoadingIdle()&&this._sinkIsDepthSortSettled?++s>=t:(s=0,!1);if(n.getEngine().activeRenderLoops.length>0)return void(yield new Promise(e=>{let t=null;t=n.onAfterRenderObservable.add(()=>{(this._disposed||o())&&(t&&(n.onAfterRenderObservable.remove(t),t=null),e())})}));const r=n.getEngine(),i=globalThis.requestAnimationFrame;for(;!this._disposed;){if(r.beginFrame(),n.render(),r.endFrame(),o())return;yield new Promise(e=>{"function"==typeof i?i(()=>e()):setTimeout(e,16)})}})}_isLoadingIdle(){return this._baseLayerReady&&0===this._decodeQueue.length&&0===this._loadingFiles.size&&this._downloadManager.isIdle}get maxDetailLod(){return this._maxDetailLod}set maxDetailLod(e){const t=Math.max(0,Math.floor(e));this._maxDetailLod!==t&&(this._maxDetailLod=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){var t,n,s,o,r,i;this._disposed||(this._disposed=!0,this._rejectPartReady("GaussianSplattingStream: disposed before the part was ready."),null===(t=this._unsubBeforeRebuild)||void 0===t||t.call(this),null===(n=this._unsubAfterRebuild)||void 0===n||n.call(this),this._unsubBeforeRebuild=null,this._unsubAfterRebuild=null,null===(s=this._hostUnsubRemove)||void 0===s||s.call(this),null===(o=this._hostUnsubDispose)||void 0===o||o.call(this),this._hostUnsubRemove=null,this._hostUnsubDispose=null,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),this._lodObserver=null),this._clearDebugDisplay(),this._downloadManager.dispose(),null===(r=this._residency)||void 0===r||r.dispose(),this._residency=null,null===(i=this._workBuffer)||void 0===i||i.dispose(),this._workBuffer=null,super.dispose(e))}_disposeAndReclaim(){const 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)}evaluateOptimalLods(e=this._scene.activeCamera){if(!e||0===this._leafNodes.length)return;const n=Math.max(0,this._metadata.lodLevels-1),s=this._lodBaseDistance,o=this._lodMultiplier,r=this._lodBehindPenalty,i=this._lodRangeMin,a=this._lodRangeMax,l=this._scene.getEngine().getAspectRatio(e)||1;let u=Math.tan(.5*e.fov);e.fovMode===t.Camera.FOVMODE_HORIZONTAL_FIXED&&(u/=l);const c=u*l,d=Math.min(u,c)/bu;this._getEffectiveWorldMatrix(!1).invertToRef(xu);const h=t.Vector3.TransformCoordinatesToRef(e.globalPosition,xu,Tu),m=h.x,f=h.y,p=h.z;let _=0,g=0,y=0;if(r>1){e.getDirectionToRef(wu,Mu);const n=t.Vector3.TransformNormalToRef(Mu,xu,Au);n.normalize(),_=n.x,g=n.y,y=n.z}for(const e of this._leafNodes){const t=e.bound.min,l=e.bound.max,u=(m<t[0]?t[0]:m>l[0]?l[0]:m)-m,c=(f<t[1]?t[1]:f>l[1]?l[1]:f)-f,h=(p<t[2]?t[2]:p>l[2]?l[2]:p)-p,v=Math.sqrt(u*u+c*c+h*h);let b=v;if(r>1&&v>.01){const e=(_*u+g*c+y*h)/v;e<0&&(b=v*(1+-e*(r-1)))}const x=b*d;let T;if(0===n||x<s)T=0;else for(T=n;T>1&&x<s*Math.pow(o,T-1);)T--;T<i?T=i:T>a&&(T=a),this._frustumCulling&&!1===e.inFrustum&&(T=a),e.optimalLod=T}}_displayedLodLevel(e){var t,n,s;return"optimal"===this._debugLodSource?null!==(n=null!==(t=e.optimalLod)&&void 0!==t?t:e.activeLod)&&void 0!==n?n:0:null!==(s=e.activeLod)&&void 0!==s?s:0}_refreshDebugDisplay(){"optimal"===this._debugLodSource&&this.evaluateOptimalLods(),this._buildDebugMesh();const 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(){"optimal"===this._debugLodSource&&this.evaluateOptimalLods(),this._computeDebugSignature()!==this._debugSignature&&this._updateDebugColors()}_buildDebugMesh(){this._debugMesh&&(this._debugMesh.dispose(),this._debugMesh=null),this._debugColorData=null;const e=[],n=[];for(const s of this._leafNodes){const o=Su[this._displayedLodLevel(s)%Su.length],r=s.bound.min,i=s.bound.max,a=[new t.Vector3(r[0],r[1],r[2]),new t.Vector3(i[0],r[1],r[2]),new t.Vector3(i[0],i[1],r[2]),new t.Vector3(r[0],i[1],r[2]),new t.Vector3(r[0],r[1],i[2]),new t.Vector3(i[0],r[1],i[2]),new t.Vector3(i[0],i[1],i[2]),new t.Vector3(r[0],i[1],i[2])];for(const t of Cu)e.push([a[t[0]],a[t[1]]]),n.push([o,o])}if(this._debugSignature=this._computeDebugSignature(),0===e.length)return;const s=t.CreateLineSystem(this.name+"_lodDebug",{lines:e,colors:n,updatable:!0,useVertexAlpha:!1},this._scene);s.parent=this,s.isPickable=!1,s.doNotSerialize=!0,s.reservedDataStore={hidden:!0},this._debugMesh=s,this._debugColorData=new Float32Array(this._leafNodes.length*Ru*4)}_updateDebugColors(){if(!this._debugMesh||!this._debugColorData)return;const e=this._debugColorData;let n=0;for(const t of this._leafNodes){const s=Su[this._displayedLodLevel(t)%Su.length];for(let t=0;t<Ru;t++)e[n++]=s.r,e[n++]=s.g,e[n++]=s.b,e[n++]=s.a}this._debugMesh.updateVerticesData(t.VertexBuffer.ColorKind,e),this._debugSignature=this._computeDebugSignature()}_computeDebugSignature(){let e=0;for(const t of this._leafNodes)e=31*e+this._displayedLodLevel(t)|0;return e}_clearDebugDisplay(){this._debugObserver&&(this._scene.onBeforeRenderObservable.remove(this._debugObserver),this._debugObserver=null),this._debugMesh&&(this._debugMesh.dispose(),this._debugMesh=null),this._debugColorData=null,this._debugSignature=0}_collectLodEntries(e){if(e.children){for(const t of e.children)this._collectLodEntries(t);return}if(!e.lods)return;const n=[];for(const t of Object.keys(e.lods)){const s=Number(t),o=e.lods[t];Number.isFinite(s)&&o&&o.count>0&&n.push(s)}0!==n.length&&(n.sort((e,t)=>e-t),e.availableLevels=n,e.baseLod=n[n.length-1],e.activeLod=void 0,e.lodCooldown=0,e.inFrustum=!0,e.cullBounds=new t.BoundingInfo(t.Vector3.FromArray(e.bound.min),t.Vector3.FromArray(e.bound.max)),this._leafNodes.push(e))}_streamAllAsync(){return b(this,void 0,void 0,function*(){const e=this._collectAllFileIds(),n=yield this._gatherCountsAsync(e);if(this._disposed)return;this._resolveResidentBudget();let s=1;n>0&&(s+=n);for(const t of e){const e=this._fileCounts.get(t);void 0!==e&&e>0&&(s+=e)}if(s<=1)return;this._evictionEnabled=this._residentBudget>0&&this._residentBudget<s;const o=this._evictionEnabled?Math.max(this._residentBudget,1):s;if(this._residency=new vu(o,this._evictionCooldownFrames,e=>this._onFileEvicted(e)),this._residency.pin(-2,1),n>0){const e=this._residency.pin(-1,n);null!==e?this._environmentRange={offset:e,count:n}:(t.Logger.Warn("GaussianSplattingStream: environment does not fit the memory budget; skipping it."),this._environmentFiles=null)}if(this._hostCompound){const e=t.Matrix.Compose(new t.Vector3(1,-1,1),t.Quaternion.RotationYawPitchRoll(0,-Math.PI/2,0),t.Vector3.ZeroReadOnly),n=this._hostCompound.reserveStreamingPart(o,e,this.name+"_part",this._shTextureCount,this._streamShDegree,this._needsRotationScale);this._host=n,this._positionBase=n.base;const s=this._hostCompound,r=s.onPartRemovedObservable.add(e=>{!this._disposed&&this._host&&e===this._host.partIndex&&(this._partReleasedByHost=!0,this.dispose())});this._hostUnsubRemove=()=>s.onPartRemovedObservable.remove(r);const i=this._shTextureCount>0&&n.shMrtAtlas?{textureCount:this._shTextureCount,externalMrts:n.shMrtAtlas}:void 0,a=this._needsRotationScale&&n.rotMrtAtlas?{externalMrt:n.rotMrtAtlas}:void 0;this._workBuffer=new pu(this._scene,n.capacity,{mrt:n.mrtAtlas,width:n.atlasWidth,baseOffset:n.base},i,a),this._readbackCandidate=this._workBuffer.supportsAsyncCentersReadback,this._splatPositions=n.splatPositions,this._vertexCount=o;const l=this._workBuffer;this._unsubBeforeRebuild=n.onBeforeAtlasRebuild(()=>{l.backupRegion(),this._positionSnapshot=this._splatPositions?this._splatPositions.slice(4*this._positionBase,4*(this._positionBase+this._vertexCount)):null}),this._unsubAfterRebuild=n.onAfterAtlasRebuild(()=>{n.mrtAtlas&&l.rebindAtlas(n.mrtAtlas),l.rebindShAtlas(n.shMrtAtlas),l.rebindRotAtlas(n.rotMrtAtlas),this._positionBase=n.base,l.setBaseOffset(n.base),l.restoreRegion(),this._splatPositions=n.splatPositions,this._positionSnapshot&&this._splatPositions&&(this._splatPositions.set(this._positionSnapshot,4*this._positionBase),this._positionSnapshot=null)}),n.setActiveRanges([])}else{const e=this._shTextureCount>0?{textureCount:this._shTextureCount}:void 0,t=this._needsRotationScale?{}:void 0;this._workBuffer=new pu(this._scene,o,void 0,e,t),this._readbackCandidate=this._workBuffer.supportsAsyncCentersReadback;const n=new Float32Array(4*o),s=this._workBuffer.textures,r=e?this._workBuffer.shTextures:void 0,i=t?this._workBuffer.rotationTextures:void 0;this._setExternalWorkBuffer(s[0],s[1],s[2],s[3],n,o,r,this._streamShDegree,i),this.setSplatIndexRanges([]),this.setEnabled(!0)}if(this._host&&this._workBuffer&&(yield this._waitForCanBackupAsync(this._workBuffer),this._disposed))return;this._environmentRange&&this._environmentFiles&&(yield this._decodeEnvironmentAsync()),this._environmentFiles=null;const r=new Set;for(const e of this._leafNodes){const t=e.lods[String(e.baseLod)];t&&this._fileCounts.has(t.file)&&r.add(t.file)}for(const e of Array.from(r)){if(this._disposed)return;yield this._decodeFileAsync(e)}this._disposed||(this._baseLayerReady=!0,this._lodObserver||(this._lodObserver=this._scene.onBeforeRenderObservable.add(()=>this._onLodFrame())),this._resolvePartReady())})}_waitForCanBackupAsync(e){return b(this,void 0,void 0,function*(){for(let t=0;t<600&&!this._disposed;t++){if(e.canBackup)return;yield new Promise(e=>this._scene.onBeforeRenderObservable.addOnce(()=>e()))}this._disposed||e.canBackup||t.Logger.Warn("GaussianSplattingStream: backup/restore copy shaders did not compile in time; a grow/compaction before they are ready may drop streamed data.")})}_resolveResidentBudget(){let e=this._maxResidentSplats;if(this._memoryBudgetMb>0){const t=this._scene.getEngine().getCaps().textureHalfFloatRender?24:48,n=84+16*this._shTextureCount+(this._needsRotationScale?t:0),s=Math.floor(1024*this._memoryBudgetMb*1024/n);e=e>0?Math.min(e,s):s}this._residentBudget=e}_collectAllFileIds(){const e=new Set;for(const t of this._leafNodes)for(const n of t.availableLevels){const s=t.lods[String(n)];s&&e.add(s.file)}return Array.from(e).sort((e,t)=>e-t)}_gatherCountsAsync(e){return b(this,void 0,void 0,function*(){var n;let s=0,o=0,r=0;const i=e=>{const t=Ou._GetShInfo(e);t.degree>o&&(o=t.degree),t.coeffs>r&&(r=t.coeffs)};if(this._metadata.environment)try{const e=this._rootUrl+this._metadata.environment,t=yield this._downloadManager.loadFileAsync(e),n=yield this._unzipAsync(new Uint8Array(t)),o=n.get("meta.json");if(o){const e=JSON.parse((new TextDecoder).decode(o));s=Ou._GetSplatCount(e),i(e),this._environmentFiles=n}}catch(e){t.Logger.Warn("GaussianSplattingStream: failed to load environment: "+(null!==(n=null==e?void 0:e.message)&&void 0!==n?n:e))}yield Promise.all(e.map(e=>b(this,void 0,void 0,function*(){var n;const s=this._metadata.filenames[e];if(s)try{const t=this._rootUrl+s,n=t.substring(0,t.lastIndexOf("/")+1),o=yield this._downloadManager.loadFileAsync(t),r=JSON.parse((new TextDecoder).decode(new Uint8Array(o)));this._fileCounts.set(e,Ou._GetSplatCount(r)),this._fileMeta.set(e,{sogData:r,subRootUrl:n})}catch(e){t.Logger.Warn(`GaussianSplattingStream: failed to load metadata for ${s}: ${null!==(n=null==e?void 0:e.message)&&void 0!==n?n:e}`)}else t.Logger.Warn(`GaussianSplattingStream: missing filename for file index ${e}.`)})));for(const{sogData:e}of this._fileMeta.values())i(e);return this._decodeSh&&o>0&&r>0&&(this._streamShDegree=o,this._shTextureCount=Math.ceil(3*r/16)),s})}_enqueueDecode(e){this._decodedFiles.has(e)||this._loadingFiles.has(e)||!this._fileMeta.has(e)||-1===this._decodeQueue.indexOf(e)&&this._decodeQueue.push(e)}_pumpDecodeQueue(){let e=0;for(;this._decodeQueue.length>0&&e<this._maxDecodesPerFrame;){const n=this._decodeQueue.shift();this._decodedFiles.has(n)||this._loadingFiles.has(n)||(e++,this._decodeFileAsync(n).catch(e=>{var n;t.Logger.Warn("GaussianSplattingStream: decode failed: "+(null!==(n=null==e?void 0:e.message)&&void 0!==n?n:e))}))}}_applyPositions(e,t,n){this._splatPositions.set(e,4*(this._positionBase+t)),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}_probeReadbackAsync(e,n,s){return b(this,void 0,void 0,function*(){if(this._readbackProbed=!0,!this._workBuffer)return;const o=Math.min(n,1024);let r=!1;try{const t=yield this._workBuffer.readCentersRangeAsync(e,o);if(this._disposed)return;if(t&&t.length>=4*o){r=!0;for(let e=0;e<o&&r;e++)for(let n=0;n<3;n++){const o=t[4*e+n],i=s[4*e+n];if(Math.abs(o-i)>.01*(1+Math.abs(i))){r=!1;break}}}}catch(e){r=!1}this._useGpuPositionReadback=r,t.Logger.Log(r?"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.")})}_applyDecodedPositionsAsync(e,t,n){return b(this,void 0,void 0,function*(){if(this._useGpuPositionReadback&&this._workBuffer){const e=yield this._workBuffer.readCentersRangeAsync(t,n);if(this._disposed)return!1;if(e&&this._splatPositions)return this._applyPositions(e,t,n),!0}const s=e.positions.length>=4*n?e.positions.subarray(0,4*n):null;return!(!s||!this._splatPositions||(this._applyPositions(s,t,n),!this._readbackProbed&&this._readbackCandidate&&(yield this._probeReadbackAsync(t,n,s)),0))})}_decodeEnvironmentAsync(){return b(this,void 0,void 0,function*(){var e;if(!this._environmentRange||!this._environmentFiles||!this._workBuffer)return;const n=this._environmentRange;try{const e=(yield hu(this._environmentFiles,"",this._scene,!this._useGpuPositionReadback,this._downloadManager)).sogTextures;if(!e)return;try{if(this._disposed||!this._workBuffer)return;if(yield this._workBuffer.decodeAsync(e,n.offset),this._disposed)return;if(yield this._applyDecodedPositionsAsync(e,n.offset,n.count),this._disposed)return;this._refreshActiveRanges()}finally{Ou._DisposePack(e)}}catch(n){t.Logger.Warn("GaussianSplattingStream: failed to decode environment: "+(null!==(e=null==n?void 0:n.message)&&void 0!==e?e:n))}})}_decodeFileAsync(e){return b(this,void 0,void 0,function*(){if(this._decodedFiles.has(e)||this._loadingFiles.has(e)||!this._residency)return;const n=this._fileMeta.get(e),s=this._fileCounts.get(e);if(!n||void 0===s)return;this._loadingFiles.add(e),this._cancelledDecodes.delete(e);let o=!1;try{const r=(yield hu(n.sogData,n.subRootUrl,this._scene,!this._useGpuPositionReadback,this._downloadManager,e)).sogTextures;if(!r)return;const i=yield this._acquireDecodeGateAsync();try{if(this._disposed||!this._workBuffer||this._cancelledDecodes.has(e))return;let n=this._residency.allocate(e,s);if(null===n&&(n=yield this._relayoutAndAllocateAsync(e,s)),null===n)return void(this._cancelledDecodes.has(e)||t.Logger.Warn(`GaussianSplattingStream: resident memory budget full; skipping LOD file ${e}.`));if(o=!0,this._disposed||!this._workBuffer||this._cancelledDecodes.has(e))return;if(yield this._workBuffer.decodeAsync(r,n),this._disposed||this._cancelledDecodes.has(e))return;if(yield this._applyDecodedPositionsAsync(r,n,s),this._disposed)return;this._decodedFiles.add(e),this._applyDesiredLods()&&this._refreshActiveRanges()}finally{Ou._DisposePack(r),i()}}catch(t){if(!this._cancelledDecodes.has(e))throw t}finally{o&&!this._decodedFiles.has(e)&&this._residency.free(e),this._loadingFiles.delete(e),this._cancelledDecodes.delete(e)}})}_acquireDecodeGateAsync(){return b(this,void 0,void 0,function*(){const e=this._decodeGate;let t;return this._decodeGate=new Promise(e=>{t=e}),yield e,t})}_relayoutAndAllocateAsync(e,t){return b(this,void 0,void 0,function*(){return this._residency&&this._workBuffer?this._residency.freeSize<t?null:yield new Promise(n=>{const s=()=>{!this._disposed&&this._residency&&this._workBuffer&&!this._cancelledDecodes.has(e)?this._workBuffer.isRelayoutReady()?(this._performRelayout(),n(this._residency.allocate(e,t))):this._scene.onBeforeRenderObservable.addOnce(s):n(null)};this._scene.onBeforeRenderObservable.addOnce(s)}):null})}_performRelayout(){if(!this._residency||!this._workBuffer||!this._splatPositions)return;const e=this._relayoutOldOffsets;e.clear();for(const t of this._residency.getResidentBlocks())e.set(t.file,t.offset);if(0===this._residency.compact().length)return;const t=this._residency.capacity;this._relayoutSrcIndex&&this._relayoutSrcIndex.length===t||(this._relayoutSrcIndex=new Float32Array(t));const n=this._relayoutSrcIndex;n.fill(-1);const s=this._residency.getResidentBlocks();for(const t of s){const s=e.get(t.file);for(let e=0;e<t.count;e++)n[t.offset+e]=s+e}this._workBuffer.relayoutSync(n);const o=this._splatPositions,r=this._positionBase;s.sort((e,t)=>e.offset-t.offset);for(const t of s){const n=e.get(t.file);n!==t.offset&&o.copyWithin(4*(r+t.offset),4*(r+n),4*(r+n+t.count))}if(this._environmentRange){const e=this._residency.offset(-1);void 0!==e&&(this._environmentRange.offset=e)}this._sinkNotifyDataChanged(),this._refreshActiveRanges()}_onFileEvicted(e){this._decodedFiles.delete(e)}_cappedLevelForNode(e,t){const n=e.availableLevels,s=this._maxDetailLod;let o=-1,r=Number.POSITIVE_INFINITY;for(const e of n){if(e<s)continue;const n=Math.abs(e-t);n<r&&(o=e,r=n)}return o<0?e.baseLod:o}_computeTargetLevels(){var e;for(const t of this._leafNodes){const n=null!==(e=t.optimalLod)&&void 0!==e?e:t.baseLod;t.targetLevel=this._cappedLevelForNode(t,n)}}_applyDesiredLods(){var e;let t=!1;for(const n of this._leafNodes){if(n.lodCooldown&&n.lodCooldown>0)continue;const s=null!==(e=n.targetLevel)&&void 0!==e?e:n.baseLod;let o;if(s!==n.activeLod){const e=n.lods[String(s)];e&&(this._decodedFiles.has(e.file)?(this._switchActiveFile(n,e.file),n.activeLod=s,n.lodCooldown=this._lodCooldownFrames,t=!0):o=e.file)}n.pendingFile!==o&&(void 0!==n.pendingFile&&this._releaseFileRef(n.pendingFile),void 0!==o&&this._acquirePendingFile(o),n.pendingFile=o)}return t}_switchActiveFile(e,t){e.activeFile!==t&&(void 0!==e.activeFile&&this._releaseFileRef(e.activeFile),this._acquireFileRef(t),e.activeFile=t)}_acquireFileRef(e){var t,n;const s=(null!==(t=this._fileRefs.get(e))&&void 0!==t?t:0)+1;this._fileRefs.set(e,s),1===s&&(null===(n=this._residency)||void 0===n||n.cancelEviction(e))}_acquirePendingFile(e){this._acquireFileRef(e),this._enqueueDecode(e)}_releaseFileRef(e){var t,n;const s=(null!==(t=this._fileRefs.get(e))&&void 0!==t?t:0)-1;if(s>0)return void this._fileRefs.set(e,s);if(this._fileRefs.delete(e),this._decodedFiles.has(e))return void(this._evictionEnabled&&(null===(n=this._residency)||void 0===n||n.scheduleEviction(e)));const o=this._decodeQueue.indexOf(e);-1!==o&&this._decodeQueue.splice(o,1),this._loadingFiles.has(e)&&(this._cancelledDecodes.add(e),this._downloadManager.cancelGroup(e))}_onLodFrame(){var e;if(this._disposed||!this._baseLayerReady)return;let n=!1;for(const e of this._leafNodes)e.lodCooldown&&e.lodCooldown>0&&(e.lodCooldown--,0===e.lodCooldown&&void 0!==e.targetLevel&&e.targetLevel!==e.activeLod&&(n=!0));this._evictionEnabled&&(null===(e=this._residency)||void 0===e||e.tick()),this._pumpDecodeQueue();const s=this._updateNodeFrustum();let o=this._forceLodUpdate||s||n;if(!o&&++this._framesSinceLodUpdate>=this._lodUpdateInterval){const e=this._scene.activeCamera,n=this._lodUpdateDistance;(!e||t.Vector3.DistanceSquared(e.globalPosition,this._lastLodCamPos)>=n*n)&&(e&&this._lastLodCamPos.copyFrom(e.globalPosition),o=!0)}o&&(this._forceLodUpdate=!1,this._framesSinceLodUpdate=0,this.evaluateOptimalLods(this._scene.activeCamera),this._computeTargetLevels(),this._applyDesiredLods()&&this._refreshActiveRanges())}_updateNodeFrustum(){const e=this._scene.activeCamera;let n=!1;if(!this._frustumCulling||!e){for(const e of this._leafNodes)!1===e.inFrustum&&(e.inFrustum=!0,n=!0);return n}const s=this._getEffectiveWorldMatrix(!1);e.getViewMatrix().multiplyToRef(e.getProjectionMatrix(),this._cullViewProj),t.Frustum.GetPlanesToRef(this._cullViewProj,this._frustumPlanes);for(const e of this._leafNodes){e.cullBounds.update(s);const t=e.cullBounds.isInFrustum(this._frustumPlanes);t!==e.inFrustum&&(e.inFrustum=t,n=!0)}return n}static _GetSplatCount(e){var t;return null!==(t=e.count)&&void 0!==t?t:Array.isArray(e.means.shape)?e.means.shape[0]:0}static _GetShInfo(e){if(!e.shN)return{degree:0,coeffs:0};let n=0;const s=e.shN.bands;if("number"==typeof s&&Number.isFinite(s)&&s>0)n=Math.floor(s);else if(Array.isArray(e.shN.shape)&&Number.isFinite(e.shN.shape[1])&&e.shN.shape[1]>0){const t=Math.floor(e.shN.shape[1]/3);n=t>0?Math.round(Math.sqrt(t+1)-1):0}return n>0?(n>4&&(t.Logger.Warn(`GaussianSplattingStream: SH degree ${n} exceeds the maximum supported (4); clamping.`),n=4),{degree:n,coeffs:Math.pow(n+1,2)-1}):{degree:0,coeffs:0}}static _DisposePack(e){var t,n,s;e.meansTextureL.dispose(),e.meansTextureU.dispose(),e.scalesTexture.dispose(),e.quatsTexture.dispose(),e.sh0Texture.dispose(),null===(t=e.shCentroidsTexture)||void 0===t||t.dispose(),null===(n=e.shLabelsTexture)||void 0===n||n.dispose(),null===(s=e.codebookTexture)||void 0===s||s.dispose()}_updateBounds(e,n){const s=this._boundsMin,o=this._boundsMax;for(let t=0;t<n;t++){const n=e[4*t+0],r=e[4*t+1],i=e[4*t+2];s.minimizeInPlaceFromFloats(n,r,i),o.maximizeInPlaceFromFloats(n,r,i)}this._host?this._host.expandBounds(s,o):this.setBoundingInfo(new t.BoundingInfo(s,o))}_refreshActiveRanges(){var e;const t=[];this._environmentRange&&t.push({offset:this._environmentRange.offset,count:this._environmentRange.count});for(const n of this._leafNodes){if(void 0===n.activeLod)continue;const s=n.lods[String(n.activeLod)];if(!s)continue;const o=null===(e=this._residency)||void 0===e?void 0:e.offset(s.file);void 0!==o&&t.push({offset:o+s.offset,count:s.count})}this._sinkSetActiveRanges(Ou._CoalesceRanges(t))}static _CoalesceRanges(e){if(e.length<=1)return e;const 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++){const s=n[n.length-1],o=t[e],r=s.offset+s.count;if(o.offset<=r){const e=Math.max(r,o.offset+o.count);s.count=e-s.offset}else n.push({offset:o.offset,count:o.count})}return n}_unzipAsync(e){return b(this,void 0,void 0,function*(){var n;let s=this._streamOptions.fflate;s||(void 0===window.fflate&&(yield t.Tools.LoadScriptAsync(null!==(n=this._streamOptions.deflateURL)&&void 0!==n?n:"https://unpkg.com/fflate/umd/index.js")),s=window.fflate);const o=s.unzipSync(e),r=new Map;for(const[e,t]of Object.entries(o))r.set(e,t);return r})}}const Fu=.28209479177387814;let Eu=null,Iu=null;class Lu{constructor(e={}){this.name=ru.name,this._assetContainer=null,this.extensions=ru.extensions,this._loadingOptions=Object.assign(Object.assign({},Lu._DefaultLoadingOptions),e)}createPlugin(e){return new Lu(e[ru.name])}importMeshAsync(e,t,n,s,o,r){return b(this,void 0,void 0,function*(){const o=this._tryCreateLODStream(t,n,s);return o?{meshes:[o],particleSystems:[],skeletons:[],animationGroups:[],transformNodes:[],geometries:[],lights:[],spriteManagers:[]}:yield this._parseAsync(e,t,n,s).then(e=>({meshes:e,particleSystems:[],skeletons:[],animationGroups:[],transformNodes:[],geometries:[],lights:[],spriteManagers:[]}))})}_tryCreateLODStream(e,t,n){if("string"!=typeof t)return null;let s;try{s=JSON.parse(t)}catch(e){return null}if(!Ou.IsLODMetadata(s))return null;const o=e._blockEntityCollection;e._blockEntityCollection=!!this._assetContainer;try{const t=new Ou("GaussianSplattingStream",s,n,e,{deflateURL:this._loadingOptions.deflateURL,fflate:this._loadingOptions.fflate});return t._parentContainer=this._assetContainer,t}finally{e._blockEntityCollection=o}}static _BuildPointCloud(e,n){if(!n.byteLength)return!1;const s=new Uint8Array(n),o=new Float32Array(n),r=s.length/32;return e.addPoints(r,function(e,n){const r=o[8*n+0],i=o[8*n+1],a=o[8*n+2];e.position=new t.Vector3(r,i,a);const l=s[32*n+24+0]/255,u=s[32*n+24+1]/255,c=s[32*n+24+2]/255;e.color=new t.Color4(l,u,c,1)}),!0}static _BuildMesh(e,n){const s=new t.Mesh("PLYMesh",e),o=new Uint8Array(n.data),r=new Float32Array(n.data),i=o.length/32,a=[],l=new t.VertexData;for(let e=0;e<i;e++){const t=r[8*e+0],n=r[8*e+1],s=r[8*e+2];a.push(t,n,s)}if(n.hasVertexColors){const e=new Float32Array(4*i);for(let t=0;t<i;t++){const n=o[32*t+24+0]/255,s=o[32*t+24+1]/255,r=o[32*t+24+2]/255;e[4*t+0]=n,e[4*t+1]=s,e[4*t+2]=r,e[4*t+3]=1}l.colors=e}return l.positions=a,l.indices=n.faces,l.applyToMesh(s),s}_unzipWithFFlateAsync(e){return b(this,void 0,void 0,function*(){var n;let s=this._loadingOptions.fflate;s||(void 0===window.fflate&&(yield t.Tools.LoadScriptAsync(null!==(n=this._loadingOptions.deflateURL)&&void 0!==n?n:"https://unpkg.com/fflate/umd/index.js")),s=window.fflate);const{unzipSync:o}=s,r=o(e),i=new Map;for(const[e,t]of Object.entries(r))i.set(e,t);return i})}_parseAsync(e,n,s,o){const r=[],i=e=>{var s;n._blockEntityCollection=!!this._assetContainer;const o=null!==(s=this._loadingOptions.gaussianSplattingMesh)&&void 0!==s?s:new t.GaussianSplattingMesh("GaussianSplatting",null,n,this._loadingOptions.keepInRam,this._loadingOptions.needsRotationScaleTextures);o._parentContainer=this._assetContainer,r.push(o),e.sogTextures?o.setSogTextureData(e.sogTextures):o.updateData(e.data,e.sh,{flipY:!1},void 0,e.shDegree),o.scaling.y*=-1,o.computeWorldMatrix(!0),o.safeOrbitCameraLimits=Lu._ExtractSafeOrbitLimits(e),n._blockEntityCollection=!1},a=n.getEngine();let l=this._loadingOptions.useSogTextures;l&&!a.isWebGPU&&a.version<2&&(t.Logger.Warn("SPLATFileLoader: useSogTextures requires WebGL2 or WebGPU. Falling back to CPU path."),l=!1);const u=l?hu:lu;if("string"==typeof s){const e=JSON.parse(s);if(e&&e.means&&e.scales&&e.quats&&e.sh0)return new Promise((t,s)=>{u(e,o,n).then(e=>{i(e),t(r)}).catch(e=>{s(new Error("Failed to parse SOG data.",{cause:e}))})})}const c=s instanceof ArrayBuffer?new Uint8Array(s):s;if(80===c[0]&&75===c[1])return new Promise((e,t)=>{this._unzipWithFFlateAsync(c).then(s=>{u(s,o,n).then(t=>{i(t),e(r)}).catch(e=>{t(new Error("Failed to parse SOG zip data.",{cause:e}))})})});const d=e=>{Lu._ConvertPLYToSplat(s).then(s=>b(this,void 0,void 0,function*(){var o;switch(n._blockEntityCollection=!!this._assetContainer,s.mode){case 0:{const e=null!==(o=this._loadingOptions.gaussianSplattingMesh)&&void 0!==o?o:new t.GaussianSplattingMesh("GaussianSplatting",null,n,this._loadingOptions.keepInRam,this._loadingOptions.needsRotationScaleTextures);switch(e._parentContainer=this._assetContainer,r.push(e),e.updateData(s.data,s.sh,{flipY:!1},void 0,s.shDegree),e.scaling.y*=-1,"RightHanded"===s.chirality&&(e.scaling.y*=-1),s.upAxis){case"X":e.rotation=new t.Vector3(0,0,Math.PI/2);break;case"Y":e.rotation=new t.Vector3(0,0,Math.PI);break;case"Z":e.rotation=new t.Vector3(-Math.PI/2,Math.PI,0)}e.computeWorldMatrix(!0),e.safeOrbitCameraLimits=Lu._ExtractSafeOrbitLimits(s)}break;case 1:{const e=new t.PointsCloudSystem("PointCloud",1,n);Lu._BuildPointCloud(e,s.data)?yield e.buildMeshAsync().then(e=>{r.push(e)}):e.dispose()}break;case 2:if(!s.faces)throw new Error("PLY mesh doesn't contain face informations.");r.push(Lu._BuildMesh(n,s));break;default:throw new Error("Unsupported Splat mode")}n._blockEntityCollection=!1,this.applyAutoCameraLimits(Lu._ExtractSafeOrbitLimits(s),n),e(r)}))},h=31===c[0]&&139===c[1],m=78===c[0]&&71===c[1]&&83===c[2]&&80===c[3];if(!h&&!m)return new Promise(e=>{d(e)});const f=(e,s)=>{var o;n._blockEntityCollection=!!this._assetContainer;const i=null!==(o=this._loadingOptions.gaussianSplattingMesh)&&void 0!==o?o:new t.GaussianSplattingMesh("GaussianSplatting",null,n,this._loadingOptions.keepInRam,this._loadingOptions.needsRotationScaleTextures);if(e.trainedWithAntialiasing){const e=i.material;e.kernelSize=.1,e.compensation=!0}i._parentContainer=this._assetContainer,r.push(i),i.updateData(e.data,e.sh,{flipY:!1},void 0,e.shDegree),this._loadingOptions.flipY||(i.scaling.y*=-1,i.computeWorldMatrix(!0)),n._blockEntityCollection=!1;const a=Lu._ExtractSafeOrbitLimits(e);i.safeOrbitCameraLimits=a,this.applyAutoCameraLimits(a,n),s(r)};if(this._loadingOptions.spzLibraryUrl)return function(e){return b(this,void 0,void 0,function*(){if(Eu&&Iu===e)return yield Eu;const n=t._LoadScriptModuleAsync(`import createSpzModule from '${e}';\n const module = await createSpzModule();\n const returnedValue = module;`);return Iu=e,Eu=n,yield n})}(this._loadingOptions.spzLibraryUrl).then(e=>function(e,n){return b(this,void 0,void 0,function*(){return yield t.runCoroutineAsync(function*(e,n,s=!1){const o=e.numPoints,r=new ArrayBuffer(32*o),i=new Float32Array(r),a=new Uint8Array(r),l=e.positions,u=e.scales,c=e.colors,d=e.alphas,h=e.rotations;let m=null;const f=e.shDegree;let p,_,g=null,y=0,v=null,b=null,x=null;if(f>0&&e.sh.length>0){y=3*((f+1)*(f+1)-1);const s=Math.ceil(y/16),r=n.getEngine().getCaps().maxTextureSize,i=Math.ceil(o/r);m=t.AllocateShBuffers(s,i*r*4*4),v=new Int32Array(s),b=new Int32Array(s);for(let e=0;e<s;e++)v[e]=16*e,b[e]=Math.min(16*(e+1),y);x=m,g=e.sh}for(let e=0;e<o;e++){const t=8*e,n=32*e,o=3*e,r=4*e;i[t+0]=l[o+0],i[t+1]=l[o+1],i[t+2]=l[o+2],i[t+3]=Math.exp(u[o+0]),i[t+4]=Math.exp(u[o+1]),i[t+5]=Math.exp(u[o+2]);const m=255*(.5+Fu*c[o+0]),f=255*(.5+Fu*c[o+1]),p=255*(.5+Fu*c[o+2]);a[n+24]=m<=0?0:m>=255?255:m+.5|0,a[n+25]=f<=0?0:f>=255?255:f+.5|0,a[n+26]=p<=0?0:p>=255?255:p+.5|0,a[n+27]=1/(1+Math.exp(-d[e]))*255+.5|0;const _=127.5*h[r+3]+127.5,T=127.5*h[r+0]+127.5,A=127.5*h[r+1]+127.5,M=127.5*h[r+2]+127.5;if(a[n+28]=_<=0?0:_>=255?255:_+.5|0,a[n+29]=T<=0?0:T>=255?255:T+.5|0,a[n+30]=A<=0?0:A>=255?255:A+.5|0,a[n+31]=M<=0?0:M>=255?255:M+.5|0,g&&x&&v&&b){const t=e*y,n=16*e;for(let e=0;e<x.length;e++){const s=x[e],o=v[e],r=b[e];for(let e=o;e<r;e++){const r=128*g[t+e]+128;s[n+e-o]=r<=0?0:r>=255?255:r+.5|0}}}e%32768==0&&s&&(yield)}if(e.extensions)for(const t of e.extensions){const e=t;if(void 0!==e.safeOrbitRadiusMin){p=e.safeOrbitRadiusMin,_=[e.safeOrbitElevationMin,e.safeOrbitElevationMax];break}}return{mode:0,data:r,hasVertexColors:!1,sh:null!==m?m:void 0,shDegree:f>0?f:void 0,trainedWithAntialiasing:!!e.antialiased,safeOrbitCameraRadiusMin:p,safeOrbitCameraElevationMinMax:_}}(e,n,!0),t.createYieldingScheduler())})}(e.loadSpzFromBuffer(new Uint8Array(s),{to:e.CoordinateSystem.RUB}),n).then(e=>new Promise(t=>{f(e,t)})));if(m)return Promise.reject(new 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."));const p=new ReadableStream({start(e){e.enqueue(new Uint8Array(s)),e.close()}}),_=new DecompressionStream("gzip"),g=p.pipeThrough(_);return new Promise(e=>{new Response(g).arrayBuffer().then(s=>{(function(e,n){const s=new Uint8Array(e),o=new Uint32Array(e.slice(0,12)),r=o[2],i=s[12],a=s[13],l=s[14],u=s[15],c=o[1];if(u||1347635022!=o[0]||c<2||c>4)return new Promise(e=>{e({mode:3,data:new ArrayBuffer(0),hasVertexColors:!1})});const d=new ArrayBuffer(32*r),h=1/(1<<a),m=new Int32Array(1),f=new Uint8Array(m.buffer),p=function(e,t){return f[0]=e[t+0],f[1]=e[t+1],f[2]=e[t+2],f[3]=128&e[t+2]?255:0,m[0]*h};let _=16;const g=new Float32Array(d),y=new Float32Array(d),v=new Uint8ClampedArray(d),b=new Uint8ClampedArray(d);for(let e=0;e<r;e++)g[8*e+0]=p(s,_+0),g[8*e+1]=p(s,_+3),g[8*e+2]=p(s,_+6),_+=9;for(let e=0;e<r;e++){for(let n=0;n<3;n++){const o=(s[_+r+3*e+n]-127.5)/38.25;v[32*e+24+n]=t.Scalar.Clamp(255*(.5+Fu*o),0,255)}v[32*e+24+3]=s[_+e]}_+=4*r;for(let e=0;e<r;e++)y[8*e+3+0]=Math.exp(s[_+0]/16-10),y[8*e+3+1]=Math.exp(s[_+1]/16-10),y[8*e+3+2]=Math.exp(s[_+2]/16-10),_+=3;if(c>=3){const e=Math.SQRT1_2;for(let t=0;t<r;t++){const n=[s[_+0],s[_+1],s[_+2],s[_+3]],o=n[0]+(n[1]<<8)+(n[2]<<16)+(n[3]<<24),r=511,i=[],a=o>>>30;let l=o,u=0;for(let t=3;t>=0;--t)if(t!==a){const n=l&r,s=l>>>9&1;l>>>=10,i[t]=e*(n/r),1===s&&(i[t]=-i[t]),u+=i[t]*i[t]}const c=1-u;i[a]=Math.sqrt(Math.max(c,0));const d=[3,0,1,2];for(let e=0;e<4;e++)b[32*t+28+e]=Math.round(127.5+127.5*i[d[e]]);_+=4}}else for(let e=0;e<r;e++){const t=s[_+0],n=s[_+1],o=s[_+2],r=t/127.5-1,i=n/127.5-1,a=o/127.5-1;b[32*e+28+1]=t,b[32*e+28+2]=n,b[32*e+28+3]=o;const l=1-(r*r+i*i+a*a);b[32*e+28+0]=127.5+127.5*Math.sqrt(l<0?0:l),_+=3}if(i){const e=3*((i+1)*(i+1)-1),o=Math.ceil(e/16);let a=_;const u=n.getEngine().getCaps().maxTextureSize,c=Math.ceil(r/u),h=t.AllocateShBuffers(o,c*u*4*4);for(let t=0;t<r;t++)for(let n=0;n<e;n++){const e=s[a++],o=Math.floor(n/16);h[o][n%16+16*t]=e}return new Promise(e=>{e({mode:0,data:d,hasVertexColors:!1,sh:h,shDegree:i,trainedWithAntialiasing:!!l})})}return new Promise(e=>{e({mode:0,data:d,hasVertexColors:!1,trainedWithAntialiasing:!!l})})})(s,n,this._loadingOptions).then(t=>{f(t,e)})}).catch(()=>{d(e)})})}static _ExtractSafeOrbitLimits(e){return void 0===e.safeOrbitCameraRadiusMin&&void 0===e.safeOrbitCameraElevationMinMax?null:{radiusMin:e.safeOrbitCameraRadiusMin,elevationMinMax:e.safeOrbitCameraElevationMinMax}}applyAutoCameraLimits(e,t){var n;if(!this._loadingOptions.disableAutoCameraLimits&&e&&"ArcRotateCamera"===(null===(n=t.activeCamera)||void 0===n?void 0:n.getClassName())){const n=t.activeCamera;e.elevationMinMax&&(n.lowerBetaLimit=.5*Math.PI-e.elevationMinMax[1],n.upperBetaLimit=.5*Math.PI-e.elevationMinMax[0]),e.radiusMin&&(n.lowerRadiusLimit=e.radiusMin)}}loadAssetContainerAsync(e,n,s){const o=new t.AssetContainer(e);return this._assetContainer=o,this.importMeshAsync(null,e,n,s).then(e=>{for(const t of e.meshes)o.meshes.push(t);return this._assetContainer=null,o}).catch(e=>{throw this._assetContainer=null,e})}loadAsync(e,t,n){return this.importMeshAsync(null,e,t,n).then(()=>{})}static _ConvertPLYToSplat(e){const n=new Uint8Array(e),s=(new TextDecoder).decode(n.slice(0,10240)),o=s.indexOf("end_header\n");if(o<0||!s)return new Promise(t=>{t({mode:0,data:e,rawSplat:!0})});const r=parseInt(/element vertex (\d+)\n/.exec(s)[1]),i=/element face (\d+)\n/.exec(s);let a=0;i&&(a=parseInt(i[1]));const l=/element chunk (\d+)\n/.exec(s);let u=0;l&&(u=parseInt(l[1]));let c=0,d=0;const h={double:8,int:4,uint:4,float:4,short:2,ushort:2,uint16:2,uchar:1,list:0};let m=1;const f=[],p=[],_=s.slice(0,o).split("\n"),g={};for(const n of _)if(n.startsWith("property ")){const[,s,o]=n.split(" ");if(1==m)p.push({name:o,type:s,offset:d}),d+=h[s];else if(0==m)f.push({name:o,type:s,offset:c}),c+=h[s];else if(2==m)f.push({name:o,type:s,offset:c});else if(3==m){const t=new DataView(e,d,2*h.float);g.safeOrbitCameraElevationMinMax=[t.getFloat32(0,!0),t.getFloat32(4,!0)]}else if(4==m){const t=new DataView(e,d,h.float);g.safeOrbitCameraRadiusMin=t.getFloat32(0,!0)}else if(5==m){const t=new DataView(e,d,h.uchar);"up_axis"==o?g.upAxis=0==t.getUint8(0)?"X":1==t.getUint8(0)?"Y":"Z":"chirality"==o&&(g.chirality=0==t.getUint8(0)?"LeftHanded":"RightHanded")}h[s]||t.Logger.Warn(`Unsupported property type: ${s}.`)}else if(n.startsWith("element ")){const[,e]=n.split(" ");"chunk"==e?m=1:"vertex"==e?m=0:"sh"==e?m=2:"safe_orbit_camera_elevation_min_max_radians"==e?m=3:"safe_orbit_camera_radius_min"==e?m=4:"up_axis"!=e&&"chirality"!=e||(m=5)}const y=c,v=d;return t.GaussianSplattingMesh.ConvertPLYWithSHToSplatAsync(e).then(t=>b(this,void 0,void 0,function*(){const n=new DataView(e,o+11);let s=v*u+y*r;const i=[];if(a)for(let e=0;e<a;e++){const e=n.getUint8(s);if(3==e){s+=1;for(let t=0;t<e;t++){const e=n.getUint32(s+4*(2-t),!0);i.push(e)}s+=12}}if(u)return yield new Promise(e=>{e({mode:0,data:t.buffer,sh:t.sh,shDegree:t.shDegree,faces:i,hasVertexColors:!1,compressed:!0,rawSplat:!1})});let l=0,c=0;const d=["x","y","z","scale_0","scale_1","scale_2","opacity","rot_0","rot_1","rot_2","rot_3"],h=["red","green","blue","f_dc_0","f_dc_1","f_dc_2"];for(let e=0;e<f.length;e++){const t=f[e];d.includes(t.name)&&l++,h.includes(t.name)&&c++}const m=l==d.length&&c>=3,p=a?2:m?0:1;return yield new Promise(e=>{e(Object.assign(Object.assign({},g),{mode:p,data:t.buffer,sh:t.sh,shDegree:t.shDegree,faces:i,hasVertexColors:!!c,compressed:!1,rawSplat:!1}))})}))}}Lu._DefaultLoadingOptions={keepInRam:!1,flipY:!1,needsRotationScaleTextures:!1,spzLibraryUrl:"object"==typeof WebAssembly?"https://unpkg.com/@adobe/spz@0.2.2/dist/spz.js":void 0};let Pu=!1;function Bu(){Pu||(Pu=!0,t.RegisterSceneLoaderPlugin(new Lu))}Bu();var Nu={__proto__:null,RegisterSPLATFileLoader:Bu,SPLATFileLoader:Lu};function ku(){t.RegisterSceneLoaderPlugin(Object.assign(Object.assign({},f),{createPlugin:e=>b(this,void 0,void 0,function*(){const{BVHFileLoader:t}=yield Promise.resolve().then(function(){return y});return new t(e[f.name])})})),t.RegisterSceneLoaderPlugin(Object.assign(Object.assign({},Nt),{createPlugin:e=>b(this,void 0,void 0,function*(){const{FBXFileLoader:t}=yield Promise.resolve().then(function(){return Zt});return new t(e[Nt.name])})})),t.RegisterSceneLoaderPlugin(Object.assign(Object.assign({},on),{createPlugin:e=>b(this,void 0,void 0,function*(){const{GLTFFileLoader:t}=yield Promise.resolve().then(function(){return Rs});return new t(e[on.name])})})),function(){ns("EXT_lights_image_based"),ts("EXT_lights_image_based",!0,e=>b(this,void 0,void 0,function*(){const{EXT_lights_image_based:t}=yield Promise.resolve().then(function(){return $s});return new t(e)})),ns("EXT_mesh_gpu_instancing"),ts("EXT_mesh_gpu_instancing",!0,e=>b(this,void 0,void 0,function*(){const{EXT_mesh_gpu_instancing:t}=yield Promise.resolve().then(function(){return js});return new t(e)})),ns("EXT_meshopt_compression"),ts("EXT_meshopt_compression",!0,e=>b(this,void 0,void 0,function*(){const{EXT_meshopt_compression:t}=yield Promise.resolve().then(function(){return Js});return new t(e)})),ns("EXT_texture_avif"),ts("EXT_texture_avif",!0,e=>b(this,void 0,void 0,function*(){const{EXT_texture_avif:t}=yield Promise.resolve().then(function(){return uo});return new t(e)})),ns("EXT_texture_webp"),ts("EXT_texture_webp",!0,e=>b(this,void 0,void 0,function*(){const{EXT_texture_webp:t}=yield Promise.resolve().then(function(){return oo});return new t(e)})),ns("ExtrasAsMetadata"),ts("ExtrasAsMetadata",!1,e=>b(this,void 0,void 0,function*(){const{ExtrasAsMetadata:t}=yield Promise.resolve().then(function(){return Vl});return new t(e)})),ns("KHR_animation_pointer"),ts("KHR_animation_pointer",!0,e=>b(this,void 0,void 0,function*(){const{KHR_animation_pointer:t}=yield Promise.resolve().then(function(){return xa});return new t(e)})),ns("KHR_draco_mesh_compression"),ts("KHR_draco_mesh_compression",!0,e=>b(this,void 0,void 0,function*(){const{KHR_draco_mesh_compression:t}=yield Promise.resolve().then(function(){return bo});return new t(e)})),ns("KHR_gaussian_splatting"),ts("KHR_gaussian_splatting",!0,e=>b(this,void 0,void 0,function*(){const{KHR_gaussian_splatting:t}=yield Promise.resolve().then(function(){return So});return new t(e)})),ns("KHR_interactivity"),ts("KHR_interactivity",!0,e=>b(this,void 0,void 0,function*(){const{KHR_interactivity:t}=yield Promise.resolve().then(function(){return yl});return new t(e)})),ns("KHR_lights_punctual"),ts("KHR_lights_punctual",!0,e=>b(this,void 0,void 0,function*(){const{KHR_lights:t}=yield Promise.resolve().then(function(){return Lo});return new t(e)})),ns("EXT_lights_area"),ts("EXT_lights_area",!0,e=>b(this,void 0,void 0,function*(){const{EXT_lights_area:t}=yield Promise.resolve().then(function(){return Do});return new t(e)})),ns("EXT_lights_ies"),ts("EXT_lights_ies",!0,e=>b(this,void 0,void 0,function*(){const{EXT_lights_ies:t}=yield Promise.resolve().then(function(){return po});return new t(e)})),ns("KHR_materials_anisotropy"),ts("KHR_materials_anisotropy",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_anisotropy:t}=yield Promise.resolve().then(function(){return fr});return new t(e)})),ns("KHR_materials_clearcoat"),ts("KHR_materials_clearcoat",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_clearcoat:t}=yield Promise.resolve().then(function(){return Jo});return new t(e)})),ns("KHR_materials_diffuse_roughness"),ts("KHR_materials_diffuse_roughness",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_diffuse_roughness:t}=yield Promise.resolve().then(function(){return Ti});return new t(e)})),ns("KHR_materials_diffuse_transmission"),ts("KHR_materials_diffuse_transmission",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_diffuse_transmission:t}=yield Promise.resolve().then(function(){return ni});return new t(e)})),ns("KHR_materials_dispersion"),ts("KHR_materials_dispersion",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_dispersion:t}=yield Promise.resolve().then(function(){return gi});return new t(e)})),ns("KHR_materials_emissive_strength"),ts("KHR_materials_emissive_strength",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_emissive_strength:t}=yield Promise.resolve().then(function(){return vr});return new t(e)})),ns("KHR_materials_ior"),ts("KHR_materials_ior",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_ior:t}=yield Promise.resolve().then(function(){return Gr});return new t(e)})),ns("KHR_materials_iridescence"),ts("KHR_materials_iridescence",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_iridescence:t}=yield Promise.resolve().then(function(){return ur});return new t(e)})),ns("KHR_materials_pbrSpecularGlossiness"),ts("KHR_materials_pbrSpecularGlossiness",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_pbrSpecularGlossiness:t}=yield Promise.resolve().then(function(){return $o});return new t(e)})),ns("KHR_materials_sheen"),ts("KHR_materials_sheen",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_sheen:t}=yield Promise.resolve().then(function(){return Mr});return new t(e)})),ns("KHR_materials_specular"),ts("KHR_materials_specular",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_specular:t}=yield Promise.resolve().then(function(){return Pr});return new t(e)})),ns("KHR_materials_transmission"),ts("KHR_materials_transmission",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_transmission:t}=yield Promise.resolve().then(function(){return Qr});return new t(e)})),ns("KHR_materials_unlit"),ts("KHR_materials_unlit",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_unlit:t}=yield Promise.resolve().then(function(){return jo});return new t(e)})),ns("KHR_materials_variants"),ts("KHR_materials_variants",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_variants:t}=yield Promise.resolve().then(function(){return Ur});return new t(e)})),ns("KHR_materials_volume"),ts("KHR_materials_volume",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_volume:t}=yield Promise.resolve().then(function(){return ai});return new t(e)})),ns("KHR_mesh_quantization"),ts("KHR_mesh_quantization",!0,e=>b(this,void 0,void 0,function*(){const{KHR_mesh_quantization:t}=yield Promise.resolve().then(function(){return Ri});return new t(e)})),ns("KHR_texture_basisu"),ts("KHR_texture_basisu",!0,e=>b(this,void 0,void 0,function*(){const{KHR_texture_basisu:t}=yield Promise.resolve().then(function(){return Ii});return new t(e)})),ns("KHR_texture_transform"),ts("KHR_texture_transform",!0,e=>b(this,void 0,void 0,function*(){const{KHR_texture_transform:t}=yield Promise.resolve().then(function(){return ki});return new t(e)})),ns("KHR_xmp_json_ld"),ts("KHR_xmp_json_ld",!0,e=>b(this,void 0,void 0,function*(){const{KHR_xmp_json_ld:t}=yield Promise.resolve().then(function(){return Ki});return new t(e)})),ns("MSFT_audio_emitter"),ts("MSFT_audio_emitter",!0,e=>b(this,void 0,void 0,function*(){const{MSFT_audio_emitter:t}=yield Promise.resolve().then(function(){return Ca});return new t(e)})),ns("MSFT_lod"),ts("MSFT_lod",!0,e=>b(this,void 0,void 0,function*(){const{MSFT_lod:t}=yield Promise.resolve().then(function(){return Ea});return new t(e)})),ns("MSFT_minecraftMesh"),ts("MSFT_minecraftMesh",!0,e=>b(this,void 0,void 0,function*(){const{MSFT_minecraftMesh:t}=yield Promise.resolve().then(function(){return Na});return new t(e)})),ns("MSFT_sRGBFactors"),ts("MSFT_sRGBFactors",!0,e=>b(this,void 0,void 0,function*(){const{MSFT_sRGBFactors:t}=yield Promise.resolve().then(function(){return Ha});return new t(e)})),ns("KHR_node_visibility"),ts("KHR_node_visibility",!0,e=>b(this,void 0,void 0,function*(){const{KHR_node_visibility:t}=yield Promise.resolve().then(function(){return Al});return new t(e)})),ns("KHR_node_hoverability"),ts("KHR_node_hoverability",!0,e=>b(this,void 0,void 0,function*(){const{KHR_node_hoverability:t}=yield Promise.resolve().then(function(){return Bl});return new t(e)})),ns("KHR_node_selectability"),ts("KHR_node_selectability",!0,e=>b(this,void 0,void 0,function*(){const{KHR_node_selectability:t}=yield Promise.resolve().then(function(){return Sl});return new t(e)})),ns("KHR_materials_coat"),ts("KHR_materials_coat",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_coat:t}=yield Promise.resolve().then(function(){return or});return new t(e)})),ns("KHR_materials_fuzz"),ts("KHR_materials_fuzz",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_fuzz:t}=yield Promise.resolve().then(function(){return Or});return new t(e)})),ns("KHR_materials_volume_scatter"),ts("KHR_materials_volume_scatter",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_volume_scatter:t}=yield Promise.resolve().then(function(){return hi});return new t(e)}))}(),t.RegisterSceneLoaderPlugin(Object.assign(Object.assign({},zl),{createPlugin:e=>b(this,void 0,void 0,function*(){const{OBJFileLoader:t}=yield Promise.resolve().then(function(){return Ql});return new t(e[zl.name])})})),t.RegisterSceneLoaderPlugin(Object.assign(Object.assign({},ru),{createPlugin:e=>b(this,void 0,void 0,function*(){const{SPLATFileLoader:t}=yield Promise.resolve().then(function(){return Nu});return new t(e[ru.name])})})),t.RegisterSceneLoaderPlugin(Object.assign(Object.assign({},Jl),{createPlugin:()=>b(this,void 0,void 0,function*(){const{STLFileLoader:e}=yield Promise.resolve().then(function(){return su});return new e})}))}var Du={__proto__:null,registerBuiltInLoaders:ku};const Gu="undefined"!=typeof global?global:"undefined"!=typeof window?window:void 0;if(void 0!==Gu)for(const e in v)Gu.BABYLON[e]||(Gu.BABYLON[e]=v[e]);const Vu="undefined"!=typeof global?global:"undefined"!=typeof window?window:void 0;if(void 0!==Vu){Vu.BABYLON=Vu.BABYLON||{};for(const e in Du)Vu.BABYLON[e]=Du[e]}const Hu="undefined"!=typeof global?global:"undefined"!=typeof window?window:void 0;if(void 0!==Hu){Hu.BABYLON=Hu.BABYLON||{};for(const e in wn)Hu.BABYLON[e]=wn[e];for(const e in nn)Hu.BABYLON[e]=nn[e]}const Ku="undefined"!=typeof global?global:"undefined"!=typeof window?window:void 0;if(void 0!==Ku){Ku.BABYLON=Ku.BABYLON||{},Ku.BABYLON.GLTF1=Ku.BABYLON.GLTF1||{};for(const e in Zn)Ku.BABYLON.GLTF1[e]=Zn[e]}const $u=Object.assign({},$l),Uu=Object.assign(Object.assign({},{__proto__:null}),{Extensions:$u}),qu=Object.assign(Object.assign({},Ul),{Loader:Uu}),Wu="undefined"!=typeof global?global:"undefined"!=typeof window?window:void 0;if(void 0!==Wu){Wu.BABYLON=Wu.BABYLON||{};const e=Wu.BABYLON;e.GLTF2=e.GLTF2||{},e.GLTF2.Loader=e.GLTF2.Loader||{},e.GLTF2.Loader.Extensions=e.GLTF2.Loader.Extensions||{};const t=["Loader"];for(const n in $u)e.GLTF2.Loader.Extensions[n]=$u[n],t.push(n);for(const n in Uu)"Extensions"!==n&&(e.GLTF2.Loader[n]=Uu[n],t.push(n));for(const n in qu)t.indexOf(n)>-1||(e.GLTF2[n]=qu[n])}const zu="undefined"!=typeof global?global:"undefined"!=typeof window?window:void 0;if(void 0!==zu)for(const e in Zl)zu.BABYLON[e]||(zu.BABYLON[e]=Zl[e]);const ju="undefined"!=typeof global?global:"undefined"!=typeof window?window:void 0;if(void 0!==ju)for(const e in ou)ju.BABYLON[e]||(ju.BABYLON[e]=ou[e]);e.AddGaussianSplattingStreamPart=function(e,t,n,s,o={}){return new Ou(t,n,s,e.getScene(),Object.assign(Object.assign({},o),{hostCompound:e}))},e.AddGaussianSplattingStreamPartAsync=function(e,t,n,s){return b(this,arguments,void 0,function*(e,t,n,s,o={}){const r=new Ou(t,n,s,e.getScene(),Object.assign(Object.assign({},o),{hostCompound:e}));try{yield r.whenPartReadyAsync()}catch(e){throw r.dispose(),e}const i=r.streamingPartProxy;if(!i)throw r.dispose(),new Error("GaussianSplattingStream: streaming part was not reserved.");return i})},e.BVHFileLoader=p,e.FBXFileLoader=kt,e.FBXFileLoaderMetadata=Nt,e.GLTF1=Zn,e.GLTF2=qu,e.GLTFFileLoader=mn,e.GLTFLoaderDefaultOptions=dn,e.GLTFValidation=tn,e.GaussianSplattingStream=Ou,e.MTLFileLoader=ql,e.OBJFileLoader=jl,e.ReadBvh=m,e.RegisterBVHFileLoader=g,e.RegisterGLTFFileLoader=pn,e.RegisterOBJFileLoader=Yl,e.RegisterSPLATFileLoader=Bu,e.RegisterSTLFileLoader=nu,e.SPLATFileLoader=Lu,e.STLFileLoader=eu,e.SolidParser=Wl,e.registerBuiltInLoaders=ku});
|
|
2
2
|
//# sourceMappingURL=babylonjs.loaders.min.js.map
|