babylonjs-loaders 9.26.0 → 9.26.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.
@@ -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),f=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),f=new t.Animation(`${e.name}_rot`,"rotationQuaternion",l.frameRate,t.Animation.ANIMATIONTYPE_QUATERNION,l.loopMode),m=[],p=[];for(let t=0;t<e.frames.length;t++){const n=e.frames[t];c&&n.position&&m.push({frame:n.frame,value:n.position.clone()}),d&&p.push({frame:n.frame,value:n.rotation.clone()})}return m.length>0&&(h.setKeys(m),u.push(h)),p.length>0&&(f.setKeys(p),u.push(f)),u}(e,u);for(const e of f)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 f=t.Matrix.Identity();for(let l=0;l<u.channels.length;++l){const d=u.channels[l],m=e[c.i++];if(!m)continue;const p=parseFloat(m.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)}f=n.multiply(f)}}t.Quaternion.FromRotationMatrixToRef(f,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 f=null===(i=e.shift())||void 0===i?void 0:i.trim().split(/\s+/);if(!f)throw new Error("Unexpected end of file: missing OFFSET");if(d=f,"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 m=new t.Vector3(parseFloat(d[1]),parseFloat(d[2]),parseFloat(d[3]));if(isNaN(m.x)||isNaN(m.y)||isNaN(m.z))throw new Error("OFFSET: Invalid values");if(c.offset=m,"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 f(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 f=r.shift();if(!f||"HIERARCHY"!==f.trim().toUpperCase())throw new Error("HIERARCHY expected");const m=r.shift();if(!m)throw new Error("Unexpected end of file after HIERARCHY");const p=h(r,m.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 v=g.trim().split(/[\s]+/);if(v.length<2)throw new Error("Invalid frame count line");const y=parseInt(v[1]);if(isNaN(y))throw new Error("Failed to read number of frames.");u.numFrames=y;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<y;++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 m={name:"bvh",extensions:{".bvh":{isBinary:!1}}};class p{constructor(e){this.name=m.name,this.extensions=m.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[m.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=f(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=f(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))}var v={__proto__:null,BVHFileLoader:p,RegisterBVHFileLoader:g};g();var y={__proto__:null,BVHFileLoader:p,ReadBvh:f,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())})}function x(e,t,n,s){if("a"===n&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?s:"a"===n?s.call(e):s?s.value:t.get(e)}function T(e,t,n,s,o){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!o)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!o:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?o.call(e,n):o?o.value=n:t.set(e,n),n}Object.create,Object.create,"function"==typeof SuppressedError&&SuppressedError;const A=[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],M=[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],w=[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],C=[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],R=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];class S{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 O{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 F{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 E,L;function I(){if(!E){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;E=new F(e)}return E}function B(){return L||(L=new F(new Array(32).fill(5))),L}function N(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=A[r]+e.readBits(M[r]),a=s.decode(e);if(a>29)throw new Error("deflate: invalid distance symbol");const l=w[a]+e.readBits(C[a]);t.copy(l,i)}}function k(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[R[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 F(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 F(i),distanceTree:new F(a,{allowEmpty:!0})}}function D(e,t,n,s,o){let r,i,a,l;if(s?(H(t,n,25,o,"FBX node header"),r=U(e,n),i=U(e,n+8),a=U(e,n+16),l=25):(H(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];H(t,n+l,u,r,"FBX node name");const c=$(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 f=[];for(let n=0;n<i;n++){const n=G(e,t,d,h);f.push(n.property),d=n.nextOffset}if(d!==h)throw new Error(`Invalid FBX property list length for node '${c}' at offset ${n}`);const m=[];if(d<r)for(;d<r;){const n=D(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}`);m.push(n.node),d=n.endOffset}return{node:{name:c,properties:f,children:m},endOffset:r}}function G(e,t,n,s){H(t,n,1,s,"FBX property type");const o=String.fromCharCode(t[n]);switch(n+=1,o){case"C":return H(t,n,1,s,"FBX boolean property"),{property:{type:"boolean",value:0!==t[n]},nextOffset:n+1};case"Y":return H(t,n,2,s,"FBX int16 property"),{property:{type:"int16",value:e.getInt16(n,!0)},nextOffset:n+2};case"I":return H(t,n,4,s,"FBX int32 property"),{property:{type:"int32",value:e.getInt32(n,!0)},nextOffset:n+4};case"F":return H(t,n,4,s,"FBX float32 property"),{property:{type:"float32",value:e.getFloat32(n,!0)},nextOffset:n+4};case"D":return H(t,n,8,s,"FBX float64 property"),{property:{type:"float64",value:e.getFloat64(n,!0)},nextOffset:n+8};case"L":return H(t,n,8,s,"FBX int64 property"),{property:{type:"int64",value:K(e,n)},nextOffset:n+8};case"S":{H(t,n,4,s,"FBX string property length");const o=e.getUint32(n,!0);H(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":{H(t,n,4,s,"FBX raw property length");const o=e.getUint32(n,!0);return H(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 V(e,t,n,"float32[]",4,s);case"d":return V(e,t,n,"float64[]",8,s);case"i":return V(e,t,n,"int32[]",4,s);case"l":return V(e,t,n,"int64[]",8,s);case"b":return V(e,t,n,"boolean[]",1,s);default:throw new Error(`Unknown FBX property type: '${o}' at offset ${n-1}`)}}function V(e,t,n,s,o,r){H(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(H(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 S(e,2,e.byteLength-4),r=new O(t);let i=!1;for(;!i;)switch(i=1===o.readBits(1),o.readBits(2)){case 0:N(o,r);break;case 1:P(o,r,I(),B());break;case 2:{const{literalLengthTree:e,distanceTree:t}=k(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]=K(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 H(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 U(e,t){const n=e.getUint32(t,!0);return 4294967296*e.getUint32(t+4,!0)+n}function K(e,t){const n=e.getUint32(t,!0);return 4294967296*e.getInt32(t+4,!0)+n}function $(e,t,n){let s="";for(let o=0;o<n;o++)s+=String.fromCharCode(e[t+o]);return s}function q(e){const t=new z(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=j(t);e&&s.push(e)}return{version:n,nodes:s}}var W;!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"}(W||(W={}));let z=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 j(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=X(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:Y(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=j(e);if(!t)break;r.push(t)}e.expect(4)}return{name:s,properties:o,children:r}}function X(e){return Number(e)}function Y(e){return e>=-2147483648&&e<=2147483647}function Q(e,t){return e.children.find(e=>e.name===t)}function Z(e,t){return e.nodes.find(e=>e.name===t)}function J(e,t){if(t<e.properties.length)return e.properties[t].value}function ee(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 te(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 ne(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 se(e,t){const n=ne(e);if(void 0!==n)return n;if("string"!=typeof e)return;const s=ee(e);return"Scene"===s?0:t.get(s)}function oe(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 re(e,t){var n,s;const o=ee(null!==(n=J(e,0))&&void 0!==n?n:e.name),r=null!==(s=J(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 ie(e,t){var n;return{name:"Geometry",properties:[{type:"int64",value:t},{type:"string",value:ee(null!==(n=J(e,0))&&void 0!==n?n:"Geometry")},{type:"string",value:"Mesh"}],children:e.children}}function ae(e,t){var n,s,o;const r=ee(null!==(n=J(e,1))&&void 0!==n?n:"Geometry"),i=Q(e,"Vertices");if(!i)throw new Error(`Geometry '${r}' has no Vertices node`);const a=_e(ve(i)),l=Q(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}(ge(ve(l))),d=function(e,t,n){const s=[];for(let o=0;o<e.length;o++){const r=e[o];s.push(...le(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),f=Q(e,"LayerElementNormal");let m=null;f&&(m=me(f,"Normals","NormalsIndex",h,a.length,3,u));const p=e.children.filter(e=>"LayerElementUV"===e.name),_=[];for(const e of p){const t=Q(e,"Name"),n=t&&null!==(s=J(t,0))&&void 0!==s?s:`UVSet${_.length}`,o=me(e,"UV","UVIndex",h,a.length,2,u);o&&_.push({name:n,data:o})}const g=_.length>0?_[0].data:null,v=Q(e,"LayerElementColor");let y=null;if(v){const e=me(v,"Colors","ColorIndex",h,a.length,4,u);if(e){y=new Float32Array(e.length);for(let t=0;t<e.length;t++)y[t]=e[t]}}const b=Q(e,"LayerElementTangent"),x=Q(e,"LayerElementBinormal"),T=x?me(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=Q(e,"Tangents");if(!c)return 3;const d=_e(ve(c)),h=null!==(a=J(null!==(i=Q(e,"MappingInformationType"))&&void 0!==i?i:{name:"",properties:[],children:[]},0))&&void 0!==a?a:"",f=null!==(u=J(null!==(l=Q(e,"ReferenceInformationType"))&&void 0!==l?l:{name:"",properties:[],children:[]},0))&&void 0!==u?u:"",m=Q(e,"TangentsIndex"),p=m?ge(ve(m)):null,_="IndexToDirect"===f&&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=me(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]:pe(e,l,s,o)}return l}(b,h,a.length/3,m,T,u):null,M=Q(e,"LayerElementMaterial");let w=null;M&&(w=function(e,t){var n,s;const o=Q(e,"MappingInformationType"),r=Q(e,"ReferenceInformationType");if(!o||!r)return null;const i=null!==(n=J(o,0))&&void 0!==n?n:"",a=null!==(s=J(r,0))&&void 0!==s?s:"";if("AllSame"===i){const n=Q(e,"Materials"),s=n?ge(ve(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=Q(e,"Materials");if(!t)return null;const n=ge(ve(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,f=new Uint32Array(h);for(let e=0;e<t.length;e++)f[3*e]=t[e].vertices[0],f[3*e+1]=t[e].vertices[1],f[3*e+2]=t[e].vertices[2];return{positions:c,indices:f,normals:s,uvs:o,uvSets:r,colors:i,tangents:a,binormals:l,controlPointIndices:d}}(a,d,h,m,g,_,y,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 le(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],f=t[a+2];n+=(u-h)*(c+f),s+=(c-f)*(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}),ue(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}),ue(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(ce(o[r],o[u],o[c],i)&&!de(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}),ue(e,t)}return l.push({vertices:[e.startIndex+a[0],e.startIndex+a[1],e.startIndex+a[2]],polyIndex:t}),l}function ue(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 ce(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 de(e,t,n,s,o){for(const r of t)if(r!==n&&r!==s&&r!==o&&he(e[r],e[n],e[s],e[o]))return!0;return!1}function he(e,t,n,s){const o=Math.abs(fe(t,n,s)),r=Math.abs(fe(e,t,n)),i=Math.abs(fe(e,n,s)),a=Math.abs(fe(e,s,t));return Math.abs(o-(r+i+a))<1e-10}function fe(e,t,n){return(t[0]-e[0])*(n[1]-e[1])-(t[1]-e[1])*(n[0]-e[0])}function me(e,t,n,s,o,r,i){var a,l;const u=Q(e,"MappingInformationType"),c=Q(e,"ReferenceInformationType");if(!u||!c)return null;const d=null!==(a=J(u,0))&&void 0!==a?a:"",h=null!==(l=J(c,0))&&void 0!==l?l:"",f=Q(e,t);if(!f)return null;const m=_e(ve(f));let p=null;if("IndexToDirect"===h){const t=Q(e,n);t&&(p=ge(ve(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>=m.length?(i.push({type:s>=m.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]=m[s]}}return _}function pe(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 _e(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 ge(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 ve(e){return 1===e.properties.length?e.properties[0].value:e.properties.map(e=>e.value)}function ye(e,t,n){const s=e.get(t);if(s)return n?s.get(n):s.values().next().value}function be(e,t,n,s=0){var o;return null===(o=Ae(e,t,n))||void 0===o?void 0:o[s]}function xe(e,t,n,s){var o;return null!==(o=Me(be(e,t,n)))&&void 0!==o?o:s}function Te(e,t,n,s){const o=Ae(e,t,n);if(!o)return s;const r=Me(o[0]),i=Me(o[1]),a=Me(o[2]);return void 0!==r&&void 0!==i&&void 0!==a?[r,i,a]:s}function Ae(e,t,n){var s,o;return null!==(s=function(e,t){const n=[Q(e,"Properties70"),Q(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)&&J(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 Me(e){if("number"==typeof e)return e}function we(e,t,n){var s;const o=new Map,r=Q(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=Ce(e);t&&o.set(t.name,t)}return{objectType:e,templateName:t,properties:o}}function Ce(e){var t,n,s;const o=J(e,0);return o?{name:o,propertyType:null!==(t=J(e,1))&&void 0!==t?t:"",label:null!==(n=J(e,2))&&void 0!==n?n:"",flags:null!==(s=J(e,3))&&void 0!==s?s:"",values:e.properties.slice(4).map(e=>e.value)}:null}function Re(e,t,n,s){var o,r,i,a;const l=ee(null!==(o=J(e,1))&&void 0!==o?o:"Material"),u=function(e,t){var n,s;if(!t)return;const o=Q(e,"ShadingModel"),r=o?J(o,0):void 0;return"phong"===(null==r?void 0:r.toLowerCase())?null!==(n=ye(t,"Material","FbxSurfacePhong"))&&void 0!==n?n:ye(t,"Material"):"lambert"===(null==r?void 0:r.toLowerCase())&&null!==(s=ye(t,"Material","FbxSurfaceLambert"))&&void 0!==s?s:ye(t,"Material")}(e,s),c=Q(e,"ShadingModel"),d="phong"===(c?null!==(r=J(c,0))&&void 0!==r?r:"Lambert":null!==(i=be(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=Se(e,t,"DiffuseColor"))&&void 0!==n?n:Se(e,t,"Diffuse"),a.diffuseFactor=Oe(e,t,"DiffuseFactor"),a.ambientColor=null!==(s=Se(e,t,"AmbientColor"))&&void 0!==s?s:Se(e,t,"Ambient"),a.ambientFactor=Oe(e,t,"AmbientFactor"),a.specularColor=null!==(o=Se(e,t,"SpecularColor"))&&void 0!==o?o:Se(e,t,"Specular"),a.specularFactor=Oe(e,t,"SpecularFactor"),a.shininess=null!==(r=Oe(e,t,"Shininess"))&&void 0!==r?r:Oe(e,t,"ShininessExponent"),a.emissiveColor=null!==(i=Se(e,t,"EmissiveColor"))&&void 0!==i?i:Se(e,t,"Emissive"),a.emissiveFactor=Oe(e,t,"EmissiveFactor"),a.opacity=Oe(e,t,"Opacity"),a.transparencyFactor=Oe(e,t,"TransparencyFactor"),a}(e,u),f=function(e,t,n){var s,o,r,i,a;const l=[],u=te(t,e,"Texture");for(const{id:e,node:c,propertyName:d}of u){const u=Q(c,"FileName"),h=Q(c,"RelativeFilename"),f=u&&null!==(s=J(u,0))&&void 0!==s?s:"",m=h&&null!==(o=J(h,0))&&void 0!==o?o:"";let p,_;const g=null!==(r=Oe(c,n,"UVRotation"))&&void 0!==r?r:Oe(c,n,"Rotation");let v;p=null!==(i=Fe(c,n,"UVTranslation"))&&void 0!==i?i:Fe(c,n,"Translation"),_=null!==(a=Fe(c,n,"UVScaling"))&&void 0!==a?a:Fe(c,n,"Scaling");const y=be(c,n,"UVSet");y&&y.length>0&&(v=y),null!=p||(p=Le(c,"ModelUVTranslation")),null!=_||(_=Le(c,"ModelUVScaling"));let b=null;const x=te(t,e,"Video");for(const{node:e}of x){const t=Q(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:f,relativeFileName:m,id:e,embeddedData:b,uvTranslation:p,uvScaling:_,uvRotation:g,uvSetName:v})}return l}(t,n,s?null!==(a=ye(s,"Texture","FbxFileTexture"))&&void 0!==a?a:ye(s,"Texture"):void 0);return{id:t,name:l,type:d,properties:h,textures:f}}function Se(e,t,n){const s=Ae(e,t,n);if(!s||s.length<3)return;const o=Ee(s[0]),r=Ee(s[1]),i=Ee(s[2]);return void 0!==o&&void 0!==r&&void 0!==i?[o,r,i]:void 0}function Oe(e,t,n){return Ee(be(e,t,n))}function Fe(e,t,n){const s=Ae(e,t,n);if(!s)return;const o=Ee(s[0]),r=Ee(s[1]);return void 0!==o&&void 0!==r?[o,r]:void 0}function Ee(e){if("number"==typeof e)return e}function Le(e,t){var n,s;const o=Q(e,t);if(!o)return;const r=Ee(null===(n=o.properties[0])||void 0===n?void 0:n.value),i=Ee(null===(s=o.properties[1])||void 0===s?void 0:s.value);return void 0!==r&&void 0!==i?[r,i]:void 0}function Ie(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=te(n,e,"Deformer");if(0===c.length)return null;const d=new Map;for(const{id:e,node:t}of c){if("Cluster"!==J(t,2))continue;const s=te(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"!==J(e,2))continue;const t=new Map;for(const o of e.children){if("PoseNode"!==o.name)continue;const e=Q(o,"Node"),r=Q(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=He(a);16===(null==l?void 0:l.length)&&t.set(i,l)}if(t.has(i))return t}return new Map}(r,n),f=[],m=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=Be(s,t);for(;void 0!==e;){const s=t.objects.get(e);if(!s||"Model"!==s.name)break;n.add(e),e=Be(e,t)}}return n}(e,n),h=function(e,t){const n=new Map;for(const s of Array.from(e)){let o=Be(s,t);for(;void 0!==o;){if(e.has(o)){n.set(s,o);break}o=Be(o,t)}}return n}(d,n),f=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),m=Array.from(d).filter(e=>!h.has(e)).map(e=>({modelId:e,parentIndex:-1}));for(;m.length>0;){const{modelId:d,parentIndex:h}=m.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),v=Pe(p),{bindPoseMatrix:y,transformLinkMatrix:b,transformAssociateModelMatrix:x,clusterMode:T}=g?ke(g.clusterNode):{bindPoseMatrix:null,transformLinkMatrix:null,transformAssociateModelMatrix:null,clusterMode:"Unknown"},A=De(d,ee(null!==(o=J(p,1))&&void 0!==o?o:`Bone${_}`),void 0!==g,T,y,b,x,null!==(r=t.get(d))&&void 0!==r?r:null);s.push(...A),u.push({modelId:d,name:ee(null!==(i=J(p,1))&&void 0!==i?i:`Bone${_}`),index:_,parentIndex:h,isCluster:void 0!==g,translation:v.translation,rotation:v.rotation,preRotation:v.preRotation,postRotation:v.postRotation,rotationPivot:v.rotationPivot,scalingPivot:v.scalingPivot,rotationOffset:v.rotationOffset,scalingOffset:v.scalingOffset,scale:v.scale,rotationOrder:v.rotationOrder,inheritType:v.inheritType,clusterMode:T,bindPoseMatrix:y,transformLinkMatrix:b,transformAssociateModelMatrix:x,modelBindPoseMatrix:null!==(a=t.get(d))&&void 0!==a?a:null,diagnostics:A});for(const e of null!==(l=f.get(d))&&void 0!==l?l:[])c.has(e)||m.push({modelId:e,parentIndex:_})}return u}(d,h,n,f);if(0===m.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=Q(e.clusterNode,"Indexes");if(!o)continue;const i=Ve(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=Q(e.clusterNode,"Indexes"),i=Q(e.clusterNode,"Weights");if(!r||!i)continue;const u=Ve(null===(s=r.properties[0])||void 0===s?void 0:s.value),c=He(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}}(m,d);return{id:e,geometryId:r,meshBindPoseMatrix:void 0!==u&&null!==(s=h.get(u))&&void 0!==s?s:null,bones:m,boneIndices:p,boneWeights:_,diagnostics:f}}function Be(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 Ne(e){const t=J(e,2);return"Root"===t||"LimbNode"===t}function Pe(e){var t,n,s,o,r,i,a,l,u,c,d,h,f,m,p,_,g,v,y,b,x,T,A,M,w,C,R,S,O,F,E,L,I,B,N,P,k,D,G,V,H,U,K,$,q,W,z,j,X,Y,Z,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],fe=[0,0,0],me=[0,0,0],pe=[1,1,1];let _e=0,ge=1;const ve=Q(e,"Properties70");if(!ve)return{translation:ae,rotation:le,preRotation:ue,postRotation:ce,rotationPivot:de,scalingPivot:he,rotationOffset:fe,scalingOffset:me,scale:pe,rotationOrder:_e,inheritType:ge};for(const e of ve.children){if("P"!==e.name)continue;const Q=J(e,0);if(Q)switch(Q){case"Lcl Translation":ae[0]=null!==(n=Ge(null===(t=e.properties[4])||void 0===t?void 0:t.value))&&void 0!==n?n:0,ae[1]=null!==(o=Ge(null===(s=e.properties[5])||void 0===s?void 0:s.value))&&void 0!==o?o:0,ae[2]=null!==(i=Ge(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=Ge(null===(a=e.properties[4])||void 0===a?void 0:a.value))&&void 0!==l?l:0,le[1]=null!==(c=Ge(null===(u=e.properties[5])||void 0===u?void 0:u.value))&&void 0!==c?c:0,le[2]=null!==(h=Ge(null===(d=e.properties[6])||void 0===d?void 0:d.value))&&void 0!==h?h:0;break;case"PreRotation":ue[0]=null!==(m=Ge(null===(f=e.properties[4])||void 0===f?void 0:f.value))&&void 0!==m?m:0,ue[1]=null!==(_=Ge(null===(p=e.properties[5])||void 0===p?void 0:p.value))&&void 0!==_?_:0,ue[2]=null!==(v=Ge(null===(g=e.properties[6])||void 0===g?void 0:g.value))&&void 0!==v?v:0;break;case"PostRotation":ce[0]=null!==(b=Ge(null===(y=e.properties[4])||void 0===y?void 0:y.value))&&void 0!==b?b:0,ce[1]=null!==(T=Ge(null===(x=e.properties[5])||void 0===x?void 0:x.value))&&void 0!==T?T:0,ce[2]=null!==(M=Ge(null===(A=e.properties[6])||void 0===A?void 0:A.value))&&void 0!==M?M:0;break;case"RotationPivot":de[0]=null!==(C=Ge(null===(w=e.properties[4])||void 0===w?void 0:w.value))&&void 0!==C?C:0,de[1]=null!==(S=Ge(null===(R=e.properties[5])||void 0===R?void 0:R.value))&&void 0!==S?S:0,de[2]=null!==(F=Ge(null===(O=e.properties[6])||void 0===O?void 0:O.value))&&void 0!==F?F:0;break;case"ScalingPivot":he[0]=null!==(L=Ge(null===(E=e.properties[4])||void 0===E?void 0:E.value))&&void 0!==L?L:0,he[1]=null!==(B=Ge(null===(I=e.properties[5])||void 0===I?void 0:I.value))&&void 0!==B?B:0,he[2]=null!==(P=Ge(null===(N=e.properties[6])||void 0===N?void 0:N.value))&&void 0!==P?P:0;break;case"RotationOffset":fe[0]=null!==(D=Ge(null===(k=e.properties[4])||void 0===k?void 0:k.value))&&void 0!==D?D:0,fe[1]=null!==(V=Ge(null===(G=e.properties[5])||void 0===G?void 0:G.value))&&void 0!==V?V:0,fe[2]=null!==(U=Ge(null===(H=e.properties[6])||void 0===H?void 0:H.value))&&void 0!==U?U:0;break;case"ScalingOffset":me[0]=null!==($=Ge(null===(K=e.properties[4])||void 0===K?void 0:K.value))&&void 0!==$?$:0,me[1]=null!==(W=Ge(null===(q=e.properties[5])||void 0===q?void 0:q.value))&&void 0!==W?W:0,me[2]=null!==(j=Ge(null===(z=e.properties[6])||void 0===z?void 0:z.value))&&void 0!==j?j:0;break;case"Lcl Scaling":pe[0]=null!==(Y=Ge(null===(X=e.properties[4])||void 0===X?void 0:X.value))&&void 0!==Y?Y:1,pe[1]=null!==(ee=Ge(null===(Z=e.properties[5])||void 0===Z?void 0:Z.value))&&void 0!==ee?ee:1,pe[2]=null!==(ne=Ge(null===(te=e.properties[6])||void 0===te?void 0:te.value))&&void 0!==ne?ne:1;break;case"RotationOrder":_e=null!==(oe=Ge(null===(se=e.properties[4])||void 0===se?void 0:se.value))&&void 0!==oe?oe:0;break;case"InheritType":ge=null!==(ie=Ge(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:fe,scalingOffset:me,scale:pe,rotationOrder:_e,inheritType:ge}}function ke(e){let t=null,n=null,s=null,o="Normalize";const r=Q(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=Q(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=Q(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=Q(e,"Mode"),u=l?J(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 De(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 Ge(e){if("number"==typeof e)return e}function Ve(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 He(e){return e instanceof Float64Array?e:e instanceof Float32Array?new Float64Array(e):null}function Ue(e,t){var n;const s=null!==(n=function(e,t){if(0===e.length)return;const n=e.map(e=>Ke(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=$e(o,t);for(;void 0!==r;){const e=t.objects.get(r);if(!e||"Model"!==e.name||!Ne(e))break;o=r,r=$e(r,t)}return o}function Ke(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=$e(s,t)}return n}function $e(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 qe(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 We(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 ze(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:ee(null!==(n=J(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 je(e,t){return e<t?-1:e>t?1:0}function Xe(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)||je(e,t)}const Ye=46186158e3,Qe=1/23,Ze=1e-5,Je=[24,25,30,48,50,60,100,120];function et(e,t,n){var s,o,r,i;const a=ee(null!==(s=J(t,1))&&void 0!==s?s:"Animation"),l=function(e){var t,n,s,o;const r=Q(e,"Properties70");if(!r)return null;let i=0,a=null;for(const e of r.children){if("P"!==e.name)continue;const r=J(e,0);"LocalStart"===r||"ReferenceStart"===r?i=null!==(n=ct(null===(t=e.properties[4])||void 0===t?void 0:t.value))&&void 0!==n?n:i:"LocalStop"!==r&&"ReferenceStop"!==r||(a=null!==(o=ct(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=te(n,e,"AnimationLayer");if(0===u.length)return null;const c=[],d=[],h=[],f=[];let m=1/0,p=0;for(const{id:e,node:t}of u){const s=ee(null!==(o=J(t,1))&&void 0!==o?o:"Layer");let a=100,l=0;const u=Q(t,"Properties70");if(u)for(const e of u.children){if("P"!==e.name)continue;const t=J(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 _=te(n,e,"AnimationCurveNode"),g=[],v=[],y=[];for(const{id:e,node:t}of _){const o=tt(e,t,n);if(!o){const o=nt(e,t,n);if(o){st(o.curves,e=>{e<m&&(m=e),e>p&&(p=e)}),v.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};y.push(t),f.push(t)}continue}for(const e of o.curves)for(const t of e.keys)t.time<m&&(m=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:v,diagnostics:y})}if(0===c.length&&0===d.length)return null;h.length>1&&f.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),f.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),f.push(t)}}const _=m>0&&isFinite(m)?m: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,v=l?Math.max(l.stop-_,g):0,y=v>g,b=y?g:0,x=y?v:p;return{name:a,startTime:b,stopTime:x,duration:Math.max(x-b,0),curveNodes:c,layers:h,unsupportedCurveNodes:d,diagnostics:f}}function tt(e,t,n){var s;const o=ee(null!==(s=J(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=ot(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"===J(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"===J(e,2))return n.parentId}return null}(e,n);if(null===t)return null;const s=ot(e,n);return 0===s.length?null:{type:"DeformPercent",targetModelId:t,curves:s}}return null}function nt(e,t,n){var s;const o=ee(null!==(s=J(t,1))&&void 0!==s?s:""),r=ot(e,n),i=function(e){var t,n;const s={},o=Q(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=J(e,0);if(!(null==t?void 0:t.startsWith("d|")))continue;const o=dt(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 st(e,t){for(const n of e)for(const e of n.keys)t(e.time)}function ot(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=rt(e);if(i.length>0){const t=it(e,i);s.push({channel:r,keys:t?at(i):i,isSampled:t})}}if(0===s.length){const n=te(t,e,"AnimationCurve"),o=["d|X","d|Y","d|Z"];for(let e=0;e<n.length&&e<3;e++){const t=rt(n[e].node);if(t.length>0){const r=it(n[e].node,t);s.push({channel:o[e],keys:r?at(t):t,isSampled:r})}}}return s}function rt(e){var t,n,s,o,r,i,a,l,u;const c=Q(e,"KeyTime"),d=Q(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,f=ht(null===(n=d.properties[0])||void 0===n?void 0:n.value),m=ut(null===(o=null===(s=Q(e,"KeyAttrFlags"))||void 0===s?void 0:s.properties[0])||void 0===o?void 0:o.value),p=ht(null===(i=null===(r=Q(e,"KeyAttrDataFloat"))||void 0===r?void 0:r.properties[0])||void 0===i?void 0:i.value),_=ut(null===(l=null===(a=Q(e,"KeyAttrRefCount"))||void 0===a?void 0:a.properties[0])||void 0===l?void 0:l.value);var g;if(!h||!f)return[];if(h.length!==f.length)return[];const v=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,m,_),y=[];for(let e=0;e<h.length;e++){const t=v[e],n=t>=0&&null!==(u=null==m?void 0:m[t])&&void 0!==u?u:0,s=4*t;y.push({time:Number(h[e])/Ye,value:f[e],interpolation:ft(n),constantMode:256&n?"next":"standard",rightSlope:mt(p,s),nextLeftSlope:mt(p,s+1)})}return y}function it(e,t){var n;return"FbxMayaSample Curve"===ee(null!==(n=J(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>Qe)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!!Je.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)>Ze||Math.abs(d)>Ze)&&(s=!1);for(const e of[.25,.5,.75]){const t=pt(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 at(e){return e.map(e=>({time:e.time,value:e.value,interpolation:"linear"}))}function lt(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 pt(i.value,a.value,t,o,l,u)}return i.value+u*(a.value-i.value)}return o[o.length-1].value}function ut(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 ct(e){return"number"==typeof e?e/Ye:null}function dt(e){return"number"==typeof e?e:null}function ht(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 ft(e){return 8&e?"cubic":4&e?"linear":2&e?"constant":"linear"}function mt(e,t){if(!e||t<0||t>=e.length)return;const n=e[t];return Number.isFinite(n)?n:void 0}function pt(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 _t(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=te(n,e,"Deformer");for(const{id:e,node:t}of u){if("BlendShapeChannel"!==J(t,2))continue;const r=ee(null!==(s=J(t,1))&&void 0!==s?s:"MorphTarget");let i=0;const a=Q(t,"Properties70");if(a)for(const e of a.children)if("P"===e.name&&"DeformPercent"===J(e,0)){const t=null===(o=e.properties[4])||void 0===o?void 0:o.value;"number"==typeof t&&(i=t)}const u=gt(t),c=[],d=te(n,e,"Geometry");for(const{node:e}of d){if("Shape"!==J(e,2))continue;const t=bt(e);t&&c.push(t)}if(c.length>0){const t=[],n=vt(u,c,e,r,t);l.push({name:r,id:e,deformPercent:i,shapes:yt(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 gt(e){var t;const n=Q(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 vt(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 yt(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 bt(e){var t,n,s;const o=Q(e,"Indexes"),r=Q(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=Q(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 xt=new Set(["Character","CharacterPose","ControlSet","ControlSetPlug","SelectionSet","CollectionExclusive"]);function Tt(e){return"Skin"===e||"Cluster"===e||"BlendShape"===e||"BlendShapeChannel"===e}function At(e,t,n,s,o){var r,i,a,l;return{type:s,message:o,objectId:t,objectName:ee(null!==(r=J(n,1))&&void 0!==r?r:n.name),nodeName:n.name,subType:null!==(i=J(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 Mt(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 f=e=>{let t=c.get(e);return void 0===t&&(t=h--,c.set(e,t)),t},m=(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=Z(e,"Objects");if(p)for(const e of p.children){const t=e.properties[0];if(t){const n=ne(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=ee(t.value),l=f(n),c=re(e,l);if(s.set(l,c),o.push({id:l,node:c,source:"Objects",legacyName:n,synthetic:!1}),"Model"===e.name&&"Mesh"===J(e,1)){const t=m("Geometry",n),c=ie(e,t);s.set(t,c),o.push({id:t,node:c,source:"legacySyntheticGeometry",legacyName:n,synthetic:!0}),oe(a,r,i,u,"OO",t,l)}}}}const _=Z(e,"Connections");if(_)for(const e of _.children){if("C"!==e.name&&"Connect"!==e.name)continue;const o=l.length,d=J(e,0),h=null===(t=e.properties[1])||void 0===t?void 0:t.value,f=null===(n=e.properties[2])||void 0===n?void 0:n.value,m={source:e.name,rawType:d,accepted:!1};if(l.push(m),"OO"!==d&&"OP"!==d){const e=void 0===h?void 0:se(h,c),t=void 0===f?void 0:se(f,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===f){u.push({reason:"missing-connection-endpoint",message:"FBX connection is missing a child or parent endpoint.",connectionIndex:o,type:d});continue}const p=se(h,c),_=se(f,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?J(e,3):void 0;m.childId=p,m.parentId=_,m.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}),oe(a,r,i,u,d,p,_,g,o),m.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=Z(e,"Definitions");if(!n)return t;for(const e of n.children){if("ObjectType"!==e.name)continue;const n=J(e,0);if(n)for(const s of e.children){if("PropertyTemplate"!==s.name)continue;const e=J(s,0);if(!e)continue;const o=we(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=Z(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=J(e,0),o=Ot(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(Re(s,e,t,n));const r=[];for(const[e,n]of Array.from(t.objects))"Geometry"===n.name&&"Mesh"===J(n,2)&&r.push(ae(n,e));const i=function(e){const t=[];for(const[n,s]of Array.from(e.objects))if("Deformer"===s.name&&"Skin"===J(s,2)){const s=Ie(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=Ue(t,e),r=n.get(o);r?r.push(s):n.set(o,[s])}return Array.from(n.entries()).sort(([e],[t])=>je(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 Ke(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=>!We(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,qe(t));const d=function(e,t){const n=new Map;for(const s of Array.from(e)){const o=$e(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)=>Xe(e,t,n));const r=[],i=[...Array.from(e).filter(e=>!t.has(e)).sort((e,t)=>Xe(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),f=[],m=new Map;for(const e of h){const t=null!==(s=c.get(e))&&void 0!==s?s:ze(e,n);if(!t)continue;const i=d.get(e),a=void 0===i?-1:null!==(o=m.get(i))&&void 0!==o?o:-1,l=f.length,u=Object.assign(Object.assign({},t),{index:l,parentIndex:a,isCluster:r.has(e)});f.push(u),m.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()}`,m));return{id:`rig_${e.toString()}`,rootModelIds:f.filter(e=>e.parentIndex<0).map(e=>e.modelId),bones:f,modelIdToBoneIndex:m,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"===J(s,2)){const s=_t(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=et(n,s,e);o&&t.push(o)}return t}(t),c=function(e,t){var n,s,o,r;const i=[],a=null!==(n=ye(t,"NodeAttribute","FbxCamera"))&&void 0!==n?n:ye(t,"NodeAttribute");for(const[t,n]of Array.from(e.objects)){if("NodeAttribute"!==n.name)continue;if("Camera"!==J(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=ee(null!==(s=J(u,1))&&void 0!==s?s:"Camera"),d=xe(n,a,"NearPlane",.1),h=xe(n,a,"FarPlane",1e4),f=Et(n,a),m=1===xe(n,a,"CameraProjectionType",0)||1===xe(n,a,"ProjectionType",0)?"orthographic":"perspective",p=Ot(be(n,a,"FocalLength")),_=null!==(o=Ot(be(n,a,"FilmWidth")))&&void 0!==o?o:Ot(be(n,a,"ApertureWidth")),g=null!==(r=Ot(be(n,a,"FilmHeight")))&&void 0!==r?r:Ot(be(n,a,"ApertureHeight")),v=Ot(be(n,a,"OrthoZoom")),y=Ot(be(n,a,"Roll")),b=Lt(n,a,f,p,g),x=[];"orthographic"===m&&void 0===v&&x.push("Orthographic camera has no OrthoZoom; runtime orthographic bounds use a fallback."),void 0!==p&&void 0===g&&void 0===be(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:f,projectionType:m,focalLength:p,filmWidth:_,filmHeight:g,orthoZoom:v,roll:y,unknownProperties:It(n,Rt),diagnostics:x})}return i}(t,n),d=function(e,t){var n,s,o,r,i;const a=[],l=null!==(n=ye(t,"NodeAttribute","FbxLight"))&&void 0!==n?n:ye(t,"NodeAttribute");for(const[t,n]of Array.from(e.objects)){if("NodeAttribute"!==n.name)continue;if("Light"!==J(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=ee(null!==(s=J(c,1))&&void 0!==s?s:"Light"),h=xe(n,l,"LightType",0),f=Te(n,l,"Color",[1,1,1]),m=xe(n,l,"Intensity",100)/100,p=null!==(o=Ot(be(n,l,"OuterAngle")))&&void 0!==o?o:Ot(be(n,l,"ConeAngle")),_=Ot(be(n,l,"InnerAngle")),g=null!=p?p:45,v=xe(n,l,"DecayType",2),y=Ot(be(n,l,"DecayStart")),b=Ft(be(n,l,"EnableNearAttenuation")),x=Ft(be(n,l,"EnableFarAttenuation")),T=null!==(i=null!==(r=Ft(be(n,l,"CastShadow")))&&void 0!==r?r:Ft(be(c,void 0,"CastShadow")))&&void 0!==i?i:Ft(be(c,void 0,"Shadow")),A=[];2!==v&&A.push(`DecayType ${v} is preserved as metadata; Babylon falloff is not remapped in this pass.`),void 0!==y&&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:f,intensity:m,coneAngle:g,decayType:v,innerAngle:_,outerAngle:p,decayStart:y,enableNearAttenuation:b,enableFarAttenuation:x,castShadows:T,unknownProperties:It(n,St),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=J(r,2))&&void 0!==t?t:"";"Constraint"!==r.name?xt.has(r.name)?s.push(At(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||Tt(i)?"NodeAttribute"===r.name&&i&&"Camera"!==i&&"Light"!==i&&s.push(At(e,o,r,"unsupported-node-attribute",`NodeAttribute subtype '${i}' is preserved as diagnostic data but not converted to a Babylon object.`)):s.push(At(e,o,r,"unsupported-deformer",`Deformer subtype '${i}' is preserved as diagnostic data but not evaluated at runtime.`)):s.push(At(e,o,r,"unsupported-pose",`Pose subtype '${i}' is preserved as diagnostic data but not evaluated at runtime.`)):s.push(At(e,o,r,"unsupported-layered-texture","LayeredTexture is preserved as diagnostic data; runtime texture layer blending is not implemented.")):s.push(At(e,o,r,"unsupported-constraint",`Constraint '${i||ee(null!==(n=J(r,1))&&void 0!==n?n:"")}' is preserved as diagnostic data but not evaluated at runtime.`))}return s}(t),f=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(wt(t,n,e,r,i,s))}return l}(t,r,o,n);return Object.assign({rootModels:f,geometries:r,materials:o,skins:i,rigs:a,blendShapes:l,animations:u,cameras:c,lights:d,diagnostics:h},s)}function wt(e,t,n,s,o,r){var i,a,l;const u=ee(null!==(i=J(t,1))&&void 0!==i?i:"Model"),c=null!==(a=J(t,2))&&void 0!==a?a:"Null",d=te(n,e,"Geometry"),h=d.length>0?s.get(d[0].id):void 0,f=te(n,e,"Material"),m=[];for(const{id:e}of f){const t=o.get(e);t&&m.push(t)}const p=function(e,t){const n=Te(e,t,"Lcl Translation",[0,0,0]),s=Te(e,t,"Lcl Rotation",[0,0,0]),o=Te(e,t,"Lcl Scaling",[1,1,1]),r=Te(e,t,"PreRotation",[0,0,0]),i=Te(e,t,"PostRotation",[0,0,0]),a=Te(e,t,"RotationPivot",[0,0,0]),l=Te(e,t,"ScalingPivot",[0,0,0]),u=Te(e,t,"RotationOffset",[0,0,0]),c=Te(e,t,"ScalingOffset",[0,0,0]),d=Te(e,t,"GeometricTranslation",[0,0,0]),h=Te(e,t,"GeometricRotation",[0,0,0]),f=Te(e,t,"GeometricScaling",[1,1,1]),m=xe(e,t,"RotationOrder",0),p=xe(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:f,rotationOrder:m,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=ye(r,"Model","FbxNode"))&&void 0!==l?l:ye(r,"Model")),_=te(n,e,"Model"),g=[];for(const{id:e,node:t}of _)g.push(wt(e,t,n,s,o,r));const v=t.children.find(e=>"Culling"===e.name),y=!!v&&"CullingOff"===J(v,0),b=function(e){var t;const n=Q(e,"Properties70");if(!n)return;const s={};let o=!1;for(const e of n.children){if("P"!==e.name)continue;const n=J(e,0);if(!n||Ct.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:m,children:g,cullingOff:y,customProperties:b},p)}const Ct=new Set(["Lcl Translation","Lcl Rotation","Lcl Scaling","PreRotation","PostRotation","RotationPivot","ScalingPivot","RotationOffset","ScalingOffset","RotationOrder","GeometricTranslation","GeometricRotation","GeometricScaling","Visibility","InheritType","ScalingMax","DefaultAttributeIndex","currentUVSet","lockInfluenceWeights"]),Rt=new Set(["FieldOfView","FieldOfViewX","FieldOfViewY","NearPlane","FarPlane","AspectWidth","AspectHeight","FilmAspectRatio","FocalLength","FilmWidth","FilmHeight","ApertureWidth","ApertureHeight","CameraProjectionType","ProjectionType","OrthoZoom","Roll","ApertureMode"]),St=new Set(["LightType","Color","Intensity","InnerAngle","OuterAngle","ConeAngle","DecayType","DecayStart","EnableNearAttenuation","EnableFarAttenuation","CastShadow","Shadow"]);function Ot(e){if("number"==typeof e)return e}function Ft(e){return"boolean"==typeof e?e:"number"==typeof e?0!==e:void 0}function Et(e,t){const n=Ot(be(e,t,"FilmAspectRatio"));if(void 0!==n&&n>0)return n;const s=Ot(be(e,t,"AspectWidth")),o=Ot(be(e,t,"AspectHeight"));return void 0!==s&&void 0!==o&&s>0&&o>0?s/o:0}function Lt(e,t,n,s,o){var r;const i=null!==(r=Ot(be(e,t,"FieldOfViewY")))&&void 0!==r?r:Ot(be(e,t,"FieldOfView"));if(void 0!==i)return i;const a=Ot(be(e,t,"FieldOfViewX"));return void 0!==a?n>0?Bt(2*Math.atan(Math.tan(a*Math.PI/180/2)/n)):a:void 0!==s&&s>0&&void 0!==o&&o>0?Bt(2*Math.atan(25.4*o/(2*s))):45}function It(e,t){var n;const s=new Set;for(const o of["Properties70","Properties60"]){const r=Q(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=J(e,0);n&&!t.has(n)&&s.add(n)}}return Array.from(s).sort()}function Bt(e){return 180*e/Math.PI}function Nt(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 kt(e,n){const s=Math.PI/180,o=t.Matrix.Scaling(n[0],n[1],n[2]),r=Nt(e[0]*s,e[1]*s,e[2]*s);return o.multiply(r)}const Dt={name:"fbx",extensions:{".fbx":{isBinary:!0}}};class Gt{constructor(e={}){var t;this.name=Dt.name,this.extensions=Dt.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 Gt(e[Dt.name])}importMeshAsync(e,t,n,s,o,r){return b(this,void 0,void 0,function*(){const o=Mt(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=Mt(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=Mt(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 q(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"!==$(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=D(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 q(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,f=new Map;for(const t of e.skins)f.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=f.get(n.skinId);t&&(c.set(n.geometryId,e),d.set(n.geometryId,t),h.set(n.geometryId,n))}}const m=new Map,p=e=>{for(const t of e)m.set(t.id,t),p(t.children)};p(e.rootModels);const _=Gt._collectCullingConflictMaterialIds(e.rootModels),g=new Map,v=new t.TransformNode("__fbx_root__",n);n.useRightHandedSystem||(v.rotation.y=Math.PI,v.scaling.z=-1);const y=[],b=[v];let x=v;const T=Gt._computeFBXAxisConversionMatrix(e);T.equals(t.Matrix.Identity())||(x=new t.TransformNode("__fbx_axis_conversion__",n),x.parent=v,Gt._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,y,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=y.find(t=>t.skeleton===e))&&void 0!==r?r:null,o=null!=s?s:v,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=Gt._getBoneReferenceWorldMatrix(e,a,o,s),l=new t.Matrix;i.invertToRef(l);const u=r.multiply(l);n.parent=null,n.attachToBone(a,o),Gt._applyMatrixToTransform(n,u)}}}}e.blendShapes.length>0&&this._applyBlendShapes(e.blendShapes,y,n);const w=[];for(const t of e.animations){const s=this._createAnimationGroup(t,e.rigs,u,n,A,m,y);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:y,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,f,m,p){var _,g;const v=Gt._computeFBXModelLocalMatrix(e).multiply(r);if(!e.geometry||"Mesh"!==e.subType||a&&!a(e.name)){if(e.geometry&&"Mesh"===e.subType&&a&&!Gt._modelSubtreeMatchesNameFilter(e,a))return;const r=new t.TransformNode(e.name,n);s&&(r.parent=s),Gt._applyFBXTransform(r,e),u.push(r),f.set(e.id,r),Gt._applyModelMetadata(r,e);for(const t of e.children)this._buildModel(t,n,r,o,v,i,a,l,u,c,d,h,f,m,p)}else{const r=c.get(e.geometry.id),y=d.get(e.geometry.id),b=h.get(e.geometry.id);r&&y&&(r.needInitialSkinMatrix=!0);const x=this._createMesh(e,e.geometry,n,r,y,b);if(r&&y){const e=y.meshBindPoseMatrix?t.Matrix.FromArray(y.meshBindPoseMatrix):v;x.parent=o,Gt._applyMatrixToTransform(x,e),x.computeWorldMatrix(!0),x.updatePoseMatrix(t.Matrix.Invert(e)),x.alwaysSelectAsActiveMesh=!0}else s&&(x.parent=s),Gt._applyFBXTransform(x,e);if(e.materials.length>1&&(null===(_=e.geometry)||void 0===_?void 0:_.materialIndices))this._applyMultiMaterial(x,e,i,n,m,p);else if(e.materials.length>0){const t=i.get(e.materials[0].id);t&&(x.material=Gt._getModelMaterial(t,e,p,m.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),f.set(e.id,x),Gt._applyModelMetadata(x,e);for(const t of e.children)this._buildModel(t,n,x,o,v,i,a,l,u,c,d,h,f,m,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,Gt._applyMatrixToTransform(e,l.getLocalMatrix()),Gt._applyMatrixToTransform(a,i.getLocalMatrix()),l.linkTransformNode(e),o.push(e)}else Gt._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(Gt._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=Vt(n.positions),d=e.geometricTranslation,h=e.geometricRotation,f=e.geometricScaling,m=Gt._computeFBXGeometricMatrix(d,h,f),p=Gt._computeFBXGeometricDeltaMatrix(h,f),_=Gt._computeFBXGeometricNormalMatrix(h,f),g=!m.equals(t.Matrix.Identity()),v=!p.equals(t.Matrix.Identity()),y=!_.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]),m);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=Vt(n.normals),y)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=Vt(n.uvs)),n.uvSets.length>1&&(u.uvs2=Vt(n.uvSets[1].data)),n.uvSets.length>2&&(u.uvs3=Vt(n.uvSets[2].data)),n.uvSets.length>3&&(u.uvs4=Vt(n.uvSets[3].data)),n.uvSets.length>4&&(u.uvs5=Vt(n.uvSets[4].data)),n.uvSets.length>5&&(u.uvs6=Vt(n.uvSets[5].data)),n.tangents){const e=Vt(n.tangents);if(y)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 f=e.length/3,m=new Map,p=new Array(f).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,f=3*c,_=2*l,g=2*u,v=2*c,y=e[h]-e[d],b=e[f]-e[d],x=e[h+1]-e[d+1],T=e[f+1]-e[d+1],A=e[h+2]-e[d+2],M=e[f+2]-e[d+2],w=n[g]-n[_],C=n[v]-n[_],R=n[g+1]-n[_+1],S=n[v+1]-n[_+1],O=w*S-C*R;if(Math.abs(O)<1e-8)continue;const F=1/O,E=(S*y-R*b)*F,L=(S*x-R*T)*F,I=(S*A-R*M)*F,B=(w*b-C*y)*F,N=(w*T-C*x)*F,P=(w*M-C*A)*F;Ht(l,u,c,E,L,I,B,N,P,e,t,n,r,a,m,p),Ht(u,c,l,E,L,I,B,N,P,e,t,n,r,a,m,p),Ht(c,l,u,E,L,I,B,N,P,e,t,n,r,a,m,p)}const _=new Float32Array(4*f);for(let e=0;e<f;e++){const n=3*e,s=4*e,[r,i,f]=Ut(t[n],t[n+1],t[n+2]),g=p[e]?m.get(p[e]):void 0,v=null!==(a=null==g?void 0:g.tx)&&void 0!==a?a:0,y=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*v+i*y+f*b;let T=v-r*x,A=y-i*x,M=b-f*x;const w=Math.hypot(T,A,M);w>1e-8?(T/=w,A/=w,M/=w):[T,A,M]=$t(r,i,f);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-f*A,F=f*T-r*M,E=r*A-i*T,L=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]=L*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:v?p:null,fbxGeometryNormalMatrix:y?_:null,fbxPreRotMatrix:v?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=[],f=[];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]);f.push({start:n,count:3*t.length,matIdx:e})}e.setIndices(h);const m=new t.MultiMaterial(n.name+"_multi",o);for(const e of f){const t=n.materials[e.matIdx];if(t){const e=s.get(t.id);e?m.subMaterials.push(Gt._getModelMaterial(e,n,i,r.has(t.id))):m.subMaterials.push(null)}else m.subMaterials.push(null)}e.material=m,e.subMeshes=[];const p=e.getTotalVertices();for(let n=0;n<f.length;n++){const s=f[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(!Gt._isSupportedMaterialTextureSlot(o.propertyName))continue;const e=Gt._createTexture(o,n,s,Gt._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=Gt._getTextureSourceName(e),i=Gt._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=Gt._getExternalTextureUrls(e,s),l=a.shift();return l?Gt._createExternalTexture(l,a,n,i):null}static _createExternalTexture(e,n,s,o){n.push(...Gt._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,Gt._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?Gt._getMimeType(e):"image/png":void 0;return{buffer:n?new Uint8Array(n):void 0,forcedExtension:e?Gt._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,"/");Gt._isSafeRelativeTexturePath(n)&&s.push(t+n);const o=Gt._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 Gt._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(Gt._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 f=new t.MorphTargetManager(s);f.optimizeInfluencers=!1;const m=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:m;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=Wt(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=qt(u,o,r,i,m,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(f.numTargets),f.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}))}f.numTargets>0&&(f.numMaxInfluencers=f.numTargets,e.morphTargetManager=f)}}_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=Gt._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]=Gt._computeFBXRuntimeLocalMatrix(n,s,e)}u.push(...Gt._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)}),f=Gt._shouldUseBindMatricesAsRest(n,l,h);for(let e=0;e<n.length;e++){let s=f?h[e]:c[e],u=n[e].parentIndex>=0?i[n[e].parentIndex]:null;if(!f&&2===n[e].inheritType&&n[e].parentIndex>=0&&u){const i=Gt._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,f?s.clone():null,f?s.clone():null,e);f&&n[e].isCluster&&Gt._getMaxScaleRatio(l[e],h[e])>=10&&this._bindRestBones.add(d),i.push(d)}if(this._sourceBonesBySkeleton.set(r,i),this._scaleCompensationHelpersBySkeleton.set(r,a),!f){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 Gt._applyParentScaleCompensation(t,r)}static _applyParentScaleCompensation(e,t){const n=Gt._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(Gt._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(Gt._safeInverseScale(e[0]),Gt._safeInverseScale(e[1]),Gt._safeInverseScale(e[2]))}static _shouldUseBindMatricesAsRest(e,t,n){return e.some((e,s)=>!!e.isCluster&&Gt._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(Gt._getScaleRatio(s.x,i.x),Gt._getScaleRatio(s.y,i.y),Gt._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 kt(n,s).multiply(o)}(e,n,s)}static _computeFBXGeometricDeltaMatrix(e,t){return kt(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=Nt(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,f=0!==a[0]||0!==a[1]||0!==a[2]||0!==l[0]||0!==l[1]||0!==l[2],m=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(!f&&!m&&!p){const e=Nt(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]),v=t.Matrix.Translation(a[0],a[1],a[2]),y=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=Nt(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=Nt(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(y),R=R.multiply(C),R=R.multiply(M),R=R.multiply(A),R=R.multiply(v),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=Gt._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 Gt._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,f=new Map,m=[];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)):(f.has(t.targetModelId)||f.set(t.targetModelId,[]),f.get(t.targetModelId).push(t)):m.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(f)){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 m){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=Yt(n.curves[0],s,e.startTime,e.stopTime,e=>{var t;return null!==(t=Wt(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=Yt(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=jt(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})),f=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=Gt._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=f[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=Gt._splitParentScaleCompensatedLocalMatrix(a[t],s);Gt._pushMatrixKeys(d[t],c,o.boneLocalMatrix),Gt._pushMatrixKeys(h[t],c,o.helperLocalMatrix)}}const m=[];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(!Xt(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&&m.push({bone:o,animations:c});const f=this._getScaleCompensationHelper(n,s);if(!f)continue;const p=[],{posKeys:_,rotKeys:g,sclKeys:v}=h[s];if(!this._isVector3KeysConstant(_)){const e=new t.Animation(`${f.name}_position`,"position",l,t.Animation.ANIMATIONTYPE_VECTOR3,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(_),p.push(e)}if(!Xt(g)){const e=new t.Animation(`${f.name}_rotation`,"rotationQuaternion",l,t.Animation.ANIMATIONTYPE_QUATERNION,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(g),p.push(e)}if(!this._isVector3KeysConstant(v)){const e=new t.Animation(`${f.name}_scaling`,"scaling",l,t.Animation.ANIMATIONTYPE_VECTOR3,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(v),p.push(e)}p.length>0&&m.push({bone:f,animations:p})}return m}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,f,m;const p=e.find(e=>"T"===e.type),_=e.find(e=>"R"===e.type),g=e.find(e=>"S"===e.type),v=jt(e,30,o,r);if(0===v.length)return[];const y=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 v){const n=30*e,o=null!==(i=lt(y,e))&&void 0!==i?i:s.translation[0],r=null!==(a=lt(b,e))&&void 0!==a?a:s.translation[1],p=null!==(l=lt(x,e))&&void 0!==l?l:s.translation[2],_=null!==(u=lt(T,e))&&void 0!==u?u:s.rotation[0],g=null!==(c=lt(A,e))&&void 0!==c?c:s.rotation[1],v=null!==(d=lt(M,e))&&void 0!==d?d:s.rotation[2],L=null!==(h=lt(w,e))&&void 0!==h?h:s.scale[0],I=null!==(f=lt(C,e))&&void 0!==f?f:s.scale[1],B=null!==(m=lt(R,e))&&void 0!==m?m:s.scale[2],N=Gt._computeFBXLocalMatrix([o,r,p],[_,g,v],[L,I,B],s.preRotation,s.postRotation,s.rotationPivot,s.scalingPivot,s.rotationOffset,s.scalingOffset,s.rotationOrder),P=new t.Vector3,k=new t.Quaternion,D=new t.Vector3;N.decompose(P,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:P})}const L=[];if(!this._isVector3KeysConstant(S)){const e=new t.Animation(`${n}_position`,"position",30,t.Animation.ANIMATIONTYPE_VECTOR3,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(S),L.push(e)}if(_){const e=new t.Animation(`${n}_rotation`,"rotationQuaternion",30,t.Animation.ANIMATIONTYPE_QUATERNION,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(O),L.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),L.push(e)}return L}_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 f=t.find(e=>"T"===e.type),m=t.find(e=>"R"===e.type),p=t.find(e=>"S"===e.type),_=null==f?void 0:f.curves.find(e=>"d|X"===e.channel),g=null==f?void 0:f.curves.find(e=>"d|Y"===e.channel),v=null==f?void 0:f.curves.find(e=>"d|Z"===e.channel),y=null==m?void 0:m.curves.find(e=>"d|X"===e.channel),b=null==m?void 0:m.curves.find(e=>"d|Y"===e.channel),x=null==m?void 0:m.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 Gt._computeFBXLocalMatrix([null!==(o=lt(_,n))&&void 0!==o?o:e.translation[0],null!==(r=lt(g,n))&&void 0!==r?r:e.translation[1],null!==(i=lt(v,n))&&void 0!==i?i:e.translation[2]],[null!==(a=lt(y,n))&&void 0!==a?a:e.rotation[0],null!==(l=lt(b,n))&&void 0!==l?l:e.rotation[1],null!==(u=lt(x,n))&&void 0!==u?u:e.rotation[2]],null!=s?s:[null!==(c=lt(T,n))&&void 0!==c?c:e.scale[0],null!==(d=lt(A,n))&&void 0!==d?d:e.scale[1],null!==(h=lt(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=lt(a,n))&&void 0!==s?s:e.scale[0],null!==(o=lt(l,n))&&void 0!==o?o:e.scale[1],null!==(r=lt(u,n))&&void 0!==r?r:e.scale[2]]}_buildBoneAnimations(e,n,s,o,r,i){var a,l,u,c,d,h,f,m,p;const _=e.find(e=>"T"===e.type),g=e.find(e=>"R"===e.type),v=e.find(e=>"S"===e.type),y=jt(e,30,o,r);if(0===y.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==v?void 0:v.curves.find(e=>"d|X"===e.channel),R=null==v?void 0:v.curves.find(e=>"d|Y"===e.channel),S=null==v?void 0:v.curves.find(e=>"d|Z"===e.channel),O=[],F=[],E=[];let L=null,I=null;if(i){const e=Gt._computeFBXLocalMatrix(s.translation,s.rotation,s.scale,s.preRotation,s.postRotation,s.rotationPivot,s.scalingPivot,s.rotationOffset,s.scalingOffset,s.rotationOrder);I=new t.Matrix,e.invertToRef(I)}for(const e of y){const n=30*e,o=null!==(a=lt(b,e))&&void 0!==a?a:s.translation[0],r=null!==(l=lt(x,e))&&void 0!==l?l:s.translation[1],_=null!==(u=lt(T,e))&&void 0!==u?u:s.translation[2],g=null!==(c=lt(A,e))&&void 0!==c?c:s.rotation[0],v=null!==(d=lt(M,e))&&void 0!==d?d:s.rotation[1],y=null!==(h=lt(w,e))&&void 0!==h?h:s.rotation[2],B=null!==(f=lt(C,e))&&void 0!==f?f:s.scale[0],N=null!==(m=lt(R,e))&&void 0!==m?m:s.scale[1],P=null!==(p=lt(S,e))&&void 0!==p?p:s.scale[2],k=Gt._computeFBXLocalMatrix([o,r,_],[g,v,y],[B,N,P],s.preRotation,s.postRotation,s.rotationPivot,s.scalingPivot,s.rotationOffset,s.scalingOffset,s.rotationOrder),D=I&&i?i.multiply(I).multiply(k):k,G=new t.Vector3,V=new t.Quaternion,H=new t.Vector3;D.decompose(G,V,H),L&&t.Quaternion.Dot(L,V)<0&&V.scaleInPlace(-1),L=V,O.push({frame:n,value:H}),F.push({frame:n,value:V}),E.push({frame:n,value:G})}const B=[];if(!this._isVector3KeysConstant(O)){const e=new t.Animation(`${n}_position`,"position",30,t.Animation.ANIMATIONTYPE_VECTOR3,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(O),B.push(e)}if(g){const e=new t.Animation(`${n}_rotation`,"rotationQuaternion",30,t.Animation.ANIMATIONTYPE_QUATERNION,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(F),B.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),B.push(e)}return B}_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 Vt(e){const t=new Float32Array(e.length);for(let n=0;n<e.length;n++)t[n]=e[n];return t}function Ht(e,t,n,s,o,r,i,a,l,u,c,d,h,f,m,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],f=Math.hypot(a,l,u),m=Math.hypot(c,d,h);if(f<=1e-8||m<=1e-8)return 0;const p=(a*c+l*d+u*h)/(f*m);return Math.acos(Math.max(-1,Math.min(1,p)))}(u,e,t,n);if(g<=1e-8)return;const v=function(e,t,n,s,o,r,i,a,l,u,c,d){const h=3*e,f=3*e,m=2*e,[p,_,g]=Ut(l[f],l[f+1],l[f+2]),v=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:${Kt(a[h])},${Kt(a[h+1])},${Kt(a[h+2])}`,Kt(p),Kt(_),Kt(g),Kt(u[m]),Kt(u[m+1]),v,d].join("|")}(e,s,o,r,i,a,l,u,c,d,h,f);let y=m.get(v);y||(y={tx:0,ty:0,tz:0,bx:0,by:0,bz:0},m.set(v,y)),y.tx+=s*g,y.ty+=o*g,y.tz+=r*g,y.bx+=i*g,y.by+=a*g,y.bz+=l*g,null!==(_=p[e])&&void 0!==_||(p[e]=v)}function Ut(e,t,n){const s=Math.hypot(e,t,n);return s>1e-8?[e/s,t/s,n/s]:[0,0,1]}function Kt(e){const t=Math.round(1e6*e);return Object.is(t,-0)?0:t}function $t(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 qt(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],f=e.vertices[3*a+2];if(r){const e=t.Vector3.TransformNormal(new t.Vector3(d,h,f),r);d=e.x,h=e.y,f=e.z}if(l[3*s]+=d,l[3*s+1]+=h,l[3*s+2]+=f,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 Wt(e,t,n){if(n<=0)return[];if(!t||t.length!==n||1===n)return[zt(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:zt(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=zt((e-o)/i);return s[n-1]=1-a,s[n]=a,s}return s[n-1]=1,s}function zt(e){return Math.max(0,Math.min(1,e))}function jt(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 Xt(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 Yt(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=lt(e,d.start))&&void 0!==r?r:0,interpolation:"linear"},frame:d.start*t,value:o(null!==(i=lt(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=lt(e,d.stop))&&void 0!==a?a:0,interpolation:"linear"},frame:d.stop*t,value:o(null!==(l=lt(e,d.stop))&&void 0!==l?l:0)});const f=h.map(e=>({frame:e.frame,value:e.value}));for(let e=0;e<h.length-1;e++){const n=h[e].source,s=f[e+1];if("constant"===n.interpolation){f[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;f[e].outTangent=Qt(null!==(u=n.rightSlope)&&void 0!==u?u:a,o)/t,s.inTangent=Qt(null!==(c=n.nextLeftSlope)&&void 0!==c?c:a,o)/t}return f}function Qt(e,t){return t(e)-t(0)}let Zt=!1;function Jt(){Zt||(Zt=!0,t.RegisterSceneLoaderPlugin(new Gt))}var en={__proto__:null,FBXFileLoader:Gt,RegisterFBXFileLoader:Jt};function tn(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 nn(){const e=[];onmessage=t=>{const n=t.data;switch(n.id){case"init":importScripts(n.url);break;case"validate":tn(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)}}}Jt();class sn{static ValidateAsync(e,n,s,o){return"function"==typeof Worker?new Promise((r,i)=>{const a=`${tn}(${nn})()`,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),sn._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(()=>tn(e,n,s,o)))}}sn.Configuration={url:`${t.Tools._DefaultCdnUrl}/gltf_validator.js`},sn._LastResults=null;var on={__proto__:null,GLTFValidation:sn};const rn="Z2xURg",an={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,"+rn)||e.startsWith("data:;base64,"+rn)||e.startsWith("data:application/octet-stream;base64,"+rn)||e.startsWith("data:model/gltf-binary;base64,"+rn)};function ln(e,t,n){try{return Promise.resolve(new Uint8Array(e,t,n))}catch(e){return Promise.reject(e)}}var un,cn,dn;e.GLTFLoaderCoordinateSystemMode=void 0,(un=e.GLTFLoaderCoordinateSystemMode||(e.GLTFLoaderCoordinateSystemMode={}))[un.AUTO=0]="AUTO",un[un.FORCE_RIGHT_HANDED=1]="FORCE_RIGHT_HANDED",e.GLTFLoaderAnimationStartMode=void 0,(cn=e.GLTFLoaderAnimationStartMode||(e.GLTFLoaderAnimationStartMode={}))[cn.NONE=0]="NONE",cn[cn.FIRST=1]="FIRST",cn[cn.ALL=2]="ALL",e.GLTFLoaderState=void 0,(dn=e.GLTFLoaderState||(e.GLTFLoaderState={}))[dn.LOADING=0]="LOADING",dn[dn.READY=1]="READY",dn[dn.COMPLETE=2]="COMPLETE";const hn=e=>Promise.resolve(e);class fn{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 mn=new fn;class pn extends fn{constructor(){super(...arguments),this.extensionOptions={},this.preprocessUrlAsync=hn}copyFrom(e){var t,n,s,o,r,i,a,l,u,c,d,h,f,m,p,_,g,v,y,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!==(f=e.loadOnlyMaterials)&&void 0!==f?f:this.loadOnlyMaterials,this.loadSkins=null!==(m=e.loadSkins)&&void 0!==m?m: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!==(v=e.targetFps)&&void 0!==v?v:this.targetFps,this.transparencyAsCoverage=null!==(y=e.transparencyAsCoverage)&&void 0!==y?y: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 _n extends pn{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=an.name,this.extensions=an.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({},mn),e))}get _isPreprocessUrlAsyncSet(){return this.preprocessUrlAsync!==hn}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=hn,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)=>ln(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 an.canDirectLoad(e)}directLoad(e,n){if(n.startsWith("base64,"+rn)||n.startsWith(";base64,"+rn)||n.startsWith("application/octet-stream;base64,"+rn)||n.startsWith("model/gltf-binary;base64,"+rn)){const s=t.DecodeBase64UrlToBinary(n);return this._validate(e,new Uint8Array(s,0,s.byteLength)),this._unpackBinaryAsync(new t.DataReader({readAsync:(e,t)=>ln(s,e,t),byteLength:s.byteLength}))}return this._validate(e,n),Promise.resolve({json:this._parseJson(n)})}createPlugin(e){return new _n(e[an.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"),sn.ValidateAsync(n,s,o,t=>this.preprocessUrlAsync(s+t,s).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=_n._parseVersion(t.version);if(!n)throw new Error("Invalid version: "+t.version);if(void 0!==t.minVersion){const e=_n._parseVersion(t.minVersion);if(!e)throw new Error("Invalid minimum version: "+t.minVersion);if(_n._compareVersion(e,{major:2,minor:0})>0)throw new Error("Incompatible minimum version: "+t.minVersion)}const s={1:_n._CreateGLTF1Loader,2:_n._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=_n._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){}}_n.IncrementalLoading=!0,_n.HomogeneousCoordinates=!1,_n._logSpaces=" ";let gn=!1;function vn(){gn||(gn=!0,t.RegisterSceneLoaderPlugin(new _n))}vn();var yn,bn,xn,Tn,An,Mn,wn,Cn,Rn,Sn={__proto__:null,GLTFFileLoader:_n,get GLTFLoaderAnimationStartMode(){return e.GLTFLoaderAnimationStartMode},get GLTFLoaderCoordinateSystemMode(){return e.GLTFLoaderCoordinateSystemMode},GLTFLoaderDefaultOptions:mn,get GLTFLoaderState(){return e.GLTFLoaderState},RegisterGLTFFileLoader:vn};!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"}(yn||(yn={})),function(e){e[e.FRAGMENT=35632]="FRAGMENT",e[e.VERTEX=35633]="VERTEX"}(bn||(bn={})),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"}(xn||(xn={})),function(e){e[e.CLAMP_TO_EDGE=33071]="CLAMP_TO_EDGE",e[e.MIRRORED_REPEAT=33648]="MIRRORED_REPEAT",e[e.REPEAT=10497]="REPEAT"}(Tn||(Tn={})),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"}(An||(An={})),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"}(Mn||(Mn={})),function(e){e[e.FRONT=1028]="FRONT",e[e.BACK=1029]="BACK",e[e.FRONT_AND_BACK=1032]="FRONT_AND_BACK"}(wn||(wn={})),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"}(Cn||(Cn={}));class On{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 xn.FLOAT_MAT2:r.setMatrix2x2(o,t.Matrix.GetAsMatrix2x2(i));break;case xn.FLOAT_MAT3:r.setMatrix3x3(o,t.Matrix.GetAsMatrix3x3(i));break;case xn.FLOAT_MAT4:r.setMatrix(o,i)}}static SetUniform(e,n,s,o){switch(o){case xn.FLOAT:return e.setFloat(n,s),!0;case xn.FLOAT_VEC2:return e.setVector2(n,t.Vector2.FromArray(s)),!0;case xn.FLOAT_VEC3:return e.setVector3(n,t.Vector3.FromArray(s)),!0;case xn.FLOAT_VEC4:return e.setVector4(n,t.Vector4.FromArray(s)),!0;default:return!1}}static GetWrapMode(e){switch(e){case Tn.CLAMP_TO_EDGE:return t.Texture.CLAMP_ADDRESSMODE;case Tn.MIRRORED_REPEAT:return t.Texture.MIRROR_ADDRESSMODE;case Tn.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 An.LINEAR:case An.LINEAR_MIPMAP_NEAREST:case An.LINEAR_MIPMAP_LINEAR:return t.Texture.TRILINEAR_SAMPLINGMODE;case An.NEAREST:case An.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 yn.BYTE:return new Int8Array(i,n,s);case yn.UNSIGNED_BYTE:return new Uint8Array(i,n,s);case yn.SHORT:return new Int16Array(i,n,s);case yn.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*On.GetByteStrideFromType(t);return On.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(!On._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};On._DefaultMaterial=new t.ShaderMaterial("GLTFDefaultMaterial",e,n,s),On._DefaultMaterial.setColor4("u_emission",new t.Color4(.5,.5,.5,1))}return On._DefaultMaterial}}On._DefaultMaterial=null,function(e){e[e.IDENTIFIER=1]="IDENTIFIER",e[e.UNKNOWN=2]="UNKNOWN",e[e.END_OF_INPUT=3]="END_OF_INPUT"}(Rn||(Rn={}));class Fn{constructor(e){this._pos=0,this.currentToken=Rn.UNKNOWN,this.currentIdentifier="",this.currentString="",this.isLetterOrDigitPattern=/^[a-zA-Z0-9]+$/,this._toParse=e,this._maxPos=e.length}getNextToken(){if(this.isEnd())return Rn.END_OF_INPUT;if(this.currentString=this.read(),this.currentToken=Rn.UNKNOWN,"_"===this.currentString||this.isLetterOrDigitPattern.test(this.currentString))for(this.currentToken=Rn.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 En=["MODEL","VIEW","PROJECTION","MODELVIEW","MODELVIEWPROJECTION","JOINTMATRIX"],Ln=["world","view","projection","worldView","worldViewProjection","mBones"],In=["translation","rotation","scale"],Bn=["position","rotationQuaternion","scaling"],Nn=(e,t,n)=>{for(const s in e){const o=e[s];n[t][s]=o}},Pn=e=>{if(e)for(let t=0;t<e.length/2;t++)e[2*t+1]=1-e[2*t+1]},kn=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},Dn=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},Gn=(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=Dn(a),r=new t.Bone(a.name||"",o,Gn(e,n,a.jointName,o),s);return r.id=i,r}}}return null},Vn=(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},Hn=(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},Un=(e,t)=>{for(let n=0;n<e.jointNames.length;n++)if(e.jointNames[n]===t)return!0;return!1},Kn=(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 f,m;for(const n in h)if(f=e.accessors[h[n]],m=On.GetBufferFromAccessor(e,f),"NORMAL"===n)s.normals=new Float32Array(m.length),s.normals.set(m);else if("POSITION"===n){if(_n.HomogeneousCoordinates){s.positions=new Float32Array(m.length-m.length/4);for(let e=0;e<m.length;e+=4)s.positions[e]=m[e],s.positions[e+1]=m[e+1],s.positions[e+2]=m[e+2]}else s.positions=new Float32Array(m.length),s.positions.set(m);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(m.length);r.set(m),Pn(r),s.set(r,o)}else"JOINT"===n?(s.matricesIndices=new Float32Array(m.length),s.matricesIndices.set(m)):"WEIGHT"===n?(s.matricesWeights=new Float32Array(m.length),s.matricesWeights.set(m)):"COLOR"===n&&(s.colors=new Float32Array(m.length),s.colors.set(m));if(f=e.accessors[o.indices],f)m=On.GetBufferFromAccessor(e,f),s.indices=new Int32Array(m.length),s.indices.set(m),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?On.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 f=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(f,l[f],u[f],c[f],d[f],r,r,!0),f++}return r},$n=(e,t,n,s)=>{e.position&&(e.position=t),(e.rotationQuaternion||e.rotation)&&(e.rotationQuaternion=n),e.scaling&&(e.scaling=s)},qn=(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=Kn(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||Un(s,i.jointName))continue;const l=Dn(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=Hn(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=Hn(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=Gn(e,n,n.jointNames[r],o),d=!0;break}if(d)break}}const f=Dn(l);!h&&r.length>0&&(h=Vn(r,u),h&&-1===i.indexOf(h)&&i.push(h)),new t.Bone(l.jointName||"",o,h,f).id=u}const a=o.bones;o.bones=[];for(let t=0;t<n.jointNames.length;t++){const s=Hn(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=Kn(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),$n(e,s,o,r)}else n.translation&&n.rotation&&n.scale&&$n(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];$n(o,t.Vector3.FromArray(e),t.Quaternion.FromArray(s),t.Vector3.FromArray(r))}o.updateCache(!0),n.babylonNode=o}return o},Wn=(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=qn(e,o,t),null!==r&&(r.id=t,r.parent=n)),o.children)for(let t=0;t<o.children.length;t++)Wn(e,o.children[t],r,s)},zn=e=>{let n=e.currentScene;if(n)for(let t=0;t<n.nodes.length;t++)Wn(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++)Wn(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=On.GetBufferFromAccessor(e,e.accessors[l]),d=On.GetBufferFromAccessor(e,e.accessors[u]),h=i.target.id;let f=e.scene.getNodeById(h);if(null===f&&(f=e.scene.getNodeByName(h)),null===f){t.Tools.Warn("Creating animation named "+n+". But cannot find node named "+h+" to attach to");continue}const m=f instanceof t.Bone;let p=i.target.path;const _=In.indexOf(p);-1!==_&&(p=Bn[_]);let g=t.Animation.ANIMATIONTYPE_MATRIX;m||("rotationQuaternion"===p?(g=t.Animation.ANIMATIONTYPE_QUATERNION,f.rotationQuaternion=new t.Quaternion):g=t.Animation.ANIMATIONTYPE_VECTOR3);let v=null;const y=[];let b=0,x=!1;m&&o&&o.getKeys().length===c.length&&(v=o,x=!0),x||(e.scene._blockEntityCollection=!!e.assetContainer,v=new t.Animation(n,m?"_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),m){const s=f;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):y.push({frame:c[e],value:n})}!x&&v&&(v.setKeys(y),f.animations.push(v)),o=v,e.scene.stopAnimation(f),e.scene.beginAnimation(f,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)}},jn=(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=En.indexOf(r.semantic);if(-1!==e)return delete n[s],Ln[e]}}return e.currentIdentifier},Xn=e=>{for(const t in e.materials)Zn.LoadMaterialAsync(e,t,()=>{},()=>{})};class Yn{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&&Nn(e.extensions,"extensions",s),e.extensionsUsed&&Nn(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&&Nn(e.bufferViews,"bufferViews",s),e.accessors&&Nn(e.accessors,"accessors",s),e.meshes&&Nn(e.meshes,"meshes",s),e.lights&&Nn(e.lights,"lights",s),e.cameras&&Nn(e.cameras,"cameras",s),e.nodes&&Nn(e.nodes,"nodes",s),e.images&&Nn(e.images,"images",s),e.textures&&Nn(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&&Nn(e.programs,"programs",s),e.samplers&&Nn(e.samplers,"samplers",s),e.techniques&&Nn(e.techniques,"techniques",s),e.materials&&Nn(e.materials,"materials",s),e.animations&&Nn(e.animations,"animations",s),e.skins&&Nn(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===An.NEAREST_MIPMAP_NEAREST||i.minFilter===An.NEAREST_MIPMAP_LINEAR||i.minFilter===An.LINEAR_MIPMAP_NEAREST||i.minFilter===An.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=On.GetWrapMode(i.wrapS)),void 0!==i.wrapT&&(h.wrapV=On.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 f=new Fn(u),m=new Fn(c),p={},_=[],g=[],v=[];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===xn.SAMPLER_2D?v.push(e):_.push(e);else{const t=En.indexOf(n.semantic);-1!==t?(_.push(Ln[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=kn(n);e&&g.push(e)}}for(;!f.isEnd()&&f.getNextToken();){if(f.currentToken!==Rn.IDENTIFIER){d+=f.currentString;continue}let e=!1;for(const t in i.attributes){const n=i.attributes[t],s=i.parameters[n];if(f.currentIdentifier===t&&s.semantic){d+=kn(s),e=!0;break}}e||(d+=jn(f,i,p))}for(;!m.isEnd()&&m.getNextToken();)m.currentToken===Rn.IDENTIFIER?h+=jn(m,i,p):h+=m.currentString;const y={vertex:a.vertexShader+n,fragment:a.fragmentShader+n},b={attributes:g,uniforms:_,samplers:v,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,y,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===xn.SAMPLER_2D?Zn.LoadTextureAsync(e,s.values?u:a.value,c(n),()=>c(null)):a.value&&On.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===xn.FLOAT_MAT2||u===xn.FLOAT_MAT3||u===xn.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;On.SetMatrix(t.scene,e,l,i,s.getEffect())}}else On.SetMatrix(t.scene,e,l,i,s.getEffect());else{const e=a[o.uniforms[i]];if(!e)continue;if(u===xn.SAMPLER_2D){const n=t.textures[r.values?e:l.value].babylonTexture;if(null==n)continue;s.getEffect().setTexture(i,n)}else On.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]!==wn.BACK&&(x.backFaceCulling=!1);const n=e.blendFuncSeparate;n&&(n[0]===Cn.SRC_ALPHA&&n[1]===Cn.ONE_MINUS_SRC_ALPHA&&n[2]===Cn.ONE&&n[3]===Cn.ONE?x.alphaMode=t.Constants.ALPHA_COMBINE:n[0]===Cn.ONE&&n[1]===Cn.ONE&&n[2]===Cn.ZERO&&n[3]===Cn.ONE?x.alphaMode=t.Constants.ALPHA_ONEONE:n[0]===Cn.SRC_ALPHA&&n[1]===Cn.ONE&&n[2]===Cn.ZERO&&n[3]===Cn.ONE?x.alphaMode=t.Constants.ALPHA_ADD:n[0]===Cn.ZERO&&n[1]===Cn.ONE_MINUS_SRC_COLOR&&n[2]===Cn.ONE&&n[3]===Cn.ONE?x.alphaMode=t.Constants.ALPHA_SUBTRACT:n[0]===Cn.DST_COLOR&&n[1]===Cn.ZERO&&n[2]===Cn.ONE&&n[3]===Cn.ONE?x.alphaMode=t.Constants.ALPHA_MULTIPLY:n[0]===Cn.SRC_ALPHA&&n[1]===Cn.ONE_MINUS_SRC_COLOR&&n[2]===Cn.ONE&&n[3]===Cn.ONE&&(x.alphaMode=t.Constants.ALPHA_MAXIMIZED))}}}let Qn=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,Zn.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,()=>{Xn(n),zn(n),!_n.IncrementalLoading&&i&&i(s,o)})}),_n.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,Zn.LoadRuntimeAsync(e,t,n,e=>{Zn.LoadRuntimeExtensionsAsync(e,()=>{this._createNodes(e),this._loadBuffersAsync(e,()=>{this._loadShadersAsync(e,()=>{Xn(e),zn(e),_n.IncrementalLoading||s()})}),_n.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)=>{Zn.LoadShaderStringAsync(e,s,r=>{r instanceof ArrayBuffer||(e.loadedShaderCount++,r&&(t.Effect.ShadersStore[s+(o.type===bn.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)=>{Zn.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++)Wn(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++)Wn(e,t.nodes[n],null)}}};Qn.Extensions={};class Zn{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){Zn._ApplyExtensions(r=>r.loadRuntimeAsync(e,t,n,s,o),()=>{setTimeout(()=>{s&&s(Yn.CreateRuntime(t.json,e,n))})})}static LoadRuntimeExtensionsAsync(e,t,n){Zn._ApplyExtensions(s=>s.loadRuntimeExtensionsAsync(e,t,n),()=>{setTimeout(()=>{t()})})}static LoadBufferAsync(e,t,n,s,o){Zn._ApplyExtensions(r=>r.loadBufferAsync(e,t,n,s,o),()=>{Yn.LoadBufferAsync(e,t,n,s,o)})}static LoadTextureAsync(e,t,n,s){Zn._LoadTextureBufferAsync(e,t,o=>{o&&Zn._CreateTextureAsync(e,t,o,n,s)},s)}static LoadShaderStringAsync(e,t,n,s){Zn._ApplyExtensions(o=>o.loadShaderStringAsync(e,t,n,s),()=>{Yn.LoadShaderStringAsync(e,t,n,s)})}static LoadMaterialAsync(e,t,n,s){Zn._ApplyExtensions(o=>o.loadMaterialAsync(e,t,n,s),()=>{Yn.LoadMaterialAsync(e,t,n,s)})}static _LoadTextureBufferAsync(e,t,n,s){Zn._ApplyExtensions(o=>o.loadTextureBufferAsync(e,t,n,s),()=>{Yn.LoadTextureBufferAsync(e,t,n,s)})}static _CreateTextureAsync(e,t,n,s,o){Zn._ApplyExtensions(r=>r.createTextureAsync(e,t,n,s,o),()=>{Yn.CreateTextureAsync(e,t,n,s)})}static _ApplyExtensions(e,t){for(const t in Qn.Extensions)if(e(Qn.Extensions[t]))return;t()}}let Jn=!1;function es(){Jn||(Jn=!0,_n._CreateGLTF1Loader=()=>new Qn)}class ts extends Zn{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(Yn.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(On.GetBufferFromBufferView(e,i,0,i.byteLength,yn.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=On.GetBufferFromBufferView(e,r,0,r.byteLength,yn.UNSIGNED_BYTE);return setTimeout(()=>{const e=On.DecodeBufferToText(i);n(e)}),!0}}let ns=!1;function ss(){ns||(ns=!0,Qn.RegisterExtension(new ts))}es(),vn(),ss();class os extends Zn{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){Yn.LoadTextureBufferAsync(e,t,o=>{Yn.CreateTextureAsync(e,t,o,e=>n[s]=e)},o)}}let rs=!1;function is(){rs||(rs=!0,Qn.RegisterExtension(new os))}is();var as={__proto__:null,get EBlendingFunction(){return Cn},get EComponentType(){return yn},get ECullingType(){return wn},get EParameterType(){return xn},get EShaderType(){return bn},get ETextureFilterType(){return An},get ETextureFormat(){return Mn},get ETextureWrapMode(){return Tn},GLTFBinaryExtension:ts,GLTFLoader:Qn,GLTFLoaderBase:Yn,GLTFLoaderExtension:Zn,GLTFMaterialsCommonExtension:os,GLTFUtils:On,RegisterGLTF1Loader:es,RegisterGLTFBinaryExtension:ss,RegisterGLTFMaterialsCommonExtension:is};const ls=new Map,us=ls;function cs(e,n,s){ds(e)&&t.Logger.Warn(`Extension with the name '${e}' already exists`),ls.set(e,{isGLTFExtension:n,factory:s})}function ds(e){return ls.delete(e)}const hs=[{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 fs{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(!hs.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 ms(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 ps={length:ms(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:ms(e=>{const t=bs(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=bs(e);if(n&&void 0!==t&&t>=0&&t<n.mtm.numTargets)return xs(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=bs(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=bs(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=bs(e);if(!t)return[];const n=[];for(let e=0;e<t.mtm.numTargets;e++)n.push(xs(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:ms(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)}}}}}},_s={length:ms(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}},gs={length:ms(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:ms(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:ms(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 vs(e,t,n,s){const o=ys(e);return s?o[n][s]:o[n]}function ys(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 bs(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 xs(e){return Number.isFinite(e)?parseFloat(e.toPrecision(7)):e}function Ts(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 As(e,n,s){return{offset:{componentsCount:2,type:"Vector2",get:(o,r,i)=>{var a,l;const u=vs(o,0,e,n);if(u)return new t.Vector2(u.uOffset,u.vOffset);if(s){const e=Ts(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:ys,set:(t,o,r,i)=>{const a=vs(o,0,e,n);if(a&&(a.uOffset=t.x,a.vOffset=t.y),s){const e=Ts(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=vs(t,0,e,n);if(a)return a.wAng;if(s){const e=Ts(t,s,!1);return null!==(i=null==e?void 0:e.rotation)&&void 0!==i?i:0}return 0},getTarget:ys,set:(t,o,r,i)=>{const a=vs(o,0,e,n);if(a&&(a.wAng=t),s){const e=Ts(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=vs(o,0,e,n);if(u)return new t.Vector2(u.uScale,u.vScale);if(s){const e=Ts(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:ys,set:(t,o,r,i)=>{const a=vs(o,0,e,n);if(a&&(a.uScale=t.x,a.vScale=t.y),s){const e=Ts(o,s,!0);e&&(e.scale=[t.x,t.y])}},getPropertyName:[()=>`${e}${n?"."+n:""}.uScale`,()=>`${e}${n?"."+n:""}.vScale`]}}}const Ms={scene:{__target__:!0,type:"number",get:e=>null!=e?e:0,getTarget:()=>({__gltfRoot:!0}),isReadOnly:!0,getPropertyName:[()=>"scene"]},cameras:{length:ms(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:ps,materials:{length:ms(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=ys(e,0,n))||void 0===s?void 0:s.backFaceCulling)},set:(e,t,n,s)=>{const o=ys(t,0,s);o&&(o.backFaceCulling=!e)},getTarget:(e,t,n)=>ys(e,0,n),getPropertyName:[()=>"backFaceCulling"]},alphaCutoff:{type:"number",get:(e,t,n)=>{var s;return null===(s=ys(e,0,n))||void 0===s?void 0:s.alphaCutOff},set:(e,t,n,s)=>{const o=ys(t,0,s);o&&(o.alphaCutOff=e)},getTarget:(e,t,n)=>ys(e,0,n),getPropertyName:[()=>"alphaCutOff"]},emissiveFactor:{type:"Color3",get:(e,t,n)=>ys(e,0,n).emissiveColor,set:(e,t,n,s)=>ys(t,0,s).emissiveColor.copyFrom(e),getTarget:(e,t,n)=>ys(e,0,n),getPropertyName:[()=>"emissiveColor"]},emissiveTexture:{extensions:{KHR_texture_transform:As("emissiveTexture")}},normalTexture:{scale:{type:"number",get:(e,t,n)=>{var s;return null===(s=vs(e,0,"bumpTexture"))||void 0===s?void 0:s.level},set:(e,t,n,s)=>{const o=vs(t,0,"bumpTexture");o&&(o.level=e)},getTarget:(e,t,n)=>ys(e,0,n),getPropertyName:[()=>"level"]},extensions:{KHR_texture_transform:As("bumpTexture")}},occlusionTexture:{strength:{type:"number",get:(e,t,n)=>ys(e,0,n).ambientTextureStrength,set:(e,t,n,s)=>{const o=ys(t,0,s);o&&(o.ambientTextureStrength=e)},getTarget:(e,t,n)=>ys(e,0,n),getPropertyName:[()=>"ambientTextureStrength"]},extensions:{KHR_texture_transform:As("ambientTexture")}},pbrMetallicRoughness:{baseColorFactor:{type:"Color4",get:(e,n,s)=>{const o=ys(e,0,s);return t.Color4.FromColor3(o.albedoColor,o.alpha)},set:(e,t,n,s)=>{const o=ys(t,0,s);o.albedoColor.set(e.r,e.g,e.b),o.alpha=e.a},getTarget:(e,t,n)=>ys(e,0,n),getPropertyName:[()=>"albedoColor",()=>"alpha"]},baseColorTexture:{extensions:{KHR_texture_transform:As("albedoTexture")}},metallicFactor:{type:"number",get:(e,t,n)=>ys(e,0,n).metallic,set:(e,t,n,s)=>{const o=ys(t,0,s);o&&(o.metallic=e)},getTarget:(e,t,n)=>ys(e,0,n),getPropertyName:[()=>"metallic"]},roughnessFactor:{type:"number",get:(e,t,n)=>ys(e,0,n).roughness,set:(e,t,n,s)=>{const o=ys(t,0,s);o&&(o.roughness=e)},getTarget:(e,t,n)=>ys(e,0,n),getPropertyName:[()=>"roughness"]},metallicRoughnessTexture:{extensions:{KHR_texture_transform:As("metallicTexture")}}},extensions:{KHR_materials_anisotropy:{anisotropyStrength:{type:"number",get:(e,t,n)=>{var s,o;return null===(o=null===(s=ys(e,0,n))||void 0===s?void 0:s.anisotropy)||void 0===o?void 0:o.intensity},set:(e,t,n,s)=>{const o=ys(t,0,s);o&&(o.anisotropy.intensity=e)},getTarget:(e,t,n)=>ys(e,0,n),getPropertyName:[()=>"anisotropy.intensity"]},anisotropyRotation:{type:"number",get:(e,t,n)=>{var s,o;return null===(o=null===(s=ys(e,0,n))||void 0===s?void 0:s.anisotropy)||void 0===o?void 0:o.angle},set:(e,t,n,s)=>{const o=ys(t,0,s);o&&(o.anisotropy.angle=e)},getTarget:(e,t,n)=>ys(e,0,n),getPropertyName:[()=>"anisotropy.angle"]},anisotropyTexture:{extensions:{KHR_texture_transform:As("anisotropy","texture")}}},KHR_materials_clearcoat:{clearcoatFactor:{type:"number",get:(e,t,n)=>ys(e,0,n).clearCoat.intensity,set:(e,t,n,s)=>{ys(t,0,s).clearCoat.intensity=e},getTarget:(e,t,n)=>ys(e,0,n),getPropertyName:[()=>"clearCoat.intensity"]},clearcoatRoughnessFactor:{type:"number",get:(e,t,n)=>ys(e,0,n).clearCoat.roughness,set:(e,t,n,s)=>{ys(t,0,s).clearCoat.roughness=e},getTarget:(e,t,n)=>ys(e,0,n),getPropertyName:[()=>"clearCoat.roughness"]},clearcoatTexture:{extensions:{KHR_texture_transform:As("clearCoat","texture")}},clearcoatNormalTexture:{scale:{type:"number",get:(e,t,n)=>{var s;return null===(s=ys(e,0,n).clearCoat.bumpTexture)||void 0===s?void 0:s.level},getTarget:ys,set:(e,t,n,s)=>ys(t,0,s).clearCoat.bumpTexture.level=e},extensions:{KHR_texture_transform:As("clearCoat","bumpTexture")}},clearcoatRoughnessTexture:{extensions:{KHR_texture_transform:As("clearCoat","textureRoughness")}}},KHR_materials_dispersion:{dispersion:{type:"number",get:(e,t,n)=>ys(e,0,n).subSurface.dispersion,getTarget:ys,set:(e,t,n,s)=>ys(t,0,s).subSurface.dispersion=e}},KHR_materials_emissive_strength:{emissiveStrength:{type:"number",get:(e,t,n)=>ys(e,0,n).emissiveIntensity,getTarget:ys,set:(e,t,n,s)=>ys(t,0,s).emissiveIntensity=e}},KHR_materials_ior:{ior:{type:"number",get:(e,t,n)=>ys(e,0,n).indexOfRefraction,getTarget:ys,set:(e,t,n,s)=>ys(t,0,s).indexOfRefraction=e}},KHR_materials_iridescence:{iridescenceFactor:{type:"number",get:(e,t,n)=>ys(e,0,n).iridescence.intensity,getTarget:ys,set:(e,t,n,s)=>ys(t,0,s).iridescence.intensity=e},iridescenceIor:{type:"number",get:(e,t,n)=>ys(e,0,n).iridescence.indexOfRefraction,getTarget:ys,set:(e,t,n,s)=>ys(t,0,s).iridescence.indexOfRefraction=e},iridescenceTexture:{extensions:{KHR_texture_transform:As("iridescence","texture")}},iridescenceThicknessMaximum:{type:"number",get:(e,t,n)=>ys(e,0,n).iridescence.maximumThickness,getTarget:ys,set:(e,t,n,s)=>ys(t,0,s).iridescence.maximumThickness=e},iridescenceThicknessMinimum:{type:"number",get:(e,t,n)=>ys(e,0,n).iridescence.minimumThickness,getTarget:ys,set:(e,t,n,s)=>ys(t,0,s).iridescence.minimumThickness=e},iridescenceThicknessTexture:{extensions:{KHR_texture_transform:As("iridescence","thicknessTexture")}}},KHR_materials_sheen:{sheenColorFactor:{type:"Color3",get:(e,t,n)=>ys(e,0,n).sheen.color,getTarget:ys,set:(e,t,n,s)=>ys(t,0,s).sheen.color.copyFrom(e)},sheenColorTexture:{extensions:{KHR_texture_transform:As("sheen","texture")}},sheenRoughnessFactor:{type:"number",get:(e,t,n)=>ys(e,0,n).sheen.intensity,getTarget:ys,set:(e,t,n,s)=>ys(t,0,s).sheen.intensity=e},sheenRoughnessTexture:{extensions:{KHR_texture_transform:As("sheen","textureRoughness")}}},KHR_materials_specular:{specularFactor:{type:"number",get:(e,t,n)=>ys(e,0,n).metallicF0Factor,getTarget:ys,set:(e,t,n,s)=>ys(t,0,s).metallicF0Factor=e,getPropertyName:[()=>"metallicF0Factor"]},specularColorFactor:{type:"Color3",get:(e,t,n)=>ys(e,0,n).metallicReflectanceColor,getTarget:ys,set:(e,t,n,s)=>ys(t,0,s).metallicReflectanceColor.copyFrom(e),getPropertyName:[()=>"metallicReflectanceColor"]},specularTexture:{extensions:{KHR_texture_transform:As("metallicReflectanceTexture")}},specularColorTexture:{extensions:{KHR_texture_transform:As("reflectanceTexture")}}},KHR_materials_transmission:{transmissionFactor:{type:"number",get:(e,t,n)=>ys(e,0,n).subSurface.refractionIntensity,getTarget:ys,set:(e,t,n,s)=>ys(t,0,s).subSurface.refractionIntensity=e,getPropertyName:[()=>"subSurface.refractionIntensity"]},transmissionTexture:{extensions:{KHR_texture_transform:As("subSurface","refractionIntensityTexture",{extensionKey:"KHR_materials_transmission",texturePath:["transmissionTexture"]})}}},KHR_materials_diffuse_transmission:{diffuseTransmissionFactor:{type:"number",get:(e,t,n)=>ys(e,0,n).subSurface.translucencyIntensity,getTarget:ys,set:(e,t,n,s)=>ys(t,0,s).subSurface.translucencyIntensity=e},diffuseTransmissionTexture:{extensions:{KHR_texture_transform:As("subSurface","translucencyIntensityTexture",{extensionKey:"KHR_materials_diffuse_transmission",texturePath:["diffuseTransmissionTexture"]})}},diffuseTransmissionColorFactor:{type:"Color3",get:(e,t,n)=>ys(e,0,n).subSurface.translucencyColor,getTarget:ys,set:(e,t,n,s)=>{var o;return e&&(null===(o=ys(t,0,s).subSurface.translucencyColor)||void 0===o?void 0:o.copyFrom(e))}},diffuseTransmissionColorTexture:{extensions:{KHR_texture_transform:As("subSurface","translucencyColorTexture",{extensionKey:"KHR_materials_diffuse_transmission",texturePath:["diffuseTransmissionColorTexture"]})}}},KHR_materials_volume:{attenuationColor:{type:"Color3",get:(e,t,n)=>ys(e,0,n).subSurface.tintColor,getTarget:ys,set:(e,t,n,s)=>ys(t,0,s).subSurface.tintColor.copyFrom(e)},attenuationDistance:{type:"number",get:(e,t,n)=>ys(e,0,n).subSurface.tintColorAtDistance,getTarget:ys,set:(e,t,n,s)=>ys(t,0,s).subSurface.tintColorAtDistance=e},thicknessFactor:{type:"number",get:(e,t,n)=>ys(e,0,n).subSurface.maximumThickness,getTarget:ys,set:(e,t,n,s)=>ys(t,0,s).subSurface.maximumThickness=e},thicknessTexture:{extensions:{KHR_texture_transform:As("subSurface","thicknessTexture",{extensionKey:"KHR_materials_volume",texturePath:["thicknessTexture"]})}}}}}},extensions:{KHR_lights_punctual:{lights:{length:ms(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:ms(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:ms(e=>e.length,e=>e.map(e=>e._babylonLight))}},EXT_lights_image_based:{lights:{length:ms(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:_s,meshes:gs,scenes:{length:ms(e=>e.length,e=>e),__array__:{__target__:!0,nodes:{length:ms(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:ms(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:ms(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 ws(e){return new fs(e,Ms)}function Cs(e){const t=e.split("/").map(e=>e.replace(/{}/g,"__array__"));let n=Ms;for(const e of t)e&&(n=n[e]);if(n&&n.type&&n.get)return n}function Rs(e,t){const n=e.split("/").map(e=>e.replace(/{}/g,"__array__"));let s=Ms;for(const e of n)e&&(s=s[e]);s&&s.type&&s.get&&(s.interpolation=t)}function Ss(e,t){const n=e.split("/").map(e=>e.replace(/{}/g,"__array__"));let s=Ms;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 Os=new t.Lazy(()=>Promise.resolve(BABYLON)),Fs=new t.Lazy(()=>Promise.resolve().then(function(){return qs}));class Es{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 Ls(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 Is{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){cs(e,!1,t)}static UnregisterExtension(e){return ds(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 zs})]).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 Xs})]).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=Es.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(Es.Assign(this._gltf.accessors),Es.Assign(this._gltf.animations),Es.Assign(this._gltf.buffers),Es.Assign(this._gltf.bufferViews),Es.Assign(this._gltf.cameras),Es.Assign(this._gltf.images),Es.Assign(this._gltf.materials),Es.Assign(this._gltf.meshes),Es.Assign(this._gltf.nodes),Es.Assign(this._gltf.samplers),Es.Assign(this._gltf.scenes),Es.Assign(this._gltf.skins),Es.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(us.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],Is._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=Es.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(Is.AddPointerMetadata(t,e),Is._LoadTransform(n,t),null!=n.camera){const s=Es.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=Es.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=Es.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=Es.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=Es.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=Es.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&&Es.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=Is._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=Es.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 Is.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=Es.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=Es.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=Ls(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=Es.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=Es.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=Es.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=Es.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=Es.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 Is.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)||Os.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;Es.Assign(t.channels),Es.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=Es.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?Fs.value.then(({RegisterGLTFLoaderAnimation:r})=>{var l,u,c,d;let h;switch(r(),a){case"translation":h=null===(l=Cs("/nodes/{}/translation"))||void 0===l?void 0:l.interpolation;break;case"rotation":h=null===(u=Cs("/nodes/{}/rotation"))||void 0===u?void 0:u.interpolation;break;case"scale":h=null===(c=Cs("/nodes/{}/scale"))||void 0===c?void 0:c.interpolation;break;case"weights":h=null===(d=Cs("/nodes/{}/weights"))||void 0===d?void 0:d.interpolation;break;default:throw new Error(`${e}/target/path: Invalid value (${s.target.path})`)}if(!h)throw new Error(`${e}/target/path: Could not find interpolation properties for target path (${s.target.path})`);const f={object:i,info:h};return this._loadAnimationChannelFromTargetInfoAsync(e,t,n,s,f,o)}):Promise.resolve()}_loadAnimationChannelFromTargetInfoAsync(e,t,n,s,o,r){const i=this.parent.targetFps,a=1/i,l=Es.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 f=0;switch(e.interpolation){case"STEP":for(let e=0;e<c.length;e++){const t=o.getValue(l,d,f,1);f+=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,f,a);f+=u;const n=o.getValue(l,d,f,1);f+=u;const s=o.getValue(l,d,f,a);f+=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,f,1);f+=u,h[e]={frame:c[e]*i,value:t}}}if(f>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=Es.Get(`${e}/input`,this._gltf.accessors,t.input),o=Es.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=Es.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=Is._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=Es.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 Is._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=Es.Get(`${e}/sparse/indices/bufferView`,this._gltf.bufferViews,i.indices.bufferView),c=Es.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=Is._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=Is._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=Is._GetTypedArray(`${e}/sparse/values`,n.componentType,u,i.values.byteOffset,d);let f=0;for(let e=0;e<c.length;e++){let t=c[e]*o;for(let e=0;e<o;e++)l[t++]=h[f++]}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=Is._GetTypedArrayConstructor(`${e}/componentType`,t.componentType);t._data=this._loadAccessorAsync(e,t,n)}else{const n=Es.Get(`${e}/bufferView`,this._gltf.bufferViews,t.bufferView);t._data=this.loadBufferViewAsync(`/bufferViews/${n.index}`,n).then(n=>Is._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=Es.Get(`${e}/bufferView`,this._gltf.bufferViews,n.bufferView);n._babylonVertexBuffer[s]=this._loadVertexBufferViewAsync(o).then(i=>{const a=Is._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,Is.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=Es.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,Is.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?Is.DefaultSampler:Es.Get(`${e}/sampler`,this._gltf.samplers,t.sampler),r=Es.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},f=new t.Texture(null,this._babylonScene,h);f._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,c.push(d.promise);const m=s.uri&&!t.IsBase64DataUrl(s.uri)?s.uri:void 0,p=null!=m?m:`${this._fileName}#image${s.index}`;if(c.push(this.loadImageAsync(`/images/${s.index}`,s).then(e=>{const t=`data:${this._uniqueRootUrl}${p}`;f.updateURL(t,e);const n=f.getInternalTexture();n&&(n.label=s.name)})),f.wrapU=u.wrapU,f.wrapV=u.wrapV,o(f),this._parent.useGltfTextureNames){const e=s.name||m||`image${s.index}`;f.name=e}return Promise.all(c).then(()=>f)}_loadSampler(e,t){return t._data||(t._data={noMipMaps:9728===t.minFilter||9729===t.minFilter,samplingMode:Is._GetTextureSamplingMode(e,t),wrapU:Is._GetTextureWrapMode(`${e}/wrapS`,t.wrapS),wrapV:Is._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=Es.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){var o;const r=this._extensionsLoadUriAsync(e,n,s);if(r)return r;if(!this._parent._isPreprocessUrlAsyncSet&&!Is._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,null!==(o=this._rootUrl)&&void 0!==o?o:void 0).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=Is._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)}}Is.DefaultSampler={index:-1};let Bs=!1;function Ns(){Bs||(Bs=!0,_n._CreateGLTF2Loader=e=>new Is(e))}var Ps={__proto__:null,ArrayItem:Es,GLTFFileLoader:_n,GLTFLoader:Is,LoadBoundingInfoFromPositionAccessor:Ls,RegisterGLTF2Loader:Ns};function ks(e,n,s,o){return t.Vector3.FromArray(n,s).scaleInPlace(o)}function Ds(e,n,s,o){return t.Quaternion.FromArray(n,s).scaleInPlace(o)}function Gs(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}Ns(),vn();class Vs{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 Hs extends Vs{buildAnimations(e,t,n,s){const o=[];return o.push({babylonAnimatable:e._babylonTransformNode,babylonAnimation:this._buildAnimation(t,n,s)}),o}}class Us extends Vs{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}}let Ks=!1;function $s(){Ks||(Ks=!0,Rs("/nodes/{}/translation",[new Hs(t.Animation.ANIMATIONTYPE_VECTOR3,"position",ks,()=>3)]),Rs("/nodes/{}/rotation",[new Hs(t.Animation.ANIMATIONTYPE_QUATERNION,"rotationQuaternion",Ds,()=>4)]),Rs("/nodes/{}/scale",[new Hs(t.Animation.ANIMATIONTYPE_VECTOR3,"scaling",ks,()=>3)]),Rs("/nodes/{}/weights",[new Us(t.Animation.ANIMATIONTYPE_FLOAT,"influence",Gs,e=>e._numMorphTargets)]))}var qs={__proto__:null,AnimationPropertyInfo:Vs,RegisterGLTFLoaderAnimation:$s,TransformNodeAnimationPropertyInfo:Hs,WeightAnimationPropertyInfo:Us,getQuaternion:Ds,getVector3:ks,getWeights:Gs};$s();class Ws{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,f,m,p,_;const g=this._material.coatWeight,v=this._material.coatWeightTexture,y=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,y.toColor4(),t.TextureChannel.RGBA,t.TextureColorSpace.SRGB),t.CreateTextureWithFactorOperand(v,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(v,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(v,T,t.TextureChannel.R),this._material.getScene());if(e._disposed)return void(null===(f=F.texture)||void 0===f||f.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(v,T,t.TextureChannel.R),this._material.getScene());if(e._disposed)null===(m=E.texture)||void 0===m||m.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(v,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 zs={__proto__:null,OpenPBRMaterialLoadingAdapter:Ws};class js{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 Xs={__proto__:null,PBRMaterialLoadingAdapter:js};const Ys="EXT_lights_image_based";class Qs{constructor(e){this.name=Ys,this._loader=e,this.enabled=this._loader.isExtensionUsed(Ys)}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 Is.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=Es.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=Es.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)}}let Zs=!1;function Js(){Zs||(Zs=!0,ds(Ys),cs(Ys,!0,e=>new Qs(e)))}var eo={__proto__:null,EXT_lights_image_based:Qs,RegisterEXT_lights_image_based:Js};Js();const to="EXT_mesh_gpu_instancing";class no{constructor(e){this.name=to,this._loader=e,this.enabled=this._loader.isExtensionUsed(to)}dispose(){this._loader=null}loadNodeAsync(e,n,s){return Is.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=Es.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}))}))}}let so=!1;function oo(){so||(so=!0,ds(to),cs(to,!0,e=>new no(e)))}var ro={__proto__:null,EXT_mesh_gpu_instancing:no,RegisterEXT_mesh_gpu_instancing:oo};oo();const io="EXT_meshopt_compression";class ao{constructor(e){this.name=io,this.enabled=e.isExtensionUsed(io),this._loader=e}dispose(){this._loader=null}loadBufferViewAsync(e,n){return Is.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=Es.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}))}}let lo=!1;function uo(){lo||(lo=!0,ds(io),cs(io,!0,e=>new ao(e)))}var co={__proto__:null,EXT_meshopt_compression:ao,RegisterEXT_meshopt_compression:uo};uo();const ho="EXT_texture_webp";class fo{constructor(e){this.name=ho,this._loader=e,this.enabled=e.isExtensionUsed(ho)}dispose(){this._loader=null}_loadTextureAsync(e,t,n){return Is.LoadExtensionAsync(e,t,this.name,(s,o)=>b(this,void 0,void 0,function*(){const r=null==t.sampler?Is.DefaultSampler:Es.Get(`${e}/sampler`,this._loader.gltf.samplers,t.sampler),i=Es.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)}))}}let mo=!1;function po(){mo||(mo=!0,ds(ho),cs(ho,!0,e=>new fo(e)))}var _o={__proto__:null,EXT_texture_webp:fo,RegisterEXT_texture_webp:po};po();const go="EXT_texture_avif";class vo{constructor(e){this.name=go,this._loader=e,this.enabled=e.isExtensionUsed(go)}dispose(){this._loader=null}_loadTextureAsync(e,t,n){return Is.LoadExtensionAsync(e,t,this.name,(s,o)=>b(this,void 0,void 0,function*(){const r=null==t.sampler?Is.DefaultSampler:Es.Get(`${e}/sampler`,this._loader.gltf.samplers,t.sampler),i=Es.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)}))}}let yo=!1;function bo(){yo||(yo=!0,ds(go),cs(go,!0,e=>new vo(e)))}var xo={__proto__:null,EXT_texture_avif:vo,RegisterEXT_texture_avif:bo};bo();const To="EXT_lights_ies";class Ao{constructor(e){this.name=To,this._loader=e,this.enabled=this._loader.isExtensionUsed(To)}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,Es.Assign(this._lights)}}loadNodeAsync(e,n,s){return Is.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=Es.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),Is.AddPointerMetadata(i,o),s(e)});let u;if(a.uri)u=yield this._loader.loadUriAsync(e,a,a.uri);else{const t=Es.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}))}}let Mo=!1;function wo(){Mo||(Mo=!0,ds(To),cs(To,!0,e=>new Ao(e)))}var Co={__proto__:null,EXT_lights_ies:Ao,RegisterEXT_lights_ies:wo};wo();const Ro="KHR_draco_mesh_compression";class So{constructor(e){this.name=Ro,this.useNormalizedFlagFromAccessor=!0,this._loader=e,this.enabled=t.DracoDecoder.DefaultAvailable&&this._loader.isExtensionUsed(Ro)}dispose(){delete this.dracoDecoder,this._loader=null}_loadVertexDataAsync(e,n,s){return Is.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=Es.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=Es.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=Es.TryGet(this._loader.gltf.accessors,n.attributes.POSITION),u=this._loader.parent.alwaysComputeBoundingBox||s.skeleton||!l?null:Ls(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}))}}let Oo=!1;function Fo(){Oo||(Oo=!0,ds(Ro),cs(Ro,!0,e=>new So(e)))}var Eo={__proto__:null,KHR_draco_mesh_compression:So,RegisterKHR_draco_mesh_compression:Fo};Fo();const Lo="KHR_gaussian_splatting",Io=.28209479177387814,Bo=[0,3,5,7];function No(e){return e<=0?0:e>=255?255:e+.5|0}class Po{constructor(e){this.name=Lo,this._loader=e,this.enabled=this._loader.isExtensionUsed(Lo)}dispose(){this._loader=null}_loadMeshPrimitiveAsync(e,n,s,o,r,i){return Is.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=Es.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<Bo[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,Is.AddPointerMetadata(h,e),o.parent.onMeshLoadedObservable.notifyObservers(h),i(h);const f=d.getEngine().getCaps(),[m,p,_,g,v,y,...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=m.length/3,T=y?y.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=f.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]=m[s+0],M[t+1]=m[s+1],M[t+2]=m[s+2],M[t+3]=_?_[s+0]:1,M[t+4]=_?_[s+1]:1,M[t+5]=_?_[s+2]:1,v)w[n+24]=No(255*(.5+Io*v[s+0])),w[n+25]=No(255*(.5+Io*v[s+1])),w[n+26]=No(255*(.5+Io*v[s+2]));else if(y){const t=e*T;w[n+24]=No(255*y[t+0]),w[n+25]=No(255*y[t+1]),w[n+26]=No(255*y[t+2])}else w[n+24]=255,w[n+25]=255,w[n+26]=255;w[n+27]=g?No(255*g[e]):y&&T>=4?No(255*y[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]=No(127.5*l+127.5),w[n+29]=No(127.5*r+127.5),w[n+30]=No(127.5*i+127.5),w[n+31]=No(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]=No(128*n[s+o]+128)}}}}return yield h.updateDataAsync(A,null!=C?C:void 0,void 0,u||void 0),h}))}}let ko=!1;function Do(){ko||(ko=!0,ds(Lo),cs(Lo,!0,e=>new Po(e)))}var Go={__proto__:null,KHR_gaussian_splatting:Po,RegisterKHR_gaussian_splatting:Do};Do();const Vo="KHR_lights_punctual";class Ho{constructor(e){this.name=Vo,this._loader=e,this.enabled=this._loader.isExtensionUsed(Vo)}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,Es.Assign(this._lights)}}loadNodeAsync(e,n,s){return Is.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=Es.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),Is.AddPointerMetadata(n,o),s(e)})}))}}let Uo=!1;function Ko(){Uo||(Uo=!0,ds(Vo),cs(Vo,!0,e=>new Ho(e)))}var $o={__proto__:null,KHR_lights:Ho,RegisterKHR_lights:Ko};Ko();const qo="EXT_lights_area";class Wo{constructor(e){this.name=qo,this._loader=e,this.enabled=this._loader.isExtensionUsed(qo)}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,Es.Assign(this._lights)}}loadNodeAsync(e,n,s){return Is.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=Es.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),Is.AddPointerMetadata(i,o),s(e)})}))}}let zo=!1;function jo(){zo||(zo=!0,ds(qo),cs(qo,!0,e=>new Wo(e)))}var Xo={__proto__:null,EXT_lights_area:Wo,RegisterEXT_lights_area:jo};jo();const Yo="KHR_materials_pbrSpecularGlossiness";class Qo{constructor(e){this.name=Yo,this.order=200,this._loader=e,this.enabled=this._loader.isExtensionUsed(Yo)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return Is.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(()=>{})}}let Zo=!1;function Jo(){Zo||(Zo=!0,ds(Yo),cs(Yo,!0,e=>new Qo(e)))}var er={__proto__:null,KHR_materials_pbrSpecularGlossiness:Qo,RegisterKHR_materials_pbrSpecularGlossiness:Jo};Jo();const tr="KHR_materials_unlit";class nr{constructor(e){this.name=tr,this.order=210,this._loader=e,this.enabled=this._loader.isExtensionUsed(tr)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return Is.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(()=>{})}}let sr=!1;function or(){sr||(sr=!0,ds(tr),cs(tr,!0,e=>new nr(e)))}var rr={__proto__:null,KHR_materials_unlit:nr,RegisterKHR_materials_unlit:or};or();const ir="KHR_materials_clearcoat";class ar{constructor(e){this.name=ir,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(ir)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return Is.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(()=>{})}}let lr=!1;function ur(){lr||(lr=!0,ds(ir),cs(ir,!0,e=>new ar(e)))}var cr={__proto__:null,KHR_materials_clearcoat:ar,RegisterKHR_materials_clearcoat:ur};ur();const dr="KHR_materials_coat";class hr{constructor(e){this.name=dr,this.order=191,this.useOpenPBR=!1,this._loader=e,this.enabled=this._loader.isExtensionUsed(dr)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return Is.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(()=>{})}}let fr=!1;function mr(){fr||(fr=!0,ds(dr),cs(dr,!0,e=>new hr(e)))}var pr={__proto__:null,KHR_materials_coat:hr,RegisterKHR_materials_coat:mr};mr();const _r="KHR_materials_iridescence";class gr{constructor(e){this.name=_r,this.order=195,this._loader=e,this.enabled=this._loader.isExtensionUsed(_r)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return Is.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(()=>{})}}let vr=!1;function yr(){vr||(vr=!0,ds(_r),cs(_r,!0,e=>new gr(e)))}var br={__proto__:null,KHR_materials_iridescence:gr,RegisterKHR_materials_iridescence:yr};yr();const xr="KHR_materials_anisotropy";class Tr{constructor(e){this.name=xr,this.order=195,this._loader=e,this.enabled=this._loader.isExtensionUsed(xr)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return Is.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)})}}let Ar=!1;function Mr(){Ar||(Ar=!0,ds(xr),cs(xr,!0,e=>new Tr(e)))}var wr={__proto__:null,KHR_materials_anisotropy:Tr,RegisterKHR_materials_anisotropy:Mr};Mr();const Cr="KHR_materials_emissive_strength";class Rr{constructor(e){this.name=Cr,this.order=170,this._loader=e,this.enabled=this._loader.isExtensionUsed(Cr)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return Is.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)}}let Sr=!1;function Or(){Sr||(Sr=!0,ds(Cr),cs(Cr,!0,e=>new Rr(e)))}var Fr={__proto__:null,KHR_materials_emissive_strength:Rr,RegisterKHR_materials_emissive_strength:Or};Or();const Er="KHR_materials_sheen";class Lr{constructor(e){this.name=Er,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(Er)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return Is.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(()=>{})}}let Ir=!1;function Br(){Ir||(Ir=!0,ds(Er),cs(Er,!0,e=>new Lr(e)))}var Nr={__proto__:null,KHR_materials_sheen:Lr,RegisterKHR_materials_sheen:Br};Br();const Pr="KHR_materials_fuzz";class kr{constructor(e){this.name=Pr,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(Pr)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return Is.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(()=>{})}}let Dr=!1;function Gr(){Dr||(Dr=!0,ds(Pr),cs(Pr,!0,e=>new kr(e)))}var Vr={__proto__:null,KHR_materials_fuzz:kr,RegisterKHR_materials_fuzz:Gr};Gr();const Hr="KHR_materials_specular";class Ur{constructor(e){this.name=Hr,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(Hr)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return Is.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(()=>{})}}let Kr=!1;function $r(){Kr||(Kr=!0,ds(Hr),cs(Hr,!0,e=>new Ur(e)))}var qr={__proto__:null,KHR_materials_specular:Ur,RegisterKHR_materials_specular:$r};$r();const Wr="KHR_materials_ior";class zr{constructor(e){this.name=Wr,this.order=180,this._loader=e,this.enabled=this._loader.isExtensionUsed(Wr)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return Is.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(e,t,n){const s=this._loader._getOrCreateMaterialAdapter(n),o=void 0!==t.ior?t.ior:zr._DEFAULT_IOR;return s.specularIor=o,Promise.resolve()}}zr._DEFAULT_IOR=1.5;let jr=!1;function Xr(){jr||(jr=!0,ds(Wr),cs(Wr,!0,e=>new zr(e)))}var Yr={__proto__:null,KHR_materials_ior:zr,RegisterKHR_materials_ior:Xr};Xr();const Qr="KHR_materials_variants";class Zr{constructor(e){this.name=Qr,this._loader=e,this.enabled=this._loader.isExtensionUsed(Qr)&&!this._loader.parent.skipMaterials}dispose(){this._loader=null}static GetAvailableVariants(e){const t=this._GetExtensionMetadata(e);return t?Object.keys(t.variants):[]}getAvailableVariants(e){return Zr.GetAvailableVariants(e)}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 ${Qr} 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(e,t){Zr.SelectVariant(e,t)}static Reset(e){const t=this._GetExtensionMetadata(e);if(!t)throw new Error(`Cannot reset on a glTF mesh that does not have the ${Qr} extension`);for(const e of t.original)e.mesh.material=e.material;t.lastSelected=null}reset(e){Zr.Reset(e)}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 ${Qr} extension`);return t.lastSelected}getLastSelectedVariant(e){return Zr.GetLastSelectedVariant(e)}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[Qr])||null}onLoading(){const e=this._loader.gltf.extensions;if(e&&e[this.name]){const t=e[this.name];this._variants=t.variants}}onReady(){var e;const t=this._loader.rootBabylonMesh;if(t){const n=this._loader.parent.extensionOptions[Qr];(null==n?void 0:n.defaultVariant)&&Zr.SelectVariant(t,n.defaultVariant),null===(e=null==n?void 0:n.onLoaded)||void 0===e||e.call(n,{get variants(){return Zr.GetAvailableVariants(t)},get selectedVariant(){const e=Zr.GetLastSelectedVariant(t);return e?Array.isArray(e)?e[0]:e:Zr.GetAvailableVariants(t)[0]},set selectedVariant(e){Zr.SelectVariant(t,e)}})}}_loadMeshPrimitiveAsync(e,n,s,o,r,i){return Is.LoadExtensionAsync(e,r,this.name,(a,l)=>b(this,void 0,void 0,function*(){const u=new Array;return u.push(this._loader._loadMeshPrimitiveAsync(e,n,s,o,r,n=>{if(i(n),n instanceof t.Mesh){const t=Is._GetDrawMode(e,r.mode),s=this._loader.rootBabylonMesh,o=s?s._internalMetadata=s._internalMetadata||{}:{},i=o.gltf=o.gltf||{},c=i[Qr]=i[Qr]||{lastSelected:null,original:[],variants:{}};c.original.push({mesh:n,material:n.material});for(let e=0;e<l.mappings.length;++e){const o=l.mappings[e],r=Es.Get(`${a}/mappings/${e}/material`,this._loader.gltf.materials,o.material);u.push(this._loader._loadMaterialAsync(`#/materials/${o.material}`,r,n,t,e=>{for(let t=0;t<o.variants.length;++t){const r=o.variants[t],i=Es.Get(`/extensions/${Qr}/variants/${r}`,this._variants,r);c.variants[i.name]=c.variants[i.name]||[],c.variants[i.name].push({mesh:n,material:e}),n.onClonedObservable.add(e=>{const t=e;let o,r=t;do{if(r=r.parent,!r)return;o=Zr._GetExtensionMetadata(r)}while(null===o);if(s&&o===Zr._GetExtensionMetadata(s)){r._internalMetadata={};for(const e in s._internalMetadata)r._internalMetadata[e]=s._internalMetadata[e];r._internalMetadata.gltf=[];for(const e in s._internalMetadata.gltf)r._internalMetadata.gltf[e]=s._internalMetadata.gltf[e];r._internalMetadata.gltf[Qr]={lastSelected:null,original:[],variants:{}};for(const e of o.original)r._internalMetadata.gltf[Qr].original.push({mesh:e.mesh,material:e.material});for(const e in o.variants)if(Object.prototype.hasOwnProperty.call(o.variants,e)){r._internalMetadata.gltf[Qr].variants[e]=[];for(const t of o.variants[e])r._internalMetadata.gltf[Qr].variants[e].push({mesh:t.mesh,material:t.material})}o=r._internalMetadata.gltf[Qr]}for(const e of o.original)e.mesh===n&&(e.mesh=t);for(const e of o.variants[i.name])e.mesh===n&&(e.mesh=t)})}}))}}})),yield Promise.all(u).then(([e])=>e)}))}}let Jr=!1;function ei(){Jr||(Jr=!0,ds(Qr),cs(Qr,!0,e=>new Zr(e)))}var ti={__proto__:null,KHR_materials_variants:Zr,RegisterKHR_materials_variants:ei};ei();class ni{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({},ni._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 si(e,t){if(e.parent.dontUseTransmissionHelper)return;const n=t.getScene()._transmissionHelper,s=null!=n?n:new ni({},t.getScene());for(const t of Array.from(e._pbrMaterialImpls.values()))s.addMaterialImpl(t);n&&!n._isRenderTargetValid()&&n._setupRenderTargets()}const oi="KHR_materials_transmission";class ri{constructor(e){this.name=oi,this.order=175,this._loader=e,this.enabled=this._loader.isExtensionUsed(oi),this.enabled&&(e.parent.transparencyAsCoverage=!0)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return Is.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&&si(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(()=>{})}}let ii=!1;function ai(){ii||(ii=!0,ds(oi),cs(oi,!0,e=>new ri(e)))}var li={__proto__:null,KHR_materials_transmission:ri,RegisterKHR_materials_transmission:ai};ai();const ui="KHR_materials_diffuse_transmission";class ci{constructor(e){this.name=ui,this.order=174,this._loader=e,this.enabled=this._loader.isExtensionUsed(ui),this.enabled&&(e.parent.transparencyAsCoverage=!0)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return Is.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&&si(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(()=>{})}}let di=!1;function hi(){di||(di=!0,ds(ui),cs(ui,!0,e=>new ci(e)))}var fi={__proto__:null,KHR_materials_diffuse_transmission:ci,RegisterKHR_materials_diffuse_transmission:hi};hi();const mi="KHR_materials_volume";class pi{constructor(e){this.name=mi,this.order=173,this._loader=e,this.enabled=this._loader.isExtensionUsed(mi),this.enabled&&this._loader._disableInstancedMesh++}dispose(){this.enabled&&this._loader._disableInstancedMesh--,this._loader=null}loadMaterialPropertiesAsync(e,t,n){return Is.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(()=>{})}}let _i=!1;function gi(){_i||(_i=!0,ds(mi),cs(mi,!0,e=>new pi(e)))}var vi={__proto__:null,KHR_materials_volume:pi,RegisterKHR_materials_volume:gi};gi();const yi="KHR_materials_volume_scatter";class bi{constructor(e){this.name=yi,this.order=172,this._loader=e,this.enabled=this._loader.isExtensionUsed(yi),this.enabled&&this._loader._disableInstancedMesh++}dispose(){this.enabled&&this._loader._disableInstancedMesh--,this._loader=null}loadMaterialPropertiesAsync(e,t,n){return Is.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(()=>{})}}let xi=!1;function Ti(){xi||(xi=!0,ds(yi),cs(yi,!0,e=>new bi(e)))}var Ai={__proto__:null,KHR_materials_volume_scatter:bi,RegisterKHR_materials_volume_scatter:Ti};Ti();const Mi="KHR_materials_dispersion";class wi{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 Is.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()}}let Ci=!1;function Ri(){Ci||(Ci=!0,ds(Mi),cs(Mi,!0,e=>new wi(e)))}var Si={__proto__:null,KHR_materials_dispersion:wi,RegisterKHR_materials_dispersion:Ri};Ri();const Oi="KHR_materials_diffuse_roughness";class Fi{constructor(e){this.name=Oi,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(Oi)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return Is.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(()=>{})}}let Ei=!1;function Li(){Ei||(Ei=!0,ds(Oi),cs(Oi,!0,e=>new Fi(e)))}var Ii={__proto__:null,KHR_materials_diffuse_roughness:Fi,RegisterKHR_materials_diffuse_roughness:Li};Li();const Bi="KHR_mesh_quantization";class Ni{constructor(e){this.name=Bi,this.enabled=e.isExtensionUsed(Bi)}dispose(){}}let Pi=!1;function ki(){Pi||(Pi=!0,ds(Bi),cs(Bi,!0,e=>new Ni(e)))}var Di={__proto__:null,KHR_mesh_quantization:Ni,RegisterKHR_mesh_quantization:ki};ki();const Gi="KHR_texture_basisu";class Vi{constructor(e){this.name=Gi,this._loader=e,this.enabled=e.isExtensionUsed(Gi)}dispose(){this._loader=null}_loadTextureAsync(e,t,n){return Is.LoadExtensionAsync(e,t,this.name,(s,o)=>b(this,void 0,void 0,function*(){const r=null==t.sampler?Is.DefaultSampler:Es.Get(`${e}/sampler`,this._loader.gltf.samplers,t.sampler),i=Es.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)}))}}let Hi=!1;function Ui(){Hi||(Hi=!0,ds(Gi),cs(Gi,!0,e=>new Vi(e)))}var Ki={__proto__:null,KHR_texture_basisu:Vi,RegisterKHR_texture_basisu:Ui};Ui();const $i="KHR_texture_transform";class qi{constructor(e){this.name=$i,this._loader=e,this.enabled=this._loader.isExtensionUsed($i)}dispose(){this._loader=null}loadTextureInfoAsync(e,n,s){return Is.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)})}))}}let Wi=!1;function zi(){Wi||(Wi=!0,ds($i),cs($i,!0,e=>new qi(e)))}var ji={__proto__:null,KHR_texture_transform:qi,RegisterKHR_texture_transform:zi};zi();const Xi="KHR_xmp_json_ld";class Yi{constructor(e){this.name=Xi,this.order=100,this._loader=e,this.enabled=this._loader.isExtensionUsed(Xi)}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])}}}let Qi=!1;function Zi(){Qi||(Qi=!0,ds(Xi),cs(Xi,!0,e=>new Yi(e)))}var Ji={__proto__:null,KHR_xmp_json_ld:Yi,RegisterKHR_xmp_json_ld:Zi};Zi();const ea="KHR_animation_pointer";class ta{constructor(e){this.name=ea,this._loader=e,this._pathToObjectConverter=ws(this._loader.gltf)}get enabled(){return this._loader.isExtensionUsed(ea)}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}}}let na=!1;function sa(){na||(na=!0,ds(ea),cs(ea,!0,e=>new ta(e)))}var oa={__proto__:null,KHR_animation_pointer:ta,RegisterKHR_animation_pointer:sa};function ra(e,n,s,o){return t.Color3.FromArray(n,s).scale(o)}function ia(e,t,n,s){return t[n+3]*s}function aa(e,t,n,s){return t[n]*s}function la(e,t,n,s){return-t[n]*s}function ua(e,t,n,s){return t[n+1]*s}function ca(e,t,n,s){return t[n]*s*2}function da(e){return{scale:[new fa(t.Animation.ANIMATIONTYPE_FLOAT,`${e}.uScale`,aa,()=>2),new fa(t.Animation.ANIMATIONTYPE_FLOAT,`${e}.vScale`,ua,()=>2)],offset:[new fa(t.Animation.ANIMATIONTYPE_FLOAT,`${e}.uOffset`,aa,()=>2),new fa(t.Animation.ANIMATIONTYPE_FLOAT,`${e}.vOffset`,ua,()=>2)],rotation:[new fa(t.Animation.ANIMATIONTYPE_FLOAT,`${e}.wAng`,la,()=>1)]}}class ha extends Vs{buildAnimations(e,t,n,s){return[{babylonAnimatable:e._babylonCamera,babylonAnimation:this._buildAnimation(t,n,s)}]}}class fa extends Vs{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 ma extends Vs{buildAnimations(e,t,n,s){return[{babylonAnimatable:e._babylonLight,babylonAnimation:this._buildAnimation(t,n,s)}]}}class pa extends Vs{buildAnimations(e,t,n,s){return e._primitiveBabylonMeshes?e._primitiveBabylonMeshes.map(e=>({babylonAnimatable:e,babylonAnimation:this._buildAnimation(t,n,s)})):[]}}let _a=!1;function ga(){if(_a)return;_a=!0,$s(),Rs("/cameras/{}/orthographic/xmag",[new ha(t.Animation.ANIMATIONTYPE_FLOAT,"orthoLeft",la,()=>1),new ha(t.Animation.ANIMATIONTYPE_FLOAT,"orthoRight",ua,()=>1)]),Rs("/cameras/{}/orthographic/ymag",[new ha(t.Animation.ANIMATIONTYPE_FLOAT,"orthoBottom",la,()=>1),new ha(t.Animation.ANIMATIONTYPE_FLOAT,"orthoTop",ua,()=>1)]),Rs("/cameras/{}/orthographic/zfar",[new ha(t.Animation.ANIMATIONTYPE_FLOAT,"maxZ",aa,()=>1)]),Rs("/cameras/{}/orthographic/znear",[new ha(t.Animation.ANIMATIONTYPE_FLOAT,"minZ",aa,()=>1)]),Rs("/cameras/{}/perspective/yfov",[new ha(t.Animation.ANIMATIONTYPE_FLOAT,"fov",aa,()=>1)]),Rs("/cameras/{}/perspective/zfar",[new ha(t.Animation.ANIMATIONTYPE_FLOAT,"maxZ",aa,()=>1)]),Rs("/cameras/{}/perspective/znear",[new ha(t.Animation.ANIMATIONTYPE_FLOAT,"minZ",aa,()=>1)]),Rs("/materials/{}/pbrMetallicRoughness/baseColorFactor",[new fa(t.Animation.ANIMATIONTYPE_COLOR3,"albedoColor",ra,()=>4),new fa(t.Animation.ANIMATIONTYPE_FLOAT,"alpha",ia,()=>4)]),Rs("/materials/{}/pbrMetallicRoughness/metallicFactor",[new fa(t.Animation.ANIMATIONTYPE_FLOAT,"metallic",aa,()=>1)]),Rs("/materials/{}/pbrMetallicRoughness/metallicFactor",[new fa(t.Animation.ANIMATIONTYPE_FLOAT,"roughness",aa,()=>1)]);const e=da("albedoTexture");Rs("/materials/{}/pbrMetallicRoughness/baseColorTexture/extensions/KHR_texture_transform/scale",e.scale),Rs("/materials/{}/pbrMetallicRoughness/baseColorTexture/extensions/KHR_texture_transform/offset",e.offset),Rs("/materials/{}/pbrMetallicRoughness/baseColorTexture/extensions/KHR_texture_transform/rotation",e.rotation);const n=da("metallicTexture");Rs("//materials/{}/pbrMetallicRoughness/metallicRoughnessTexture/scale",n.scale),Rs("//materials/{}/pbrMetallicRoughness/metallicRoughnessTexture/offset",n.offset),Rs("//materials/{}/pbrMetallicRoughness/metallicRoughnessTexture/rotation",n.rotation),Rs("/materials/{}/emissiveFactor",[new fa(t.Animation.ANIMATIONTYPE_COLOR3,"emissiveColor",ra,()=>3)]);const s=da("bumpTexture");Rs("/materials/{}/normalTexture/scale",[new fa(t.Animation.ANIMATIONTYPE_FLOAT,"bumpTexture.level",aa,()=>1)]),Rs("/materials/{}/normalTexture/extensions/KHR_texture_transform/scale",s.scale),Rs("/materials/{}/normalTexture/extensions/KHR_texture_transform/offset",s.offset),Rs("/materials/{}/normalTexture/extensions/KHR_texture_transform/rotation",s.rotation),Rs("/materials/{}/occlusionTexture/strength",[new fa(t.Animation.ANIMATIONTYPE_FLOAT,"ambientTextureStrength",aa,()=>1)]);const o=da("ambientTexture");Rs("/materials/{}/occlusionTexture/extensions/KHR_texture_transform/scale",o.scale),Rs("/materials/{}/occlusionTexture/extensions/KHR_texture_transform/offset",o.offset),Rs("/materials/{}/occlusionTexture/extensions/KHR_texture_transform/rotation",o.rotation);const r=da("emissiveTexture");Rs("/materials/{}/emissiveTexture/extensions/KHR_texture_transform/scale",r.scale),Rs("/materials/{}/emissiveTexture/extensions/KHR_texture_transform/offset",r.offset),Rs("/materials/{}/emissiveTexture/extensions/KHR_texture_transform/rotation",r.rotation),Rs("/materials/{}/extensions/KHR_materials_anisotropy/anisotropyStrength",[new fa(t.Animation.ANIMATIONTYPE_FLOAT,"anisotropy.intensity",aa,()=>1)]),Rs("/materials/{}/extensions/KHR_materials_anisotropy/anisotropyRotation",[new fa(t.Animation.ANIMATIONTYPE_FLOAT,"anisotropy.angle",aa,()=>1)]);const i=da("anisotropy.texture");Rs("/materials/{}/extensions/KHR_materials_anisotropy/anisotropyTexture/extensions/KHR_texture_transform/scale",i.scale),Rs("/materials/{}/extensions/KHR_materials_anisotropy/anisotropyTexture/extensions/KHR_texture_transform/offset",i.offset),Rs("/materials/{}/extensions/KHR_materials_anisotropy/anisotropyTexture/extensions/KHR_texture_transform/rotation",i.rotation),Rs("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatFactor",[new fa(t.Animation.ANIMATIONTYPE_FLOAT,"clearCoat.intensity",aa,()=>1)]),Rs("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatRoughnessFactor",[new fa(t.Animation.ANIMATIONTYPE_FLOAT,"clearCoat.roughness",aa,()=>1)]);const a=da("clearCoat.texture");Rs("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatTexture/extensions/KHR_texture_transform/scale",a.scale),Rs("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatTexture/extensions/KHR_texture_transform/offset",a.offset),Rs("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatTexture/extensions/KHR_texture_transform/rotation",a.rotation);const l=da("clearCoat.bumpTexture");Rs("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatNormalTexture/scale",[new fa(t.Animation.ANIMATIONTYPE_FLOAT,"clearCoat.bumpTexture.level",aa,()=>1)]),Rs("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatNormalTexture/extensions/KHR_texture_transform/scale",l.scale),Rs("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatNormalTexture/extensions/KHR_texture_transform/offset",l.offset),Rs("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatNormalTexture/extensions/KHR_texture_transform/rotation",l.rotation);const u=da("clearCoat.textureRoughness");Rs("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatRoughnessTexture/extensions/KHR_texture_transform/scale",u.scale),Rs("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatRoughnessTexture/extensions/KHR_texture_transform/offset",u.offset),Rs("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatRoughnessTexture/extensions/KHR_texture_transform/rotation",u.rotation),Rs("/materials/{}/extensions/KHR_materials_dispersion/dispersionFactor",[new fa(t.Animation.ANIMATIONTYPE_FLOAT,"subSurface.dispersion",aa,()=>1)]),Rs("/materials/{}/extensions/KHR_materials_emissive_strength/emissiveStrength",[new fa(t.Animation.ANIMATIONTYPE_FLOAT,"emissiveIntensity",aa,()=>1)]),Rs("/materials/{}/extensions/KHR_materials_ior/ior",[new fa(t.Animation.ANIMATIONTYPE_FLOAT,"indexOfRefraction",aa,()=>1)]),Rs("/materials/{}/extensions/KHR_materials_iridescence/iridescenceFactor",[new fa(t.Animation.ANIMATIONTYPE_FLOAT,"iridescence.intensity",aa,()=>1)]),Rs("/materials/{}/extensions/KHR_materials_iridescence/iridescenceIor",[new fa(t.Animation.ANIMATIONTYPE_FLOAT,"iridescence.indexOfRefraction",aa,()=>1)]),Rs("/materials/{}/extensions/KHR_materials_iridescence/iridescenceThicknessMinimum",[new fa(t.Animation.ANIMATIONTYPE_FLOAT,"iridescence.minimumThickness",aa,()=>1)]),Rs("/materials/{}/extensions/KHR_materials_iridescence/iridescenceThicknessMaximum",[new fa(t.Animation.ANIMATIONTYPE_FLOAT,"iridescence.maximumThickness",aa,()=>1)]);const c=da("iridescence.texture");Rs("/materials/{}/extensions/KHR_materials_iridescence/iridescenceTexture/extensions/KHR_texture_transform/scale",c.scale),Rs("/materials/{}/extensions/KHR_materials_iridescence/iridescenceTexture/extensions/KHR_texture_transform/offset",c.offset),Rs("/materials/{}/extensions/KHR_materials_iridescence/iridescenceTexture/extensions/KHR_texture_transform/rotation",c.rotation);const d=da("iridescence.thicknessTexture");Rs("/materials/{}/extensions/KHR_materials_iridescence/iridescenceThicknessTexture/extensions/KHR_texture_transform/scale",d.scale),Rs("/materials/{}/extensions/KHR_materials_iridescence/iridescenceThicknessTexture/extensions/KHR_texture_transform/offset",d.offset),Rs("/materials/{}/extensions/KHR_materials_iridescence/iridescenceThicknessTexture/extensions/KHR_texture_transform/rotation",d.rotation),Rs("/materials/{}/extensions/KHR_materials_sheen/sheenColorFactor",[new fa(t.Animation.ANIMATIONTYPE_COLOR3,"sheen.color",ra,()=>3)]),Rs("/materials/{}/extensions/KHR_materials_sheen/sheenRoughnessFactor",[new fa(t.Animation.ANIMATIONTYPE_FLOAT,"sheen.roughness",aa,()=>1)]);const h=da("sheen.texture");Rs("/materials/{}/extensions/KHR_materials_sheen/sheenColorTexture/extensions/KHR_texture_transform/scale",h.scale),Rs("/materials/{}/extensions/KHR_materials_sheen/sheenColorTexture/extensions/KHR_texture_transform/offset",h.offset),Rs("/materials/{}/extensions/KHR_materials_sheen/sheenColorTexture/extensions/KHR_texture_transform/rotation",h.rotation);const f=da("sheen.textureRoughness");Rs("/materials/{}/extensions/KHR_materials_sheen/sheenRoughnessTexture/extensions/KHR_texture_transform/scale",f.scale),Rs("/materials/{}/extensions/KHR_materials_sheen/sheenRoughnessTexture/extensions/KHR_texture_transform/offset",f.offset),Rs("/materials/{}/extensions/KHR_materials_sheen/sheenRoughnessTexture/extensions/KHR_texture_transform/rotation",f.rotation),Rs("/materials/{}/extensions/KHR_materials_specular/specularFactor",[new fa(t.Animation.ANIMATIONTYPE_FLOAT,"metallicF0Factor",aa,()=>1)]),Rs("/materials/{}/extensions/KHR_materials_specular/specularColorFactor",[new fa(t.Animation.ANIMATIONTYPE_COLOR3,"metallicReflectanceColor",ra,()=>3)]);const m=da("metallicReflectanceTexture");Rs("/materials/{}/extensions/KHR_materials_specular/specularTexture/extensions/KHR_texture_transform/scale",m.scale),Rs("/materials/{}/extensions/KHR_materials_specular/specularTexture/extensions/KHR_texture_transform/offset",m.offset),Rs("/materials/{}/extensions/KHR_materials_specular/specularTexture/extensions/KHR_texture_transform/rotation",m.rotation);const p=da("reflectanceTexture");Rs("/materials/{}/extensions/KHR_materials_specular/specularColorTexture/extensions/KHR_texture_transform/scale",p.scale),Rs("/materials/{}/extensions/KHR_materials_specular/specularColorTexture/extensions/KHR_texture_transform/offset",p.offset),Rs("/materials/{}/extensions/KHR_materials_specular/specularColorTexture/extensions/KHR_texture_transform/rotation",p.rotation),Rs("/materials/{}/extensions/KHR_materials_transmission/transmissionFactor",[new fa(t.Animation.ANIMATIONTYPE_FLOAT,"subSurface.refractionIntensity",aa,()=>1)]);const _=da("subSurface.refractionIntensityTexture");Rs("/materials/{}/extensions/KHR_materials_transmission/transmissionTexture/extensions/KHR_texture_transform/scale",_.scale),Rs("/materials/{}/extensions/KHR_materials_transmission/transmissionTexture/extensions/KHR_texture_transform/offset",_.offset),Rs("/materials/{}/extensions/KHR_materials_transmission/transmissionTexture/extensions/KHR_texture_transform/rotation",_.rotation),Rs("/materials/{}/extensions/KHR_materials_volume/attenuationColor",[new fa(t.Animation.ANIMATIONTYPE_COLOR3,"subSurface.tintColor",ra,()=>3)]),Rs("/materials/{}/extensions/KHR_materials_volume/attenuationDistance",[new fa(t.Animation.ANIMATIONTYPE_FLOAT,"subSurface.tintColorAtDistance",aa,()=>1)]),Rs("/materials/{}/extensions/KHR_materials_volume/thicknessFactor",[new fa(t.Animation.ANIMATIONTYPE_FLOAT,"subSurface.maximumThickness",aa,()=>1)]);const g=da("subSurface.thicknessTexture");Rs("/materials/{}/extensions/KHR_materials_volume/thicknessTexture/extensions/KHR_texture_transform/scale",g.scale),Rs("/materials/{}/extensions/KHR_materials_volume/thicknessTexture/extensions/KHR_texture_transform/offset",g.offset),Rs("/materials/{}/extensions/KHR_materials_volume/thicknessTexture/extensions/KHR_texture_transform/rotation",g.rotation),Rs("/materials/{}/extensions/KHR_materials_diffuse_transmission/diffuseTransmissionFactor",[new fa(t.Animation.ANIMATIONTYPE_FLOAT,"subSurface.translucencyIntensity",aa,()=>1)]);const v=da("subSurface.translucencyIntensityTexture");Rs("materials/{}/extensions/KHR_materials_diffuse_transmission/diffuseTransmissionTexture/extensions/KHR_texture_transform/scale",v.scale),Rs("materials/{}/extensions/KHR_materials_diffuse_transmission/diffuseTransmissionTexture/extensions/KHR_texture_transform/offset",v.offset),Rs("materials/{}/extensions/KHR_materials_diffuse_transmission/diffuseTransmissionTexture/extensions/KHR_texture_transform/rotation",v.rotation),Rs("/materials/{}/extensions/KHR_materials_diffuse_transmission/diffuseTransmissionColorFactor",[new fa(t.Animation.ANIMATIONTYPE_COLOR3,"subSurface.translucencyColor",ra,()=>3)]);const y=da("subSurface.translucencyColorTexture");Rs("materials/{}/extensions/KHR_materials_diffuse_transmission/diffuseTransmissionColorTexture/extensions/KHR_texture_transform/scale",y.scale),Rs("materials/{}/extensions/KHR_materials_diffuse_transmission/diffuseTransmissionColorTexture/extensions/KHR_texture_transform/offset",y.offset),Rs("materials/{}/extensions/KHR_materials_diffuse_transmission/diffuseTransmissionColorTexture/extensions/KHR_texture_transform/rotation",y.rotation),Rs("/extensions/KHR_lights_punctual/lights/{}/color",[new ma(t.Animation.ANIMATIONTYPE_COLOR3,"diffuse",ra,()=>3)]),Rs("/extensions/KHR_lights_punctual/lights/{}/intensity",[new ma(t.Animation.ANIMATIONTYPE_FLOAT,"intensity",aa,()=>1)]),Rs("/extensions/KHR_lights_punctual/lights/{}/range",[new ma(t.Animation.ANIMATIONTYPE_FLOAT,"range",aa,()=>1)]),Rs("/extensions/KHR_lights_punctual/lights/{}/spot/innerConeAngle",[new ma(t.Animation.ANIMATIONTYPE_FLOAT,"innerAngle",ca,()=>1)]),Rs("/extensions/KHR_lights_punctual/lights/{}/spot/outerConeAngle",[new ma(t.Animation.ANIMATIONTYPE_FLOAT,"angle",ca,()=>1)]),Rs("/extensions/EXT_lights_area/lights/{}/color",[new ma(t.Animation.ANIMATIONTYPE_COLOR3,"diffuse",ra,()=>3)]),Rs("/extensions/EXT_lights_area/lights/{}/intensity",[new ma(t.Animation.ANIMATIONTYPE_FLOAT,"intensity",aa,()=>1)]),Rs("/extensions/EXT_lights_area/lights/{}/size",[new ma(t.Animation.ANIMATIONTYPE_FLOAT,"radius",aa,()=>1)]),Rs("/extensions/EXT_lights_area/lights/{}/rect/aspect",[new ma(t.Animation.ANIMATIONTYPE_FLOAT,"radius",aa,()=>1)]),Rs("/nodes/{}/extensions/EXT_lights_ies/color",[new ma(t.Animation.ANIMATIONTYPE_COLOR3,"diffuse",ra,()=>3)]),Rs("/nodes/{}/extensions/EXT_lights_ies/multiplier",[new ma(t.Animation.ANIMATIONTYPE_FLOAT,"intensity",aa,()=>1)]),Rs("/nodes/{}/extensions/KHR_node_visibility/visible",[new pa(t.Animation.ANIMATIONTYPE_FLOAT,"isVisible",aa,()=>1)])}var va={__proto__:null,_RegisterKHRAnimationPointerData:ga};ga(),sa();const ya="MSFT_audio_emitter";class ba{constructor(e){this.name=ya,this._loader=e,this.enabled=this._loader.isExtensionUsed(ya)}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,Es.Assign(this._clips),Es.Assign(this._emitters)}}loadSceneAsync(e,t){return Is.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=Es.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 Is.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=Es.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 Is.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;Es.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=Es.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=Es.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=Es.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()})}})}}let xa=!1;function Ta(){xa||(xa=!0,ds(ya),cs(ya,!0,e=>new ba(e)))}var Aa={__proto__:null,MSFT_audio_emitter:ba,RegisterMSFT_audio_emitter:Ta};Ta();const Ma="MSFT_lod";class wa{constructor(e){var n,s;this.name=Ma,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[Ma])||void 0===n?void 0:n.maxLODsToLoad)&&void 0!==s?s:this.maxLODsToLoad,this.enabled=this._loader.isExtensionUsed(Ma)}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 Is.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:Is.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(Es.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()}}let Ca=!1;function Ra(){Ca||(Ca=!0,ds(Ma),cs(Ma,!0,e=>new wa(e)))}var Sa={__proto__:null,MSFT_lod:wa,RegisterMSFT_lod:Ra};Ra();const Oa="MSFT_minecraftMesh";class Fa{constructor(e){this.name=Oa,this._loader=e,this.enabled=this._loader.isExtensionUsed(Oa)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return Is.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}}))}}let Ea=!1;function La(){Ea||(Ea=!0,ds(Oa),cs(Oa,!0,e=>new Fa(e)))}var Ia={__proto__:null,MSFT_minecraftMesh:Fa,RegisterMSFT_minecraftMesh:La};La();const Ba="MSFT_sRGBFactors";class Na{constructor(e){this.name=Ba,this._loader=e,this.enabled=this._loader.isExtensionUsed(Ba)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return Is.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}}))}}let Pa=!1;function ka(){Pa||(Pa=!0,ds(Ba),cs(Ba,!0,e=>new Na(e)))}var Da={__proto__:null,MSFT_sRGBFactors:Na,RegisterMSFT_sRGBFactors:ka};function Ga(e){const[t,n]=e.split(":");return Va({op:t,extension:n})}function Va(e,n=!0){var s;const o=e.extension?null===(s=Ua[e.extension])||void 0===s?void 0:s[e.op]:Ka[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 Ha(e,t,n){Ua[t]||(Ua[t]={}),Ua[t][e]=n}ka();const Ua={BABYLON:{"flow/log":{blocks:["FlowGraphConsoleLogBlock"],inputs:{values:{message:{name:"message"}}}}}},Ka={"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":$a("FlowGraphEBlock"),"math/Pi":$a("FlowGraphPIBlock"),"math/Tau":$a("FlowGraphTauBlock"),"math/Inf":$a("FlowGraphInfBlock"),"math/NaN":$a("FlowGraphNaNBlock"),"math/abs":$a("FlowGraphAbsBlock"),"math/sign":$a("FlowGraphSignBlock"),"math/trunc":$a("FlowGraphTruncBlock"),"math/floor":$a("FlowGraphFloorBlock"),"math/ceil":$a("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":$a("FlowGraphFractBlock"),"math/neg":$a("FlowGraphNegationBlock"),"math/add":$a("FlowGraphAddBlock",["a","b"],!0),"math/sub":$a("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?qa(e):{valid:!0}},"math/div":$a("FlowGraphDivideBlock",["a","b"],!0),"math/rem":$a("FlowGraphModuloBlock",["a","b"]),"math/min":$a("FlowGraphMinBlock",["a","b"]),"math/max":$a("FlowGraphMaxBlock",["a","b"]),"math/clamp":$a("FlowGraphClampBlock",["a","b","c"]),"math/saturate":$a("FlowGraphSaturateBlock"),"math/mix":$a("FlowGraphMathInterpolationBlock",["a","b","c"]),"math/smoothStep":$a("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":$a("FlowGraphMathSlerpBlock",["a","b","c"]),"math/slerp":$a("FlowGraphVectorSlerpBlock",["a","b","c"]),"math/eq":$a("FlowGraphEqualityBlock",["a","b"]),"ref/eq":$a("FlowGraphEqualityBlock",["a","b"]),"math/lt":$a("FlowGraphLessThanBlock",["a","b"]),"math/le":$a("FlowGraphLessThanOrEqualBlock",["a","b"]),"math/gt":$a("FlowGraphGreaterThanBlock",["a","b"]),"math/ge":$a("FlowGraphGreaterThanOrEqualBlock",["a","b"]),"math/isNaN":$a("FlowGraphIsNaNBlock"),"math/isInf":$a("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":$a("FlowGraphSinBlock"),"math/cos":$a("FlowGraphCosBlock"),"math/tan":$a("FlowGraphTanBlock"),"math/asin":$a("FlowGraphASinBlock"),"math/acos":$a("FlowGraphACosBlock"),"math/atan":$a("FlowGraphATanBlock"),"math/atan2":$a("FlowGraphATan2Block",["a","b"]),"math/sinh":$a("FlowGraphSinhBlock"),"math/cosh":$a("FlowGraphCoshBlock"),"math/tanh":$a("FlowGraphTanhBlock"),"math/asinh":$a("FlowGraphASinhBlock"),"math/acosh":$a("FlowGraphACoshBlock"),"math/atanh":$a("FlowGraphATanhBlock"),"math/exp":$a("FlowGraphExponentialBlock"),"math/log":$a("FlowGraphLogBlock"),"math/log2":$a("FlowGraphLog2Block"),"math/log10":$a("FlowGraphLog10Block"),"math/sqrt":$a("FlowGraphSquareRootBlock"),"math/cbrt":$a("FlowGraphCubeRootBlock"),"math/pow":$a("FlowGraphPowerBlock",["a","b"]),"math/length":$a("FlowGraphLengthBlock"),"math/normalize":$a("FlowGraphNormalizeBlock"),"math/dot":$a("FlowGraphDotBlock",["a","b"]),"math/cross":$a("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":$a("FlowGraphTransposeBlock"),"math/determinant":$a("FlowGraphDeterminantBlock"),"math/inverse":$a("FlowGraphInvertMatrixBlock"),"math/matMul":$a("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":$a("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":$a("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":$a("FlowGraphAxisAngleFromQuaternionBlock",["a"]),"math/quatFromDirections":$a("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":$a("FlowGraphBitwiseRightShiftBlock",["a","b"]),"math/lsl":$a("FlowGraphBitwiseLeftShiftBlock",["a","b"]),"math/clz":$a("FlowGraphLeadingZerosBlock"),"math/ctz":$a("FlowGraphTrailingZerosBlock"),"math/popcnt":$a("FlowGraphOneBitsCounterBlock"),"math/rad":$a("FlowGraphDegToRadBlock"),"math/deg":$a("FlowGraphRadToDegBlock"),"type/boolToInt":$a("FlowGraphBooleanToInt"),"type/boolToFloat":$a("FlowGraphBooleanToFloat"),"type/intToBool":$a("FlowGraphIntToBoolean"),"type/intToFloat":$a("FlowGraphIntToFloat"),"type/floatToInt":$a("FlowGraphFloatToInt"),"type/floatToBool":$a("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],f=null===(a=null===(i=e.configuration)||void 0===i?void 0:i.variable.value)||void 0===a?void 0:a[0];if("number"!=typeof f)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 m=o.arrays.staticVariables[f];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(m.type));const p=r[4];return p.config||(p.config={}),(d=p.config).variable||(d.variable={}),p.config.variable.value=o.getVariableName(f),r}},"pointer/get":{blocks:["FlowGraphGetPropertyBlock","FlowGraphJsonPointerParserBlock"],validation:za,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:za,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:za,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 $a(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?qa(e):{valid:!0}}}function qa(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 Wa(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 za(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(Wa(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 ja(){return Object.keys(Ka)}const Xa={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 Ya{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(Xa[e.signature])}_parseDeclarations(){if(this._interactivityGraph.declarations)for(const e of this._interactivityGraph.declarations){const n=Va(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,f,m,p,_,g,v,y,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,f=this._nodes[h];if(!f)throw t.Logger.Error(["No node found for input node id",h]),new Error("Error parsing node connections");if(0===f.blocks.length){t.Logger.Warn(`Dropping flow connection from node #${x} "${e}" to no-op node #${h} (unsupported operation: ${f.fullOperationName})`);continue}const m=this._createNewSocketConnection(d,!0);(c&&c.toBlock&&A.blocks.find(e=>e.className===c.toBlock)||A.blocks[0]).signalOutputs.push(m);const p=Ga(f.fullOperationName);if(!p)throw t.Logger.Error(["No mapping found for input node",f]),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 v=_?g?_.name.replace("$1",n.socket||""):_.name:n.socket||"in",y=_&&_.toBlock&&f.blocks.find(e=>e.className===_.toBlock)||f.blocks[0];let b=y.signalInputs.find(e=>e.name===v);b||(b=this._createNewSocketConnection(v),y.signalInputs.push(b)),b.connectedPointIds.push(m.uniqueId),m.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===(m=null===(f=M.flowGraphMapping.inputs)||void 0===f?void 0:f.values)||void 0===m?void 0:m[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=Ga(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===(y=null===(v=u.outputs)||void 0===v?void 0:v.values)||void 0===y?void 0:y[e]);const h=c?d?c.name.replace("$1",r):null==c?void 0:c.name:r,f=c&&c.toBlock&&i.blocks.find(e=>e.className===c.toBlock)||i.blocks[0];let m=f.dataOutputs.find(e=>e.name===h);m||(m=this._createNewSocketConnection(h,!0),f.dataOutputs.push(m)),l?this._connectWithSecondsToFramesConversion(e,m,a):(a.connectedPointIds.push(m.uniqueId),m.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 Qa{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 Za="/extensions/BABYLON_scene_objects/";class Ja{constructor(e,t){this._scene=e,this._tree=t}convert(e){if(!e.startsWith(Za))throw new Error(`BabylonScenePathToObjectConverter: path "${e}" does not start with the expected prefix "${Za}".`);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 el="/extensions/KHR_interactivity/events/";const tl={isKhrInteractivityRef:!0};class nl{convert(e){const n=e.endsWith("/")?e.slice(0,-1):e;if(n.startsWith(el)){const e=n.substring(37);return{object:tl,info:{type:"object",isReadOnly:!0,get:()=>e.length>0?n:void 0,getTarget:()=>tl}}}const s=n.substring(37),o=/^\d+$/.test(s)?parseInt(s,10):NaN;return{object:tl,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:()=>tl}}}}const sl="/extensions/KHR_interactivity/limits/",ol={major:2,minor:0},rl=2147483647,il={maxActiveAnimations:rl,maxActiveDelays:rl,maxActivePropertyInterpolations:rl,maxActiveVariableInterpolations:rl},al={isKhrInteractivityAssetCapability:!0};class ll{constructor(e,t){this._gltf=e,this._isExtensionEnabled=t}convert(e){const t=e.endsWith("/")?e.slice(0,-1):e;if(t.startsWith(sl)){const n=il[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)?ol:s!==ol.major?s<ol.major?{major:s,minor:isNaN(o)?0:o}:ol:{major:s,minor:Math.min(isNaN(o)?0:o,ol.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:al,info:{type:e,isReadOnly:!0,get:t,getTarget:()=>al}}}}class ul{encodeEventReference(e){return function(e){return el+e}(e)}decodeEventReference(e){return function(e){return"string"==typeof(t=e)&&t.startsWith(el)?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 cl="KHR_interactivity";class dl{constructor(e){var n;this._loader=e,this.name=cl,this.enabled=this._loader.isExtensionUsed(cl),this._gltfPathConverter=ws(this._loader.gltf);const s=e.babylonScene;if(this._gltfPathConverter){const e=[];s&&e.push({prefix:Za,converter:new Ja(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 nl;e.push({prefix:el,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 us.has(e)&&!1!==(null===(t=this._loader.parent.extensionOptions[e])||void 0===t?void 0:t.enabled)})),i=new ll(this._loader.gltf,e=>r.has(e));e.push({prefix:"/extensions/KHR_interactivity/asset/",converter:i}),e.push({prefix:sl,converter:i}),this._pathConverter=new Qa(e,this._gltfPathConverter)}e._skipStartAnimationStep=!0,s&&hl(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 ul});r.dispatchEventsSynchronously=!1;try{const n=new Ya(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 hl(e){Ss("/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}),Ss("/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};Ss("/extensions/KHR_interactivity/?/activeCamera/perspective/aspectRatio",{get:()=>n(e=>e.getEngine().getAspectRatio(e)),type:"number",getTarget:()=>e.activeCamera}),Ss("/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}),Ss("/extensions/KHR_interactivity/?/activeCamera/perspective/znear",{get:()=>n(e=>e.minZ),type:"number",getTarget:()=>e.activeCamera}),Ss("/extensions/KHR_interactivity/?/activeCamera/perspective/zfar",{get:()=>n(e=>0===e.maxZ?1/0:e.maxZ),type:"number",getTarget:()=>e.activeCamera}),Ss("/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}),Ss("/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}),Ss("/extensions/KHR_interactivity/?/activeCamera/orthographic/znear",{get:()=>s(e=>e.minZ),type:"number",getTarget:()=>e.activeCamera}),Ss("/extensions/KHR_interactivity/?/activeCamera/orthographic/zfar",{get:()=>s(e=>e.maxZ),type:"number",getTarget:()=>e.activeCamera}),Ss("/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}),Ss("/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}),Ss("/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}),Ss("/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}),Ss("/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 fl=!1;function ml(){fl||(fl=!0,t.addToBlockFactory(cl,"FlowGraphGLTFDataProvider",()=>b(this,void 0,void 0,function*(){return(yield Promise.resolve().then(function(){return zl})).FlowGraphGLTFDataProvider})))}let pl=!1;function _l(){pl||(pl=!0,ml(),ds(cl),cs(cl,!0,e=>new dl(e)))}var gl={__proto__:null,KHR_interactivity:dl,RegisterKHR_interactivity:_l,_AddInteractivityObjectModel:hl,_RegisterKHRInteractivityRuntime:ml};_l();const vl="KHR_node_visibility";class yl{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}}let bl=!1;function xl(){bl||(bl=!0,Ss("/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"}))}let Tl=!1;function Al(){Tl||(Tl=!0,xl(),ds(vl),cs(vl,!0,e=>new yl(e)))}var Ml={__proto__:null,KHR_node_visibility:yl,RegisterKHR_node_visibility:Al,_RegisterKHRNodeVisibilityRuntime:xl};Al();const wl="KHR_node_selectability";class Cl{constructor(e){this.name=wl,this._loader=e,this.enabled=e.isExtensionUsed(wl)}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}}let Rl=!1;function Sl(){Rl||(Rl=!0,Ha("event/onSelect",wl,{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,f;const m=o[o.length-1];m.config=m.config||{},m.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===(f=null===(h=null==i?void 0:i.nodes)||void 0===h?void 0:h[p]._babylonTransformNode)||void 0===f?void 0:f.uniqueId},o}}),Ss("/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"}))}let Ol=!1;function Fl(){Ol||(Ol=!0,Sl(),ds(wl),cs(wl,!0,e=>new Cl(e)))}var El={__proto__:null,KHR_node_selectability:Cl,RegisterKHR_node_selectability:Fl,_RegisterKHRNodeSelectabilityRuntime:Sl};Fl();const Ll="KHR_node_hoverability",Il="targetMeshPointerOver_",Bl="targetMeshPointerOut_";class Nl{constructor(e){this.name=Ll,this._loader=e,this.enabled=e.isExtensionUsed(Ll)}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}}let Pl=!1;function kl(){Pl||(Pl=!0,Ha("event/onHoverIn",Ll,{blocks:["FlowGraphPointerOverEventBlock","FlowGraphGetVariableBlock","FlowGraphIndexOfBlock","KHR_interactivity/FlowGraphGLTFDataProvider"],configuration:{stopPropagation:{name:"stopPropagation"},nodeIndex:{name:"variable",toBlock:"FlowGraphGetVariableBlock",dataTransformer:e=>Il+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,f;const m=o[o.length-1];m.config=m.config||{},m.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 _=Il+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===(f=null===(h=null==i?void 0:i.nodes)||void 0===h?void 0:h[p]._babylonTransformNode)||void 0===f?void 0:f.uniqueId},o}}),Ha("event/onHoverOut",Ll,{blocks:["FlowGraphPointerOutEventBlock","FlowGraphGetVariableBlock","FlowGraphIndexOfBlock","KHR_interactivity/FlowGraphGLTFDataProvider"],configuration:{stopPropagation:{name:"stopPropagation"},nodeIndex:{name:"variable",toBlock:"FlowGraphGetVariableBlock",dataTransformer:e=>Bl+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,f;const m=o[o.length-1];m.config=m.config||{},m.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 _=Bl+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===(f=null===(h=null==i?void 0:i.nodes)||void 0===h?void 0:h[p]._babylonTransformNode)||void 0===f?void 0:f.uniqueId},o}}),Ss("/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"}))}let Dl=!1;function Gl(){Dl||(Dl=!0,kl(),ds(Ll),cs(Ll,!0,e=>new Nl(e)))}var Vl={__proto__:null,KHR_node_hoverability:Nl,RegisterKHR_node_hoverability:Gl,_RegisterKHRNodeHoverabilityRuntime:kl};Gl();const Hl="ExtrasAsMetadata";class Ul{_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=Hl,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))}}let Kl=!1;function $l(){Kl||(Kl=!0,ds(Hl),cs(Hl,!1,e=>new Ul(e)))}var ql={__proto__:null,ExtrasAsMetadata:Ul,RegisterExtrasAsMetadata:$l};$l();class Wl 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 zl={__proto__:null,FlowGraphGLTFDataProvider:Wl},jl={__proto__:null,AddObjectAccessorToKey:Ss,EXT_lights_area:Wo,EXT_lights_ies:Ao,EXT_lights_image_based:Qs,EXT_mesh_gpu_instancing:no,EXT_meshopt_compression:ao,EXT_texture_avif:vo,EXT_texture_webp:fo,ExtrasAsMetadata:Ul,FlowGraphGLTFDataProvider:Wl,GetMappingForKey:Cs,GetPathToObjectConverter:ws,InteractivityGraphToFlowGraphParser:Ya,KHR_animation_pointer:ta,KHR_draco_mesh_compression:So,KHR_gaussian_splatting:Po,KHR_interactivity:dl,KHR_lights:Ho,KHR_materials_anisotropy:Tr,KHR_materials_clearcoat:ar,KHR_materials_coat:hr,KHR_materials_diffuse_roughness:Fi,KHR_materials_diffuse_transmission:ci,KHR_materials_dispersion:wi,KHR_materials_emissive_strength:Rr,KHR_materials_fuzz:kr,KHR_materials_ior:zr,KHR_materials_iridescence:gr,KHR_materials_pbrSpecularGlossiness:Qo,KHR_materials_sheen:Lr,KHR_materials_specular:Ur,KHR_materials_transmission:ri,KHR_materials_unlit:nr,KHR_materials_variants:Zr,KHR_materials_volume:pi,KHR_materials_volume_scatter:bi,KHR_mesh_quantization:Ni,KHR_node_hoverability:Nl,KHR_node_selectability:Cl,KHR_node_visibility:yl,KHR_texture_basisu:Vi,KHR_texture_transform:qi,KHR_xmp_json_ld:Yi,MSFT_audio_emitter:ba,MSFT_lod:wa,MSFT_minecraftMesh:Fa,MSFT_sRGBFactors:Na,RegisterEXT_lights_area:jo,RegisterEXT_lights_ies:wo,RegisterEXT_lights_image_based:Js,RegisterEXT_mesh_gpu_instancing:oo,RegisterEXT_meshopt_compression:uo,RegisterEXT_texture_avif:bo,RegisterEXT_texture_webp:po,RegisterExtrasAsMetadata:$l,RegisterKHR_animation_pointer:sa,RegisterKHR_draco_mesh_compression:Fo,RegisterKHR_gaussian_splatting:Do,RegisterKHR_interactivity:_l,RegisterKHR_lights:Ko,RegisterKHR_materials_anisotropy:Mr,RegisterKHR_materials_clearcoat:ur,RegisterKHR_materials_coat:mr,RegisterKHR_materials_diffuse_roughness:Li,RegisterKHR_materials_diffuse_transmission:hi,RegisterKHR_materials_dispersion:Ri,RegisterKHR_materials_emissive_strength:Or,RegisterKHR_materials_fuzz:Gr,RegisterKHR_materials_ior:Xr,RegisterKHR_materials_iridescence:yr,RegisterKHR_materials_pbrSpecularGlossiness:Jo,RegisterKHR_materials_sheen:Br,RegisterKHR_materials_specular:$r,RegisterKHR_materials_transmission:ai,RegisterKHR_materials_unlit:or,RegisterKHR_materials_variants:ei,RegisterKHR_materials_volume:gi,RegisterKHR_materials_volume_scatter:Ti,RegisterKHR_mesh_quantization:ki,RegisterKHR_node_hoverability:Gl,RegisterKHR_node_selectability:Fl,RegisterKHR_node_visibility:Al,RegisterKHR_texture_basisu:Ui,RegisterKHR_texture_transform:zi,RegisterKHR_xmp_json_ld:Zi,RegisterMSFT_audio_emitter:Ta,RegisterMSFT_lod:Ra,RegisterMSFT_minecraftMesh:La,RegisterMSFT_sRGBFactors:ka,SetInterpolationForKey:Rs,TransmissionHelper:ni,_AddInteractivityObjectModel:hl,_RegisterKHRInteractivityRuntime:ml,_RegisterKHRNodeHoverabilityRuntime:kl,_RegisterKHRNodeSelectabilityRuntime:Sl,_RegisterKHRNodeVisibilityRuntime:xl,addNewInteractivityFlowGraphMapping:Ha,ensureTransmissionHelper:si,getAllSupportedNativeNodeTypes:ja,getMappingForDeclaration:Va,getMappingForFullOperationName:Ga,gltfTypeToBabylonType:Xa},Xl={__proto__:null,AddObjectAccessorToKey:Ss,AnimationPropertyInfo:Vs,ArrayItem:Es,EXT_lights_area:Wo,EXT_lights_ies:Ao,EXT_lights_image_based:Qs,EXT_mesh_gpu_instancing:no,EXT_meshopt_compression:ao,EXT_texture_avif:vo,EXT_texture_webp:fo,ExtrasAsMetadata:Ul,FlowGraphGLTFDataProvider:Wl,GLTFFileLoader:_n,GLTFLoader:Is,GetMappingForKey:Cs,GetPathToObjectConverter:ws,InteractivityGraphToFlowGraphParser:Ya,KHR_animation_pointer:ta,KHR_draco_mesh_compression:So,KHR_gaussian_splatting:Po,KHR_interactivity:dl,KHR_lights:Ho,KHR_materials_anisotropy:Tr,KHR_materials_clearcoat:ar,KHR_materials_coat:hr,KHR_materials_diffuse_roughness:Fi,KHR_materials_diffuse_transmission:ci,KHR_materials_dispersion:wi,KHR_materials_emissive_strength:Rr,KHR_materials_fuzz:kr,KHR_materials_ior:zr,KHR_materials_iridescence:gr,KHR_materials_pbrSpecularGlossiness:Qo,KHR_materials_sheen:Lr,KHR_materials_specular:Ur,KHR_materials_transmission:ri,KHR_materials_unlit:nr,KHR_materials_variants:Zr,KHR_materials_volume:pi,KHR_materials_volume_scatter:bi,KHR_mesh_quantization:Ni,KHR_node_hoverability:Nl,KHR_node_selectability:Cl,KHR_node_visibility:yl,KHR_texture_basisu:Vi,KHR_texture_transform:qi,KHR_xmp_json_ld:Yi,LoadBoundingInfoFromPositionAccessor:Ls,MSFT_audio_emitter:ba,MSFT_lod:wa,MSFT_minecraftMesh:Fa,MSFT_sRGBFactors:Na,OpenPBRMaterialLoadingAdapter:Ws,PBRMaterialLoadingAdapter:js,RegisterEXT_lights_area:jo,RegisterEXT_lights_ies:wo,RegisterEXT_lights_image_based:Js,RegisterEXT_mesh_gpu_instancing:oo,RegisterEXT_meshopt_compression:uo,RegisterEXT_texture_avif:bo,RegisterEXT_texture_webp:po,RegisterExtrasAsMetadata:$l,RegisterGLTF2Loader:Ns,RegisterGLTFLoaderAnimation:$s,RegisterKHR_animation_pointer:sa,RegisterKHR_draco_mesh_compression:Fo,RegisterKHR_gaussian_splatting:Do,RegisterKHR_interactivity:_l,RegisterKHR_lights:Ko,RegisterKHR_materials_anisotropy:Mr,RegisterKHR_materials_clearcoat:ur,RegisterKHR_materials_coat:mr,RegisterKHR_materials_diffuse_roughness:Li,RegisterKHR_materials_diffuse_transmission:hi,RegisterKHR_materials_dispersion:Ri,RegisterKHR_materials_emissive_strength:Or,RegisterKHR_materials_fuzz:Gr,RegisterKHR_materials_ior:Xr,RegisterKHR_materials_iridescence:yr,RegisterKHR_materials_pbrSpecularGlossiness:Jo,RegisterKHR_materials_sheen:Br,RegisterKHR_materials_specular:$r,RegisterKHR_materials_transmission:ai,RegisterKHR_materials_unlit:or,RegisterKHR_materials_variants:ei,RegisterKHR_materials_volume:gi,RegisterKHR_materials_volume_scatter:Ti,RegisterKHR_mesh_quantization:ki,RegisterKHR_node_hoverability:Gl,RegisterKHR_node_selectability:Fl,RegisterKHR_node_visibility:Al,RegisterKHR_texture_basisu:Ui,RegisterKHR_texture_transform:zi,RegisterKHR_xmp_json_ld:Zi,RegisterMSFT_audio_emitter:Ta,RegisterMSFT_lod:Ra,RegisterMSFT_minecraftMesh:La,RegisterMSFT_sRGBFactors:ka,SetInterpolationForKey:Rs,TransformNodeAnimationPropertyInfo:Hs,TransmissionHelper:ni,WeightAnimationPropertyInfo:Us,_AddInteractivityObjectModel:hl,_RegisterKHRInteractivityRuntime:ml,_RegisterKHRNodeHoverabilityRuntime:kl,_RegisterKHRNodeSelectabilityRuntime:Sl,_RegisterKHRNodeVisibilityRuntime:xl,addNewInteractivityFlowGraphMapping:Ha,ensureTransmissionHelper:si,getAllSupportedNativeNodeTypes:ja,getMappingForDeclaration:Va,getMappingForFullOperationName:Ga,getQuaternion:Ds,getVector3:ks,getWeights:Gs,gltfTypeToBabylonType:Xa,registerGLTFExtension:cs,registeredGLTFExtensions:us,unregisterGLTFExtension:ds};class Yl{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=Yl._GetTexture(s,h,e);else if("map_kd"===d&&l)l.diffuseTexture=Yl._GetTexture(s,h,e);else if("map_ks"===d&&l)l.specularTexture=Yl._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=Yl._GetTexture(s,t.join(" "),e),l.bumpTexture&&null!==o&&(l.bumpTexture.level=parseFloat(o))}else"map_d"===d&&l&&(l.opacityTexture=Yl._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,Yl.INVERT_TEXTURE_Y)}}Yl.INVERT_TEXTURE_Y=!0;class Ql{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 f=[];h.push(f);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((Ql._IsGroupElement(t)||Ql._IsObjectElement(t))&&(f=[],h.push(f)),Ql._IsLineElement(t)){const e=t.split(" ");for(let t=1;t<e.length-1;t++)f.push(`l ${e[t]} ${e[t+1]}`)}else f.push(t)}const m=h.flat();for(let e=0;e<m.length;e++){const n=m[e].trim().replace(/\s\s/g," ");let s;if(0!==n.length&&"#"!==n.charAt(0))if(Ql.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=Ql.NormalPattern.exec(n)))this._normals.push(new t.Vector3(parseFloat(s[1]),parseFloat(s[2]),parseFloat(s[3])));else if(null!==(s=Ql.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=Ql.FacePattern3.exec(n)))this._setDataForCurrentFaceWithPattern3(s[1].trim().split(" "),1);else if(null!==(s=Ql.FacePattern4.exec(n)))this._setDataForCurrentFaceWithPattern4(s[1].trim().split(" "),1);else if(null!==(s=Ql.FacePattern5.exec(n)))this._setDataForCurrentFaceWithPattern5(s[1].trim().split(" "),1);else if(null!==(s=Ql.FacePattern2.exec(n)))this._setDataForCurrentFaceWithPattern2(s[1].trim().split(" "),1);else if(null!==(s=Ql.FacePattern1.exec(n)))this._setDataForCurrentFaceWithPattern1(s[1].trim().split(" "),1);else if(null!==(s=Ql.LinePattern1.exec(n)))this._setDataForCurrentFaceWithPattern1(s[1].trim().split(" "),0),this._hasLineData=!0;else if(null!==(s=Ql.LinePattern2.exec(n)))this._setDataForCurrentFaceWithPattern2(s[1].trim().split(" "),0),this._hasLineData=!0;else if(s=Ql._GetZbrushMRGB(n,!this._loadingOptions.importVertexColors))for(const e of s)this._extColors.push(e);else if(null!==(s=Ql.LinePattern3.exec(n)))this._setDataForCurrentFaceWithPattern3(s[1].trim().split(" "),0),this._hasLineData=!0;else if(Ql.GroupDescriptor.test(n)||Ql.ObjectDescriptor.test(n)){const e={name:n.substring(2).trim(),indices:null,positions:null,normals:null,uvs:null,colors:null,materialName:this._materialNameFromObj,isObject:Ql.ObjectDescriptor.test(n)};this._addPreviousObjMesh(),this._meshesFromObj.push(e),this._hasMeshes=!0,this._isFirstMaterial=!0,this._increment=1}else if(Ql.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 Ql.MtlLibGroupDescriptor.test(n)?r(n.substring(7).trim()):Ql.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)}}}Ql.ObjectDescriptor=/^o/,Ql.GroupDescriptor=/^g/,Ql.MtlLibGroupDescriptor=/^mtllib /,Ql.UseMtlDescriptor=/^usemtl /,Ql.SmoothDescriptor=/^s /,Ql.VertexPattern=/^v(\s+[\d|.|+|\-|e|E]+){3,7}/,Ql.NormalPattern=/^vn(\s+[\d|.|+|\-|e|E]+)( +[\d|.|+|\-|e|E]+)( +[\d|.|+|\-|e|E]+)/,Ql.UVPattern=/^vt(\s+[\d|.|+|\-|e|E]+)( +[\d|.|+|\-|e|E]+)/,Ql.FacePattern1=/^f\s+(([\d]{1,}[\s]?){3,})+/,Ql.FacePattern2=/^f\s+((([\d]{1,}\/[\d]{1,}[\s]?){3,})+)/,Ql.FacePattern3=/^f\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){3,})+)/,Ql.FacePattern4=/^f\s+((([\d]{1,}\/\/[\d]{1,}[\s]?){3,})+)/,Ql.FacePattern5=/^f\s+(((-[\d]{1,}\/-[\d]{1,}\/-[\d]{1,}[\s]?){3,})+)/,Ql.LinePattern1=/^l\s+(([\d]{1,}[\s]?){2,})+/,Ql.LinePattern2=/^l\s+((([\d]{1,}\/[\d]{1,}[\s]?){2,})+)/,Ql.LinePattern3=/^l\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){2,})+)/;const Zl={name:"obj",extensions:{".obj":{isBinary:!0}}};class Jl{static get INVERT_TEXTURE_Y(){return Yl.INVERT_TEXTURE_Y}static set INVERT_TEXTURE_Y(e){Yl.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{encoding:Jl.ENCODING,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,!0,(e,t)=>{o(r,t)})}_decode(e){var t;if("string"==typeof e)return e;const n=new Uint8Array(e),s=null!==(t=this._loadingOptions.encoding)&&void 0!==t?t:"auto";if("auto"!==s)return new TextDecoder(s).decode(n);if(255===n[0]&&254===n[1])return new TextDecoder("utf-16le").decode(n);if(254===n[0]&&255===n[1])return new TextDecoder("utf-16be").decode(n);try{return new TextDecoder("utf-8",{fatal:!0}).decode(n)}catch(e){return new TextDecoder("gb18030").decode(n)}}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 Yl,a=[],l=[];s=(s=this._decode(s)).replace(/#.*$/gm,"").trim(),new Ql(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,this._decode(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.ENCODING="auto",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 eu=!1;function tu(){eu||(eu=!0,t.RegisterSceneLoaderPlugin(new Jl))}var nu={__proto__:null,OBJFileLoader:Jl,RegisterOBJFileLoader:tu};tu();var su={__proto__:null,MTLFileLoader:Yl,OBJFileLoader:Jl,RegisterOBJFileLoader:tu,SolidParser:Ql};const ou={name:"stl",extensions:{".stl":{isBinary:!0}}};class ru{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=ou.name,this.extensions=ou.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,ru.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}ru.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);)ru.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]));ru.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)}}ru.DO_NOT_ALTER_FILE_COORDINATES=!1;let iu=!1;function au(){iu||(iu=!0,t.RegisterSceneLoaderPlugin(new ru))}var lu={__proto__:null,RegisterSTLFileLoader:au,STLFileLoader:ru};au();var uu={__proto__:null,RegisterSTLFileLoader:au,STLFileLoader:ru};const cu={name:"splat",extensions:{".splat":{isBinary:!0},".ply":{isBinary:!0},".spz":{isBinary:!0},".json":{isBinary:!1},".sog":{isBinary:!0}}},du=.28209479177387814;function hu(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 fu(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 hu(t,e,s.getEngine())}return yield hu(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 f=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[f[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=f[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 m=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[m[n+s]]*du;l[32*t+24+s]=Math.max(0,Math.min(255,Math.round(255*o)))}l[32*t+24+3]=m[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=m[s+o],u=t.Scalar.Lerp(r,i,a/255);let c;c=o<3?.5+u*du: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),f=s.getEngine().getCaps().maxTextureSize,m=Math.ceil(o/f),p=t.AllocateShBuffers(h,m*f*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,f=127.5*e.shN.codebook[l[4*(s+n)+r+o*c*4]]+127.5;u[d+h]=Math.max(0,Math.min(255,f))}}}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],f=i%16,m=16*n,_=127.5*t.Scalar.Lerp(a,d,l[4*(o+s)+e+r*c*4]/255)+127.5;h[f+m]=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 mu(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 pu(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 hu(e,n,o);return mu(s,r)})}function _u(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 gu(e,n,s){return b(this,arguments,void 0,function*(e,n,s,o=!0,r,i){var a,l,u,c,d,h,f;let m,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");m=JSON.parse((new TextDecoder).decode(t))}else m=e;const _=e=>b(this,void 0,void 0,function*(){if(p&&p.has(e))return yield hu(p.get(e),e,s.getEngine());if(r){const t=new Uint8Array(yield r.loadFileAsync(n+e,i));return yield hu(t,e,s.getEngine())}return yield hu(n,e,s.getEngine())}),g=e=>b(this,void 0,void 0,function*(){if(p&&p.has(e))return yield pu(p.get(e),e,s);if(r){const t=new Uint8Array(yield r.loadFileAsync(n+e,i));return yield pu(t,e,s)}return yield pu(n,e,s)}),v=[...m.scales.files,...m.quats.files,...m.sh0.files,...null!==(l=null===(a=m.shN)||void 0===a?void 0:a.files)&&void 0!==l?l:[]];let y,x,T,A,M,w=null;if(o){const[e,t]=yield Promise.all([Promise.all(m.means.files.map(_)),Promise.all(v.map(g))]);w=[e[0],e[1]],M=t,y=mu(s,e[0]),x=mu(s,e[1]),T=e[0].width,A=e[0].height}else{const[e,t]=yield Promise.all([Promise.all(m.means.files.map(g)),Promise.all(v.map(g))]);M=t,y=e[0],x=e[1];const n=y.getSize();T=n.width,A=n.height}const C=null!==(u=m.count)&&void 0!==u?u:m.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,L,I,B=0,N=0;if(m.shN&&M.length>=5&&(E=M[3],L=M[4],B=m.shN.bands?Math.pow(m.shN.bands+1,2)-1:m.shN.shape[1]/3,N=null!==(c=m.shN.bands)&&void 0!==c?c:Math.round(Math.sqrt(B+1)-1)),2===m.version){const e=256,n=new Float32Array(3*e);m.scales.codebook&&n.set(m.scales.codebook.slice(0,e),0),m.sh0.codebook&&n.set(m.sh0.codebook.slice(0,e),e),(null===(d=m.shN)||void 0===d?void 0:d.codebook)&&n.set(m.shN.codebook.slice(0,e),2*e),I=new t.RawTexture(n,3*e,1,t.Constants.TEXTUREFORMAT_R,s,!1,!1,t.Constants.TEXTURE_NEAREST_SAMPLINGMODE,t.Constants.TEXTURETYPE_FLOAT),I.wrapU=t.Constants.TEXTURE_CLAMP_ADDRESSMODE,I.wrapV=t.Constants.TEXTURE_CLAMP_ADDRESSMODE}const P=m.means.mins,k=m.means.maxs,D={version:2===m.version?2:1,splatCount:C,shDegree:N,meansTextureL:y,meansTextureU:x,scalesTexture:S,quatsTexture:O,sh0Texture:F,shCentroidsTexture:E,shLabelsTexture:L,codebookTexture:I,meansMin:[P[0],P[1],P[2]],meansMax:[k[0],k[1],k[2]],scalesMin:Array.isArray(m.scales.mins)?[m.scales.mins[0],m.scales.mins[1],m.scales.mins[2]]:void 0,scalesMax:Array.isArray(m.scales.maxs)?[m.scales.maxs[0],m.scales.maxs[1],m.scales.maxs[2]]:void 0,sh0Min:Array.isArray(m.sh0.mins)?[m.sh0.mins[0],m.sh0.mins[1],m.sh0.mins[2],m.sh0.mins[3]]:void 0,sh0Max:Array.isArray(m.sh0.maxs)?[m.sh0.maxs[0],m.sh0.maxs[1],m.sh0.maxs[2],m.sh0.maxs[3]]:void 0,shnMin:"number"==typeof(null===(h=m.shN)||void 0===h?void 0:h.mins)?m.shN.mins:void 0,shnMax:"number"==typeof(null===(f=m.shN)||void 0===f?void 0:f.maxs)?m.shN.maxs:void 0,shCoeffCount:B,positions:w?_u(m,w[0].bits,w[1].bits,C):new Float32Array(0)};return{mode:0,data:new ArrayBuffer(0),hasVertexColors:!1,shDegree:N,sogTextures:D}})}const vu="precision highp float;\nattribute vec3 position;\nvoid main() {\n gl_Position = vec4(position.xy, 0.0, 1.0);\n}\n",yu="\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 bu{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?yu:vu,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?yu:vu,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?yu:vu,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,f=h._gl,m=null===(s=null===(n=c.getInternalTexture())||void 0===n?void 0:n._hardwareTexture)||void 0===s?void 0:s.underlyingResource;if(!m)return null;const p=new Float32Array(o*a*4);this._readFbo||(this._readFbo=f.createFramebuffer());const _=h._currentFramebuffer;f.bindFramebuffer(f.FRAMEBUFFER,this._readFbo),f.framebufferTexture2D(f.FRAMEBUFFER,f.COLOR_ATTACHMENT0,f.TEXTURE_2D,m,0),f.readBuffer(f.COLOR_ATTACHMENT0);const g=h._readPixelsAsync(0,i,o,a,f.RGBA,f.FLOAT,p);return f.bindFramebuffer(f.FRAMEBUFFER,_),_||f.readBuffer(f.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?yu:vu,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?yu:vu,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?yu:vu,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 xu{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 Tu{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 Au{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 Tu;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 Mu{constructor(e,t,n){this._blocks=new Map,this._cooldown=new Map,this._pinned=new Set,this._allocator=new Au(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 wu=Math.tan(22.5*Math.PI/180),Cu=new t.Matrix,Ru=new t.Vector3,Su=new t.Vector3,Ou=new t.Vector3,Fu=new t.Vector3(0,0,1),Eu=[[0,1],[1,2],[2,3],[3,0],[4,5],[5,6],[6,7],[7,4],[0,4],[1,5],[2,6],[3,7]],Lu=2*Eu.length,Iu=[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 Bu 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._lod0SplatCount=Object.freeze({status:"pending"}),this._lodBaseDistance=5,this._lodMultiplier=3,this._lodBehindPenalty=1,this._lodRangeMin=0,this._maxDecodesPerFrame=1,this._lodCooldownFrames=10,this._lodUpdateInterval=4,this._lodUpdateDistance=.5,this._maxDetailLod=0,this._lodPixelThreshold=1,this._hostBudgetAllocation=null,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._frustumScratch=[],this._workBuffer=null,this._streamShDegree=0,this._shTextureCount=0,this._needsRotationScale=!1,this._useGpuPositionReadback=!1,this._readbackCandidate=!1,this._readbackProbed=!1,this._residency=null,this._fileCounts=new Map,this._fileMeta=new Map,this._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._lastLodCamPositions=[],this._lastLodSignature="",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))),this._splatBudget=this._resolveSplatBudget(r.splatBudget),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 xu({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;this._lod0SplatCount=Object.freeze({status:"unavailable"}),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 splatBudget(){return this._splatBudget}set splatBudget(e){const t=e>0?Math.floor(e):0;t!==this._splatBudget&&(this._splatBudget=t,this._forceLodUpdate=!0)}get effectiveSplatBudget(){return this._effectiveSplatBudget()}get residentSplatBudget(){return this._residentBudget}get lod0SplatCount(){return this._lod0SplatCount}_resolveSplatBudget(e){return void 0===e?0:"auto"===e?this._computeDefaultSplatBudget():e>0?Math.floor(e):0}_computeDefaultSplatBudget(){var e;return(null===(e=this._scene.getEngine().hostInformation)||void 0===e?void 0:e.isMobile)?"undefined"!=typeof navigator&&navigator.userAgent&&/iPad|iPhone|iPod/.test(navigator.userAgent)?15e5:1e6:25e5}_effectiveSplatBudget(){if(null!==this._hostBudgetAllocation){const e=Math.max(1,this._hostBudgetAllocation);return this._residentBudget>0?Math.min(e,this._residentBudget):e}return this._splatBudget<=0?0:this._residentBudget>0?Math.min(this._splatBudget,this._residentBudget):this._splatBudget}_splatBudgetEnabled(){return this._effectiveSplatBudget()>0}getBudgetDemand(){var e;if(!this._baseLayerReady)return 0;let t=this._environmentSplatCount();for(const n of this._leafNodes){const s=null!==(e=n.optimalLod)&&void 0!==e?e:n.baseLod;t+=this._countAtLevel(n,this._cappedLevelForNode(n,s))}return t}setBudgetAllocation(e){if(null===e)return void(null!==this._hostBudgetAllocation&&(this._hostBudgetAllocation=null,this._forceLodUpdate=!0));const t=this._hostBudgetAllocation;this._hostBudgetAllocation=e,null!==t&&e===t||(this._forceLodUpdate=!0)}get maxLodLevel(){return Math.max(0,this._metadata.lodLevels-1)}get frustumCulling(){return this._frustumCulling}set frustumCulling(e){this._frustumCulling!==e&&(this._frustumCulling=e,this._forceLodUpdate=!0)}get debugDisplay(){return this._debugDisplay}set debugDisplay(e){this._debugDisplay!==e&&(this._debugDisplay=e,e?this._refreshDebugDisplay():this._clearDebugDisplay())}get debugLodSource(){return this._debugLodSource}set debugLodSource(e){this._debugLodSource!==e&&(this._debugLodSource=e,this._debugDisplay&&this._refreshDebugDisplay())}dispose(e){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._hostCompound&&!this._hostCompound.isDisposed()&&this._hostCompound.unregisterLodBudgetParticipant(this),this._host&&this._hostCompound&&!this._partReleasedByHost&&!this._hostCompound.isDisposed()&&this._hostCompound.removePart(this._host.partIndex),this._host=null,this._lodObserver&&(this._scene.onBeforeRenderObservable.remove(this._lodObserver),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)}_getActiveLodCameras(){var e;return((null===(e=this._scene.activeCameras)||void 0===e?void 0:e.length)?this._scene.activeCameras:this._scene.activeCamera?[this._scene.activeCamera]:[]).filter(e=>!!e)}evaluateOptimalLods(e=null){const n=e?[e]:this._getActiveLodCameras();if(0===n.length||0===this._leafNodes.length)return;const s=Math.max(0,this._metadata.lodLevels-1),o=this._lodBaseDistance,r=this._lodMultiplier,i=this._lodBehindPenalty,a=this._lodRangeMin,l=this._lodRangeMax,u=this._splatBudgetEnabled(),c=this._scene.getEngine().getRenderHeight()||1,d=this._scene.getEngine();this._getEffectiveWorldMatrix(!1).invertToRef(Cu);const h=n.map(e=>{const n=d.getAspectRatio(e)||1;let s=Math.tan(.5*e.fov);e.fovMode===t.Camera.FOVMODE_HORIZONTAL_FIXED&&(s/=n);const o=s*n,r=Math.min(s,o)/wu,a=c*(e.viewport?e.viewport.height:1),l=t.Vector3.TransformCoordinatesToRef(e.globalPosition,Cu,Ru),u={px:l.x,py:l.y,pz:l.z,fwx:0,fwy:0,fwz:0,fovScale:r,tanHalfV:s,pixelHeight:a};if(i>1){e.getDirectionToRef(Fu,Ou);const n=t.Vector3.TransformNormalToRef(Ou,Cu,Su);n.normalize(),u.fwx=n.x,u.fwy=n.y,u.fwz=n.z}return u});for(const e of this._leafNodes){const t=e.bound.min,n=e.bound.max,c=.5*(t[0]+n[0]),d=.5*(t[1]+n[1]),f=.5*(t[2]+n[2]),m=n[0]-t[0],p=n[1]-t[1],_=n[2]-t[2],g=.5*Math.sqrt(m*m+p*p+_*_);let v=Number.POSITIVE_INFINITY,y=0;for(const e of h){const a=e.px<t[0]?t[0]:e.px>n[0]?n[0]:e.px,l=e.py<t[1]?t[1]:e.py>n[1]?n[1]:e.py,h=e.pz<t[2]?t[2]:e.pz>n[2]?n[2]:e.pz,m=a-e.px,p=l-e.py,_=h-e.pz,b=Math.sqrt(m*m+p*p+_*_);let x=b;if(i>1&&b>.01){const t=(e.fwx*m+e.fwy*p+e.fwz*_)/b;t<0&&(x=b*(1+-t*(i-1)))}const T=x*e.fovScale;let A;if(0===s||T<o)A=0;else for(A=s;A>1&&T<o*Math.pow(r,A-1);)A--;if(A<v&&(v=A),u){const t=c-e.px,n=d-e.py,s=f-e.pz,o=Math.sqrt(t*t+n*n+s*s),r=g*e.pixelHeight/(Math.max(o,1e-4)*e.tanHalfV);r>y&&(y=r)}}v<a?v=a:v>l&&(v=l),this._frustumCulling&&!1===e.inFrustum&&(v=l),e.optimalLod=v,u&&(e.pixelSize=y)}}_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=Iu[this._displayedLodLevel(s)%Iu.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 Eu)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*Lu*4)}_updateDebugColors(){if(!this._debugMesh||!this._debugColorData)return;const e=this._debugColorData;let n=0;for(const t of this._leafNodes){const s=Iu[this._displayedLodLevel(t)%Iu.length];for(let t=0;t<Lu;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){var n,s;if(e.children){for(const t of e.children)this._collectLodEntries(t);return}if(!e.lods)return;const o=null===(n=e.bound)||void 0===n?void 0:n.min,r=null===(s=e.bound)||void 0===s?void 0:s.max;if(!o||!r||o.length<3||r.length<3||!o.every(e=>Number.isFinite(e))||!r.every(e=>Number.isFinite(e)))return;const i=r[0]-o[0],a=r[1]-o[1],l=r[2]-o[2],u=Math.sqrt(i*i+a*a+l*l);if(!Number.isFinite(u)||u<=0)return;const c=Math.floor(Number(this._metadata.lodLevels)),d=Number.isFinite(c)&&c>0?c-1:0,h=[];for(const t of Object.keys(e.lods)){const n=Number(t),s=e.lods[t],o=s?Math.floor(Number(s.count)):NaN;Number.isInteger(n)&&String(n)===t&&n>=0&&n<=d&&s&&Number.isFinite(o)&&o>0&&(s.count=o,h.push(n))}if(0===h.length)return;h.sort((e,t)=>e-t);const f=[];let m=1/0;for(const t of h){const n=e.lods[String(t)].count;n<=m&&(f.push(t),m=n)}e.availableLevels=f,e.baseLod=f[f.length-1],e.activeLod=void 0,e.lodCooldown=0,e.inFrustum=!0,e.cullBounds=new t.BoundingInfo(t.Vector3.FromArray(o),t.Vector3.FromArray(r)),this._leafNodes.push(e)}_streamAllAsync(){return b(this,void 0,void 0,function*(){const e=this._collectAllFileIds(),n=yield this._gatherCountsAsync(e);if(this._resolveLod0SplatCount(),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 Mu(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,this._hostCompound.registerLodBudgetParticipant(this);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 bu(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 bu(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)}_resolveLod0SplatCount(){var e,t;let n=0,s=!1;for(const o of this._leafNodes){if(0!==(null===(e=o.availableLevels)||void 0===e?void 0:e[0]))continue;const r=null===(t=o.lods)||void 0===t?void 0:t[0];if(!r)return void(this._lod0SplatCount=Object.freeze({status:"unavailable"}));if(s=!0,!this._fileCounts.has(r.file)||!this._fileMeta.has(r.file))return void(this._lod0SplatCount=Object.freeze({status:"unavailable"}));if(n+=r.count,!Number.isSafeInteger(n))return void(this._lod0SplatCount=Object.freeze({status:"unavailable"}))}this._lod0SplatCount=s?Object.freeze({status:"available",count:n}):Object.freeze({status:"unavailable"})}_gatherCountsAsync(e){return b(this,void 0,void 0,function*(){var n;let s=0,o=0,r=0;const i=e=>{const t=Bu._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=Bu._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,Bu._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 gu(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{Bu._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 gu(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{Bu._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;const t=this._effectiveSplatBudget();if(t<=0){for(const t of this._leafNodes){const n=null!==(e=t.optimalLod)&&void 0!==e?e:t.baseLod;t.targetLevel=this._cappedLevelForNode(t,n)}return}const n=Math.max(0,t-this._environmentSplatCount());this._convergePixelThreshold(n);const s=this._lodPixelThreshold;for(const e of this._leafNodes)e.targetLevel=this._budgetedLevel(e,s)}_environmentSplatCount(){const e=this._environmentRange?Math.floor(Number(this._environmentRange.count)):0;return Number.isFinite(e)&&e>0?e:0}_budgetedLevel(e,t){var n,s;const o=null!==(n=e.optimalLod)&&void 0!==n?n:e.baseLod,r=null!==(s=e.pixelSize)&&void 0!==s?s:0;let i=0;return r>0&&t>r&&(i=Math.max(0,Math.round(Math.log(t/r)/Math.log(this._lodMultiplier)))),this._cappedLevelForNode(e,o+i)}_countAtLevel(e,t){const n=e.lods[String(t)];return n?n.count:0}_totalSplatsAtThreshold(e){let t=0;for(const n of this._leafNodes)t+=this._countAtLevel(n,this._budgetedLevel(n,e));return t}_convergePixelThreshold(e){if(this._totalSplatsAtThreshold(1)<=e)return void(this._lodPixelThreshold=1);let t=1;for(const e of this._leafNodes)e.pixelSize&&e.pixelSize>t&&(t=e.pixelSize);const n=Math.min(32,Math.max(1,this._metadata.lodLevels)),s=t*Math.pow(this._lodMultiplier,n+1);if(this._totalSplatsAtThreshold(s)>e)return void(this._lodPixelThreshold=s);let o=1,r=s;for(let t=0;t<40&&r-o>.001*r;t++){const t=.5*(o+r);this._totalSplatsAtThreshold(t)<=e?r=t:o=t}this._lodPixelThreshold=r}_residentLevelAtLeast(e,t){for(const n of e.availableLevels)if(n>=t&&this._decodedFiles.has(e.lods[String(n)].file))return n;return null}_applyDesiredLods(){var e;let t=!1;for(const n of this._leafNodes){const s=null!==(e=n.targetLevel)&&void 0!==e?e:n.baseLod;if(this._splatBudgetEnabled()&&void 0!==n.activeLod&&n.activeLod<s){const e=this._residentLevelAtLeast(n,s);null!==e&&e!==n.activeLod&&(this._switchActiveFile(n,n.lods[String(e)].file),n.activeLod=e,n.lodCooldown=this._lodCooldownFrames,t=!0)}if(n.lodCooldown&&n.lodCooldown>0)continue;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._getActiveLodCameras(),n=this._lodUpdateDistance;if(e.length!==this._lastLodCamPositions.length||this._computeLodSignature(e)!==this._lastLodSignature)o=!0;else for(let s=0;s<e.length;s++)if(t.Vector3.DistanceSquared(e[s].globalPosition,this._lastLodCamPositions[s])>=n*n){o=!0;break}}if(o){this._forceLodUpdate=!1,this._framesSinceLodUpdate=0;const e=this._getActiveLodCameras();this._lastLodCamPositions.length=0;for(const t of e)this._lastLodCamPositions.push(t.globalPosition.clone());this._lastLodSignature=this._computeLodSignature(e),this.evaluateOptimalLods(),this._computeTargetLevels(),this._applyDesiredLods()&&this._refreshActiveRanges()}}_computeLodSignature(e){const t=this._scene.getEngine();let n=`${t.getRenderWidth()}x${t.getRenderHeight()}#${this._getEffectiveWorldMatrix(!1).updateFlag}`;for(const t of e){const e=t.viewport;n+=`|${t.uniqueId}:${t.fov}:${t.fovMode}:${e.x},${e.y},${e.width},${e.height}`}return n}_updateNodeFrustum(){const e=this._getActiveLodCameras();let n=!1;if(!this._frustumCulling||0===e.length){for(const e of this._leafNodes)!1===e.inFrustum&&(e.inFrustum=!0,n=!0);return n}const s=this._leafNodes,o=this._frustumScratch,r=this._getEffectiveWorldMatrix(!1);for(let e=0;e<s.length;e++)s[e].cullBounds.update(r),o[e]=!1;for(const n of e){n.getViewMatrix().multiplyToRef(n.getProjectionMatrix(),this._cullViewProj),t.Frustum.GetPlanesToRef(this._cullViewProj,this._frustumPlanes);for(let e=0;e<s.length;e++)!o[e]&&s[e].cullBounds.isInFrustum(this._frustumPlanes)&&(o[e]=!0)}for(let e=0;e<s.length;e++)o[e]!==s[e].inFrustum&&(s[e].inFrustum=o[e],n=!0);return n}static _GetSplatCount(e){var t;const n=null!==(t=e.count)&&void 0!==t?t:Array.isArray(e.means.shape)?e.means.shape[0]:0,s=Math.floor(Number(n));return Number.isFinite(s)&&s>0?s: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(Bu._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 Nu=.28209479177387814;let Pu=null,ku=null;class Du{constructor(e={}){this.name=cu.name,this._assetContainer=null,this.extensions=cu.extensions,this._loadingOptions=Object.assign(Object.assign({},Du._DefaultLoadingOptions),e)}createPlugin(e){return new Du(e[cu.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(!Bu.IsLODMetadata(s))return null;const o=e._blockEntityCollection;e._blockEntityCollection=!!this._assetContainer;try{const t=new Bu("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=Du._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?gu:fu;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=>{Du._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=Du._ExtractSafeOrbitLimits(s)}break;case 1:{const e=new t.PointsCloudSystem("PointCloud",1,n);Du._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(Du._BuildMesh(n,s));break;default:throw new Error("Unsupported Splat mode")}n._blockEntityCollection=!1,this.applyAutoCameraLimits(Du._ExtractSafeOrbitLimits(s),n),e(r)}))},h=31===c[0]&&139===c[1],f=78===c[0]&&71===c[1]&&83===c[2]&&80===c[3];if(!h&&!f)return new Promise(e=>{d(e)});const m=(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=Du._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(Pu&&ku===e)return yield Pu;const n=t._LoadScriptModuleAsync(`import createSpzModule from '${e}';\n const module = await createSpzModule();\n const returnedValue = module;`);return ku=e,Pu=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 f=null;const m=e.shDegree;let p,_,g=null,v=0,y=null,b=null,x=null;if(m>0&&e.sh.length>0){v=3*((m+1)*(m+1)-1);const s=Math.ceil(v/16),r=n.getEngine().getCaps().maxTextureSize,i=Math.ceil(o/r);f=t.AllocateShBuffers(s,i*r*4*4),y=new Int32Array(s),b=new Int32Array(s);for(let e=0;e<s;e++)y[e]=16*e,b[e]=Math.min(16*(e+1),v);x=f,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 f=255*(.5+Nu*c[o+0]),m=255*(.5+Nu*c[o+1]),p=255*(.5+Nu*c[o+2]);a[n+24]=f<=0?0:f>=255?255:f+.5|0,a[n+25]=m<=0?0:m>=255?255:m+.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&&y&&b){const t=e*v,n=16*e;for(let e=0;e<x.length;e++){const s=x[e],o=y[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!==f?f:void 0,shDegree:m>0?m: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=>{m(e,t)})));if(f)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),f=new Int32Array(1),m=new Uint8Array(f.buffer),p=function(e,t){return m[0]=e[t+0],m[1]=e[t+1],m[2]=e[t+2],m[3]=128&e[t+2]?255:0,f[0]*h};let _=16;const g=new Float32Array(d),v=new Float32Array(d),y=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;y[32*e+24+n]=t.Scalar.Clamp(255*(.5+Nu*o),0,255)}y[32*e+24+3]=s[_+e]}_+=4*r;for(let e=0;e<r;e++)v[8*e+3+0]=Math.exp(s[_+0]/16-10),v[8*e+3+1]=Math.exp(s[_+1]/16-10),v[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=>{m(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 f=1;const m=[],p=[],_=s.slice(0,o).split("\n"),g={};for(const n of _)if(n.startsWith("property ")){const[,s,o]=n.split(" ");if(1==f)p.push({name:o,type:s,offset:d}),d+=h[s];else if(0==f)m.push({name:o,type:s,offset:c}),c+=h[s];else if(2==f)m.push({name:o,type:s,offset:c});else if(3==f){const t=new DataView(e,d,2*h.float);g.safeOrbitCameraElevationMinMax=[t.getFloat32(0,!0),t.getFloat32(4,!0)]}else if(4==f){const t=new DataView(e,d,h.float);g.safeOrbitCameraRadiusMin=t.getFloat32(0,!0)}else if(5==f){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?f=1:"vertex"==e?f=0:"sh"==e?f=2:"safe_orbit_camera_elevation_min_max_radians"==e?f=3:"safe_orbit_camera_radius_min"==e?f=4:"up_axis"!=e&&"chirality"!=e||(f=5)}const v=c,y=d;return t.GaussianSplattingMesh.ConvertPLYWithSHToSplatAsync(e).then(t=>b(this,void 0,void 0,function*(){const n=new DataView(e,o+11);let s=y*u+v*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<m.length;e++){const t=m[e];d.includes(t.name)&&l++,h.includes(t.name)&&c++}const f=l==d.length&&c>=3,p=a?2:f?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}))})}))}}Du._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 Gu=!1;function Vu(){Gu||(Gu=!0,t.RegisterSceneLoaderPlugin(new Du))}var Hu={__proto__:null,RegisterSPLATFileLoader:Vu,SPLATFileLoader:Du};Vu();const Uu={name:"usd",extensions:{".usd":{isBinary:!0},".usda":{isBinary:!0},".usdc":{isBinary:!0},".usdz":{isBinary:!0}}};var Ku,$u,qu,Wu;const zu=4294967295;var ju,Xu,Yu,Qu,Zu,Ju,ec,tc;function nc(e){switch(e){case 1:return 12;case 2:case 7:return 40;case 3:return 76;case 4:case 5:return 20;case 6:return 60;case 8:return 16;case 9:return 32;case 10:return 44;default:throw new Error(`Unknown OpenUSD Babylon command opcode ${e}.`)}}!function(e){e[e.Scene=1]="Scene",e[e.Texture=2]="Texture",e[e.Material=3]="Material",e[e.TransformNode=4]="TransformNode",e[e.Skeleton=5]="Skeleton",e[e.Geometry=6]="Geometry",e[e.Mesh=7]="Mesh",e[e.Instance=8]="Instance",e[e.Animation=9]="Animation",e[e.AnalyticPrimitive=10]="AnalyticPrimitive"}(ju||(ju={})),function(e){e[e.Cube=0]="Cube",e[e.Sphere=1]="Sphere",e[e.Cylinder=2]="Cylinder",e[e.Cone=3]="Cone"}(Xu||(Xu={})),function(e){e[e.X=0]="X",e[e.Y=1]="Y",e[e.Z=2]="Z"}(Yu||(Yu={})),function(e){e[e.Node=0]="Node",e[e.Bone=1]="Bone"}(Qu||(Qu={})),function(e){e[e.Position=0]="Position",e[e.RotationQuaternion=1]="RotationQuaternion",e[e.Scaling=2]="Scaling",e[e.Matrix=3]="Matrix"}(Zu||(Zu={})),function(e){e[e.DoubleSided=1]="DoubleSided",e[e.Unlit=2]="Unlit",e[e.AlphaBlend=4]="AlphaBlend"}(Ju||(Ju={})),function(e){e[e.DoubleSided=1]="DoubleSided",e[e.LeftHanded=2]="LeftHanded"}(ec||(ec={})),function(e){e[e.Normals=1]="Normals",e[e.Tangents=2]="Tangents",e[e.Uv0=4]="Uv0",e[e.Colors=8]="Colors",e[e.Skin0=16]="Skin0",e[e.Skin1=32]="Skin1"}(tc||(tc={}));class sc{constructor(e,t,n){Ku.add(this),$u.set(this,void 0),qu.set(this,void 0),T(this,$u,new DataView(e),"f"),this.offset=t,T(this,qu,t+n,"f")}u32(){x(this,Ku,"m",Wu).call(this,4);const e=x(this,$u,"f").getUint32(this.offset,!0);return this.offset+=4,e}f32(){x(this,Ku,"m",Wu).call(this,4);const e=x(this,$u,"f").getFloat32(this.offset,!0);return this.offset+=4,e}}$u=new WeakMap,qu=new WeakMap,Ku=new WeakSet,Wu=function(e){if(this.offset+e>x(this,qu,"f"))throw new Error("OpenUSD Babylon command payload read exceeded its bounds.")};class oc extends t.AbstractAssetContainer{dispose(){for(const e of this.animationGroups.splice(0))e.dispose();for(const e of this.meshes.splice(0))e.dispose();for(const e of this.skeletons.splice(0))e.dispose();for(const e of this.multiMaterials.splice(0))e.dispose();for(const e of this.materials.splice(0))e.dispose();for(const e of this.geometries.splice(0))e.dispose();for(const e of this.transformNodes.splice(0))e.dispose();for(const e of this.textures.splice(0))e.dispose();this.rootNodes.length=0}}const rc=new TextDecoder,ic="__babylonUsdLocalMatrix";function ac(e,t,n,s,o){if(!Number.isInteger(t)||!Number.isInteger(n)||t<0||n<0||t%Math.min(s,4)!==0||n>Math.floor((e.byteLength-t)/s))throw new Error(`Invalid ${o} range in OpenUSD Babylon data buffer.`)}function lc(e,t,n){return ac(e,t,n,1,"string"),rc.decode(new Uint8Array(e,t,n))}function uc(e,n){ac(e,n,16,4,"matrix");const s=new Float32Array(e,n,16);return t.Matrix.FromValues(s[0],s[1],s[2],s[3],s[4],s[5],s[6],s[7],s[8],s[9],s[10],s[11],s[12],s[13],s[14],s[15])}function cc(e){switch(e){case 2:return"image/jpeg";case 3:return"image/bmp";case 4:return"image/webp";default:return"image/png"}}function dc(e){switch(e){case 0:return t.Texture.CLAMP_ADDRESSMODE;case 1:return t.Texture.WRAP_ADDRESSMODE;case 2:return t.Texture.MIRROR_ADDRESSMODE;default:throw new Error(`Invalid texture wrap mode ${e}.`)}}const hc=`${t.Tools._DefaultCdnUrl}/babylonUsdImporter/4/`,fc=/\.(?:usd|usda|usdc|usdz)$/i;function mc(e){return e instanceof Uint8Array?e.slice():e instanceof ArrayBuffer?new Uint8Array(e.slice(0)):new Uint8Array(e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength))}function pc(e,t,n){const s=null==e?void 0:e.replace(/\\/g,"/").replace(/^\.\/+/,""),o=n?s:null==s?void 0:s.split(/[?#]/,1)[0],r=null==o?void 0:o.split("/").filter(Boolean);return o&&!o.startsWith("/")&&(null==r?void 0:r.length)&&!r.includes("..")&&fc.test(o)?r.join("/"):t.length>=4&&80===t[0]&&75===t[1]&&3===t[2]&&4===t[3]?"scene.usdz":"scene.usd"}class _c{constructor(e={}){var t,n,s,o,r;this.name=Uu.name,this.extensions=Uu.extensions,this._nextRequestId=1,this._pending=new Map,this._activeLoads=new Set,this._options=Object.assign(Object.assign({},e),{resolveByFileName:null===(t=e.resolveByFileName)||void 0===t||t,glueUrl:null!==(n=e.glueUrl)&&void 0!==n?n:_c.DefaultConfiguration.glueUrl,wasmUrl:null!==(s=e.wasmUrl)&&void 0!==s?s:_c.DefaultConfiguration.wasmUrl,dataUrl:null!==(o=e.dataUrl)&&void 0!==o?o:_c.DefaultConfiguration.dataUrl,workerUrl:null!==(r=e.workerUrl)&&void 0!==r?r:_c.DefaultConfiguration.workerUrl})}createPlugin(e){return yc(),new _c(e[Uu.name])}importMeshAsync(e,t,n,s,o,r){return b(this,void 0,void 0,function*(){return{meshes:(e=(yield this._loadAsync(t,n,s,o,r,!0)).container).meshes,particleSystems:e.particleSystems,skeletons:e.skeletons,animationGroups:e.animationGroups,transformNodes:e.transformNodes,geometries:e.geometries,lights:e.lights,spriteManagers:e.spriteManagers};var e})}loadAsync(e,t,n,s,o){return b(this,void 0,void 0,function*(){yield this._loadAsync(e,t,n,s,o,!0)})}loadAssetContainerAsync(e,n,s,o,r){return b(this,void 0,void 0,function*(){const i=(yield this._loadAsync(e,n,s,o,r,!1)).container;if(!(i instanceof t.AssetContainer))throw new Error("USDFileLoader failed to create an asset container.");return i})}dispose(){this._terminateWorker();const e=new Error("USDFileLoader was disposed.");for(const t of this._activeLoads)t.abort(e);for(const t of this._pending.values())t.reject(e);this._pending.clear()}_loadAsync(e,n,s,o,r,i){return b(this,void 0,void 0,function*(){var s,a,l,u,c,d;if(!(n instanceof ArrayBuffer||ArrayBuffer.isView(n)))throw new Error("USDFileLoader expects binary USD data.");const h=mc(n),f=function(e){if(!e)return;const t={};for(const[n,s]of Object.entries(e))t[n]=mc(s);return t}(this._options.files),m=this._nextRequestId++,p={type:"extract",requestId:m,asset:{bytes:h,files:f,fileName:pc(null!==(s=this._options.rootFileName)&&void 0!==s?s:r,h,void 0!==this._options.rootFileName),resolveByFileName:null===(a=this._options.resolveByFileName)||void 0===a||a,glueUrl:this._options.glueUrl,wasmUrl:this._options.wasmUrl,dataUrl:this._options.dataUrl}},_=[...new Set([h.buffer,...Object.values(null!=f?f:{}).map(e=>e.buffer)])],g=new AbortController,v=g.signal;this._activeLoads.add(g);try{const n=this._getWorker(this._options.workerUrl),s=yield new Promise((e,t)=>{this._pending.set(m,{resolve:e,reject:t,onProgress:e=>{var t,n;null===(n=(t=this._options).onProgress)||void 0===n||n.call(t,e),null==o||o({lengthComputable:!1,loaded:gc[e.phase],total:4})},onLog:this._options.onLog});try{n.postMessage(p,_)}catch(e){this._pending.delete(m),t(e instanceof Error?e:new Error(String(e)))}}),r={phase:"materializing",message:"Creating Babylon.js objects..."};null===(u=(l=this._options).onProgress)||void 0===u||u.call(l,r),null==o||o({lengthComputable:!1,loaded:4,total:4}),v.throwIfAborted();const a=yield function(e,n,s,o,r){return b(this,void 0,void 0,function*(){var i,a,l,u,c,d,h,f,m,p,_,g,v,y;null==r||r.throwIfAborted();const b=performance.now(),x=function(e){const t=new DataView(e);if(t.byteLength<16||1111774037!==t.getUint32(0,!0))throw new Error("Invalid OpenUSD Babylon command buffer.");if(4!==t.getUint16(4,!0))throw new Error(`Unsupported OpenUSD Babylon protocol ${t.getUint16(4,!0)}.`);const n=t.getUint32(8,!0),s=[];let o=16;for(let e=0;e<n;++e){if(o+8>t.byteLength)throw new Error("Truncated OpenUSD Babylon command header.");const e=t.getUint16(o,!0),n=t.getUint16(o+2,!0),r=t.getUint32(o+4,!0),i=o+8,a=nc(e);if(r!==a)throw new Error(`Invalid payload length ${r} for command ${e}; expected ${a}.`);if(i+r>t.byteLength)throw new Error("Truncated OpenUSD Babylon command payload.");s.push({opcode:e,flags:n,payloadOffset:i,payloadLength:r}),o=i+r}if(o!==t.byteLength)throw new Error("Unexpected trailing data in OpenUSD Babylon command buffer.");return s}(n),T=o?new oc:new t.AssetContainer(e),A=new Map,M=[],w=new Map,C=new Map,R=new Map,S=new Map,O=new Map,F=new Map,E=new Map,L=new Map,I=[],B=new Set,N=T instanceof t.AssetContainer?T:void 0;let P,k=24;const D=(e,t)=>{e.push(t),N&&(t._parentContainer=N)},G=(n,s)=>{const o=!(2&s);n.sideOrientation=e.useRightHandedSystem===o?t.Material.CounterClockWiseSideOrientation:t.Material.ClockWiseSideOrientation},V=(e,t)=>{const n=C.get(e);if(!n||!t||!n.backFaceCulling)return null!=n?n:null;let s=R.get(e);return s||(s=n.clone(`${n.name} (double-sided)`),D(T.materials,s),s.backFaceCulling=!1,s.twoSidedLighting=!0,R.set(e,s)),s};try{const R=e._blockEntityCollection;o||(e._blockEntityCollection=!0);try{for(const o of x){const r=new sc(n,o.payloadOffset,o.payloadLength);switch(o.opcode){case 1:{const n=1===r.u32(),s=r.f32();k=r.f32()||24,P=new t.TransformNode("USD Root",e),D(T.transformNodes,P),T.rootNodes.push(P),P.rotationQuaternion=n?t.Quaternion.FromArray([-.7071068,0,0,.7071068]):t.Quaternion.Identity(),P.scaling.copyFrom(e.useRightHandedSystem?new t.Vector3(s,s,s):n?new t.Vector3(s,-s,s):new t.Vector3(s,s,-s));break}case 2:{const n=r.u32(),o=r.u32(),i=r.u32(),a=cc(r.u32()),l=r.u32(),u=r.u32(),c=r.u32(),d=r.u32(),h=r.u32(),f=r.u32();ac(s,d,5,4,"texture transform"),ac(s,l,u,1,"texture image");const m=new Float32Array(s,d,5),p=new Uint8Array(s,l,u),_=URL.createObjectURL(new Blob([p],{type:a}));let g,v;B.add(_);const y=new Promise((e,t)=>{g=e,v=t});I.push(y);const b=new t.Texture(_,e,!1,!1,t.Texture.TRILINEAR_SAMPLINGMODE,g,(e,t)=>{URL.revokeObjectURL(_),v(t instanceof Error?t:new Error(e||`Could not load texture '${_}'.`))});D(T.textures,b),b.onDisposeObservable.addOnce(()=>URL.revokeObjectURL(_)),b.name=lc(s,o,i),b.coordinatesIndex=c,b.uScale=m[0],b.vScale=m[1],b.uRotationCenter=0,b.vRotationCenter=0,b.uOffset=m[2]-m[1]*Math.sin(m[4]),b.vOffset=1-m[1]*Math.cos(m[4])-m[3],b.wAng=-m[4],b.wrapU=dc(h),b.wrapV=dc(f),w.set(n,b);break}case 3:{const n=r.u32(),o=r.u32(),d=r.u32(),h=r.u32(),f=r.u32(),m=r.f32(),p=r.f32(),_=r.f32(),g=r.f32(),v=r.u32(),y=r.u32(),b=r.u32(),x=r.u32(),A=r.u32(),M=r.u32(),R=r.u32(),S=r.u32(),O=r.u32(),F=r.u32();ac(s,h,4,4,"material base color"),ac(s,f,3,4,"material emissive color");const E=new Float32Array(s,h,4),L=new Float32Array(s,f,3),I=new t.PBRMaterial(lc(s,o,d),e);D(T.materials,I),I.id=`usd-material-${n}`,I.albedoColor=new t.Color3(E[0],E[1],E[2]),I.alpha=E[3],I.metallic=m,I.roughness=p,I.emissiveColor=new t.Color3(L[0],L[1],L[2]);const B=Boolean(1&v);I.backFaceCulling=!B,I.twoSidedLighting=B,I.unlit=Boolean(2&v),4&v&&(I.transparencyMode=2),g>0&&(I.transparencyMode=1,I.alphaCutOff=g),y!==zu&&(I.albedoTexture=null!==(i=w.get(y))&&void 0!==i?i:null,I.albedoTexture&&b===zu&&4&v&&(I.albedoTexture.hasAlpha=!0,I.useAlphaFromAlbedoTexture=!0)),b!==zu&&(I.opacityTexture=null!==(a=w.get(b))&&void 0!==a?a:null,I.opacityTexture&&(I.opacityTexture.gammaSpace=!1,I.opacityTexture.getAlphaFromRGB=3!==R)),x!==zu&&(I.bumpTexture=null!==(l=w.get(x))&&void 0!==l?l:null,I.bumpTexture&&(I.bumpTexture.gammaSpace=!1,I.bumpTexture.level=_)),A!==zu&&(I.metallicTexture=null!==(u=w.get(A))&&void 0!==u?u:null,I.metallicTexture&&(I.metallicTexture.gammaSpace=!1,I.useRoughnessFromMetallicTextureAlpha=3===S,I.useRoughnessFromMetallicTextureGreen=1===S,I.useMetallnessFromMetallicTextureBlue=2===O,I.useAmbientOcclusionFromMetallicTextureRed=0===F)),M!==zu&&(I.emissiveTexture=null!==(c=w.get(M))&&void 0!==c?c:null),C.set(n,I);break}case 4:{const n=r.u32(),o=r.u32(),i=r.u32(),a=r.u32(),l=r.u32(),u=new t.TransformNode(lc(s,i,a),e);D(T.transformNodes,u),u.setPreTransformMatrix(uc(s,l)),Object.defineProperty(u,ic,{configurable:!0,get:()=>u.getPivotMatrix(),set:e=>u.setPreTransformMatrix(e)}),A.set(n,u),o===zu?u.parent=null!=P?P:null:M.push({node:u,parentId:o});break}case 5:{const n=r.u32(),o=r.u32(),i=r.u32(),a=r.u32(),l=r.u32(),u=new t.Skeleton(lc(s,o,i),`usd-skeleton-${n}`,e);D(T.skeletons,u);const c=new DataView(s);ac(s,l,5*a,4,"skeleton joints");const d=[];for(let e=0;e<a;++e){const o=l+20*e,r=c.getUint32(o,!0),i=c.getUint32(o+4,!0),a=c.getUint32(o+8,!0),h=c.getUint32(o+12,!0),f=c.getUint32(o+16,!0);if(r!==zu&&r>=e)throw new Error(`Skeleton ${n} has an invalid parent joint index.`);const m=new t.Bone(lc(s,a,h),u,r===zu?null:d[r],uc(s,f),uc(s,f),void 0,e);d.push(m),O.set(i,m)}S.set(n,u);break}case 6:{const e=r.u32();F.set(e,{vertexCount:r.u32(),indexCount:r.u32(),flags:r.u32(),positions:r.u32(),normals:r.u32(),tangents:r.u32(),uv0:r.u32(),colors:r.u32(),joints0:r.u32(),weights0:r.u32(),joints1:r.u32(),weights1:r.u32(),indices:r.u32(),influences:r.u32()});break}case 7:{const n=r.u32(),o=r.u32(),i=r.u32(),a=r.u32(),l=r.u32(),u=r.u32(),c=r.u32(),m=r.u32(),p=r.u32(),_=r.u32(),g=F.get(i);if(!g)throw new Error(`Mesh ${n} references missing geometry ${i}.`);const v=new t.Mesh(lc(s,l,u),e);D(T.meshes,v),G(v,c),v.parent=null!==(h=null!==(d=A.get(o))&&void 0!==d?d:P)&&void 0!==h?h:null;const y=new t.VertexData;ac(s,g.positions,3*g.vertexCount,4,"positions"),y.positions=new Float32Array(s,g.positions,3*g.vertexCount),1&g.flags&&(ac(s,g.normals,3*g.vertexCount,4,"normals"),y.normals=new Float32Array(s,g.normals,3*g.vertexCount)),2&g.flags&&(ac(s,g.tangents,4*g.vertexCount,4,"tangents"),y.tangents=new Float32Array(s,g.tangents,4*g.vertexCount)),4&g.flags&&(ac(s,g.uv0,2*g.vertexCount,4,"texture coordinates"),y.uvs=new Float32Array(s,g.uv0,2*g.vertexCount)),8&g.flags&&(ac(s,g.colors,4*g.vertexCount,4,"vertex colors"),y.colors=new Float32Array(s,g.colors,4*g.vertexCount)),16&g.flags&&(ac(s,g.joints0,4*g.vertexCount,2,"joint indices"),ac(s,g.weights0,4*g.vertexCount,4,"joint weights"),y.matricesIndices=Float32Array.from(new Uint16Array(s,g.joints0,4*g.vertexCount)),y.matricesWeights=new Float32Array(s,g.weights0,4*g.vertexCount)),32&g.flags&&(ac(s,g.joints1,4*g.vertexCount,2,"extra joint indices"),ac(s,g.weights1,4*g.vertexCount,4,"extra joint weights"),y.matricesIndicesExtra=Float32Array.from(new Uint16Array(s,g.joints1,4*g.vertexCount)),y.matricesWeightsExtra=new Float32Array(s,g.weights1,4*g.vertexCount)),ac(s,g.indices,g.indexCount,4,"indices"),y.indices=new Uint32Array(s,g.indices,g.indexCount),y.applyToMesh(v,!0),v.geometry&&D(T.geometries,v.geometry),v.numBoneInfluencers=Math.min(g.influences,8),m!==zu&&(v.skeleton=null!==(f=S.get(m))&&void 0!==f?f:null);const b=new DataView(s);ac(s,p,5*_,4,"submeshes");const x=Boolean(1&c);if(1===_&&a!==zu)v.material=V(a,x);else{const n=new t.MultiMaterial(`${v.name} materials`,e);D(T.multiMaterials,n);for(let e=0;e<_;++e){const t=p+20*e;n.subMaterials.push(V(b.getUint32(t,!0),x))}v.material=n}v.releaseSubMeshes();for(let e=0;e<_;++e){const n=p+20*e;new t.SubMesh(e,b.getUint32(n+12,!0),b.getUint32(n+16,!0),b.getUint32(n+4,!0),b.getUint32(n+8,!0),v)}E.set(n,v);break}case 10:{const n=r.u32(),o=r.u32(),i=r.u32(),a=r.u32(),l=r.u32(),u=r.u32(),c=r.u32(),d=r.u32(),h=r.f32(),f=r.f32(),_=r.u32(),g=lc(s,l,u);if(!Number.isFinite(h)||h<=0)throw new Error(`Analytic primitive ${n} has an invalid size or radius.`);if((2===i||3===i)&&(!Number.isFinite(f)||f<=0))throw new Error(`Analytic primitive ${n} has an invalid height.`);if(0!==i&&(!Number.isInteger(_)||_<3||_>512))throw new Error(`Analytic primitive ${n} has invalid tessellation.`);let v;switch(i){case 0:v=t.CreateBox(g,{size:h},e);break;case 1:v=t.CreateSphere(g,{diameter:2*h,segments:_},e);break;case 2:case 3:v=t.CreateCylinder(g,{height:f,diameterTop:3===i?0:2*h,diameterBottom:2*h,tessellation:_},e);break;default:throw new Error(`Unsupported analytic primitive type ${i}.`)}if(D(T.meshes,v),v.geometry&&D(T.geometries,v.geometry),!(2&c)){const e=v.getIndices();if(!e)throw new Error(`Analytic primitive ${n} has no generated indices.`);const t=Array.from(e);for(let e=0;e<t.length;e+=3)[t[e],t[e+2]]=[t[e+2],t[e]];v.setIndices(t)}if(0===d)v.rotationQuaternion=t.Quaternion.RotationAxis(new t.Vector3(0,0,1),-Math.PI/2);else if(2===d)v.rotationQuaternion=t.Quaternion.RotationAxis(new t.Vector3(1,0,0),Math.PI/2);else if(1!==d)throw new Error(`Unsupported analytic primitive axis ${d}.`);G(v,c),v.parent=null!==(p=null!==(m=A.get(o))&&void 0!==m?m:P)&&void 0!==p?p:null,v.material=V(a,Boolean(1&c)),E.set(n,v);break}case 8:{const e=r.u32(),t=r.u32(),n=r.u32(),o=r.u32(),i=E.get(e);if(!i)throw new Error(`Instance references missing mesh ${e}.`);const a=i.createInstance(lc(s,n,o));D(T.meshes,a),a.parent=null!==(g=null!==(_=A.get(t))&&void 0!==_?_:P)&&void 0!==g?g:null;break}case 9:{const n=r.u32(),o=r.u32(),i=r.u32(),a=r.u32(),l=r.u32(),u=r.u32(),c=r.u32(),d=r.u32();if(0!==n&&1!==n)throw new Error(`Invalid animation target kind ${n}.`);if(d!==(0===i||2===i?3:1===i?4:3===i?16:0))throw new Error(`Invalid animation value stride ${d} for property ${i}.`);const h=0===n?A.get(o):O.get(o);if(!h)break;const f=0===i?"position":1===i?"rotationQuaternion":2===i?"scaling":0===n?ic:"_matrix",m=1===i?t.Animation.ANIMATIONTYPE_QUATERNION:3===i?t.Animation.ANIMATIONTYPE_MATRIX:t.Animation.ANIMATIONTYPE_VECTOR3,p=new t.Animation(`USD ${f}`,f,k,m,t.Animation.ANIMATIONLOOPMODE_CYCLE);ac(s,u,l,4,"animation times"),ac(s,c,l*d,4,"animation values");const _=new Float32Array(s,u,l),g=new Float32Array(s,c,l*d);p.setKeys(Array.from({length:l},(e,n)=>({frame:_[n],value:m===t.Animation.ANIMATIONTYPE_QUATERNION?t.Quaternion.FromArray(g,n*d):m===t.Animation.ANIMATIONTYPE_MATRIX?t.Matrix.FromArray(g,n*d):t.Vector3.FromArray(g,n*d)})));let v=L.get(a);v||(v=new t.AnimationGroup(`USD Animation ${a+1}`,e),L.set(a,v),D(T.animationGroups,v)),v.addTargetedAnimation(p,h);break}}}}finally{o||(e._blockEntityCollection=R)}const N=Promise.all(I);if(r){let e;const t=new Promise((t,n)=>{e=()=>n(r.reason instanceof Error?r.reason:new Error("USD materialization was aborted.")),r.aborted?e():r.addEventListener("abort",e,{once:!0})});try{yield Promise.race([N,t]),r.throwIfAborted()}finally{e&&r.removeEventListener("abort",e)}}else yield N;for(const{node:e,parentId:t}of M)e.parent=null!==(y=null!==(v=A.get(t))&&void 0!==v?v:P)&&void 0!==y?y:null;return{container:T,materializeMs:performance.now()-b}}catch(e){Promise.allSettled(I),T.dispose();for(const e of B)URL.revokeObjectURL(e);throw e}})}(e,s.commands,s.data,i,v),h={container:a.container,timings:Object.assign(Object.assign({},s.timings),{materializeMs:a.materializeMs}),statistics:s.statistics,missingAssets:s.missingAssets};try{v.throwIfAborted(),null===(d=(c=this._options).onComplete)||void 0===d||d.call(c,{timings:h.timings,statistics:h.statistics,missingAssets:h.missingAssets}),v.throwIfAborted()}catch(e){throw a.container.dispose(),e}return h}finally{this._activeLoads.delete(g),0===this._pending.size&&this._terminateWorker()}})}_getWorker(e){var t;if(!e)throw new Error("The USD worker URL was not configured.");const n=globalThis.location,s=new URL(String(e),null!==(t=null==n?void 0:n.href)&&void 0!==t?t:"http://localhost/").href;if(this._worker&&this._workerUrl!==s){if(this._pending.size>0)throw new Error("Cannot change the USD worker URL while requests are pending.");this._terminateWorker()}if(this._worker)return this._worker;this._workerUrl=s,n&&new URL(s).origin!==n.origin?(this._workerBlobUrl=URL.createObjectURL(new Blob([`import ${JSON.stringify(s)};`],{type:"application/javascript"})),this._worker=new Worker(this._workerBlobUrl,{type:"module"})):this._worker=new Worker(s,{type:"module"}),this._worker.addEventListener("message",e=>{var t,n;const s=e.data,o=this._pending.get(s.requestId);if(o)if("progress"!==s.type)if("log"!==s.type)if(this._pending.delete(s.requestId),"error"===s.type){const e=new Error(s.message);e.stack=s.stack,o.reject(e)}else o.resolve(s);else null===(n=o.onLog)||void 0===n||n.call(o,s.level>=2?"error":1===s.level?"warning":"info",s.message);else null===(t=o.onProgress)||void 0===t||t.call(o,s.progress)});const o=e=>{this._terminateWorker();for(const t of this._pending.values())t.reject(e);this._pending.clear()};return this._worker.addEventListener("error",e=>{var t;o(null!==(t=e.error)&&void 0!==t?t:new Error(e.message||`Could not load the USD worker from '${s}'.`))}),this._worker.addEventListener("messageerror",()=>{o(new Error("The USD worker returned a message that could not be deserialized."))}),this._worker}_terminateWorker(){var e;null===(e=this._worker)||void 0===e||e.terminate(),this._worker=void 0,this._workerUrl=void 0,this._workerBlobUrl&&(URL.revokeObjectURL(this._workerBlobUrl),this._workerBlobUrl=void 0)}}_c.DefaultConfiguration={glueUrl:`${hc}babylon-usd-importer.js`,wasmUrl:`${hc}babylon-usd-importer.wasm`,dataUrl:`${hc}babylon-usd-importer.data`,workerUrl:`${hc}babylon-usd-importer.worker.js`};const gc={initializing:1,staging:2,extracting:3,materializing:4};let vc=!1;function yc(){t.RegisterPbrMaterial(),t.RegisterInstancedMesh()}function bc(){vc||(vc=!0,yc(),t.RegisterSceneLoaderPlugin(new _c))}var xc={__proto__:null,RegisterUSDFileLoader:bc,USDFileLoader:_c,_RegisterUSDLoaderDependencies:yc};function Tc(){t.RegisterSceneLoaderPlugin(Object.assign(Object.assign({},m),{createPlugin:e=>b(this,void 0,void 0,function*(){const{BVHFileLoader:t}=yield Promise.resolve().then(function(){return v});return new t(e[m.name])})})),t.RegisterSceneLoaderPlugin(Object.assign(Object.assign({},Dt),{createPlugin:e=>b(this,void 0,void 0,function*(){const{FBXFileLoader:t}=yield Promise.resolve().then(function(){return en});return new t(e[Dt.name])})})),t.RegisterSceneLoaderPlugin(Object.assign(Object.assign({},an),{createPlugin:e=>b(this,void 0,void 0,function*(){const[{GLTFFileLoader:t,RegisterGLTF2Loader:n},{RegisterInstancedMesh:s}]=yield Promise.all([Promise.resolve().then(function(){return Ps}),Promise.resolve(BABYLON)]);return s(),n(),new t(e[an.name])})})),function(){ds("EXT_lights_image_based"),cs("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 eo});return new t(e)})),ds("EXT_mesh_gpu_instancing"),cs("EXT_mesh_gpu_instancing",!0,e=>b(this,void 0,void 0,function*(){const[{EXT_mesh_gpu_instancing:t},{RegisterThinInstanceMesh:n}]=yield Promise.all([Promise.resolve().then(function(){return ro}),Promise.resolve(BABYLON)]);return n(),new t(e)})),ds("EXT_meshopt_compression"),cs("EXT_meshopt_compression",!0,e=>b(this,void 0,void 0,function*(){const{EXT_meshopt_compression:t}=yield Promise.resolve().then(function(){return co});return new t(e)})),ds("EXT_texture_avif"),cs("EXT_texture_avif",!0,e=>b(this,void 0,void 0,function*(){const{EXT_texture_avif:t}=yield Promise.resolve().then(function(){return xo});return new t(e)})),ds("EXT_texture_webp"),cs("EXT_texture_webp",!0,e=>b(this,void 0,void 0,function*(){const{EXT_texture_webp:t}=yield Promise.resolve().then(function(){return _o});return new t(e)})),ds("ExtrasAsMetadata"),cs("ExtrasAsMetadata",!1,e=>b(this,void 0,void 0,function*(){const{ExtrasAsMetadata:t}=yield Promise.resolve().then(function(){return ql});return new t(e)})),ds("KHR_animation_pointer"),cs("KHR_animation_pointer",!0,e=>b(this,void 0,void 0,function*(){const[{KHR_animation_pointer:t},{_RegisterKHRAnimationPointerData:n}]=yield Promise.all([Promise.resolve().then(function(){return oa}),Promise.resolve().then(function(){return va})]);return n(),new t(e)})),ds("KHR_draco_mesh_compression"),cs("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 Eo});return new t(e)})),ds("KHR_gaussian_splatting"),cs("KHR_gaussian_splatting",!0,e=>b(this,void 0,void 0,function*(){const{KHR_gaussian_splatting:t}=yield Promise.resolve().then(function(){return Go});return new t(e)})),ds("KHR_interactivity"),cs("KHR_interactivity",!0,e=>b(this,void 0,void 0,function*(){const{KHR_interactivity:t,_RegisterKHRInteractivityRuntime:n}=yield Promise.resolve().then(function(){return gl});return n(),new t(e)})),ds("KHR_lights_punctual"),cs("KHR_lights_punctual",!0,e=>b(this,void 0,void 0,function*(){const{KHR_lights:t}=yield Promise.resolve().then(function(){return $o});return new t(e)})),ds("EXT_lights_area"),cs("EXT_lights_area",!0,e=>b(this,void 0,void 0,function*(){const{EXT_lights_area:t}=yield Promise.resolve().then(function(){return Xo});return new t(e)})),ds("EXT_lights_ies"),cs("EXT_lights_ies",!0,e=>b(this,void 0,void 0,function*(){const{EXT_lights_ies:t}=yield Promise.resolve().then(function(){return Co});return new t(e)})),ds("KHR_materials_anisotropy"),cs("KHR_materials_anisotropy",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_anisotropy:t}=yield Promise.resolve().then(function(){return wr});return new t(e)})),ds("KHR_materials_clearcoat"),cs("KHR_materials_clearcoat",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_clearcoat:t}=yield Promise.resolve().then(function(){return cr});return new t(e)})),ds("KHR_materials_diffuse_roughness"),cs("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 Ii});return new t(e)})),ds("KHR_materials_diffuse_transmission"),cs("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 fi});return new t(e)})),ds("KHR_materials_dispersion"),cs("KHR_materials_dispersion",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_dispersion:t}=yield Promise.resolve().then(function(){return Si});return new t(e)})),ds("KHR_materials_emissive_strength"),cs("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 Fr});return new t(e)})),ds("KHR_materials_ior"),cs("KHR_materials_ior",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_ior:t}=yield Promise.resolve().then(function(){return Yr});return new t(e)})),ds("KHR_materials_iridescence"),cs("KHR_materials_iridescence",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_iridescence:t}=yield Promise.resolve().then(function(){return br});return new t(e)})),ds("KHR_materials_pbrSpecularGlossiness"),cs("KHR_materials_pbrSpecularGlossiness",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_pbrSpecularGlossiness:t}=yield Promise.resolve().then(function(){return er});return new t(e)})),ds("KHR_materials_sheen"),cs("KHR_materials_sheen",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_sheen:t}=yield Promise.resolve().then(function(){return Nr});return new t(e)})),ds("KHR_materials_specular"),cs("KHR_materials_specular",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_specular:t}=yield Promise.resolve().then(function(){return qr});return new t(e)})),ds("KHR_materials_transmission"),cs("KHR_materials_transmission",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_transmission:t}=yield Promise.resolve().then(function(){return li});return new t(e)})),ds("KHR_materials_unlit"),cs("KHR_materials_unlit",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_unlit:t}=yield Promise.resolve().then(function(){return rr});return new t(e)})),ds("KHR_materials_variants"),cs("KHR_materials_variants",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_variants:t}=yield Promise.resolve().then(function(){return ti});return new t(e)})),ds("KHR_materials_volume"),cs("KHR_materials_volume",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_volume:t}=yield Promise.resolve().then(function(){return vi});return new t(e)})),ds("KHR_mesh_quantization"),cs("KHR_mesh_quantization",!0,e=>b(this,void 0,void 0,function*(){const{KHR_mesh_quantization:t}=yield Promise.resolve().then(function(){return Di});return new t(e)})),ds("KHR_texture_basisu"),cs("KHR_texture_basisu",!0,e=>b(this,void 0,void 0,function*(){const{KHR_texture_basisu:t}=yield Promise.resolve().then(function(){return Ki});return new t(e)})),ds("KHR_texture_transform"),cs("KHR_texture_transform",!0,e=>b(this,void 0,void 0,function*(){const{KHR_texture_transform:t}=yield Promise.resolve().then(function(){return ji});return new t(e)})),ds("KHR_xmp_json_ld"),cs("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 Ji});return new t(e)})),ds("MSFT_audio_emitter"),cs("MSFT_audio_emitter",!0,e=>b(this,void 0,void 0,function*(){const[{MSFT_audio_emitter:t},{RegisterAudioSceneComponent:n},{Sound:s}]=yield Promise.all([Promise.resolve().then(function(){return Aa}),Promise.resolve(BABYLON),Promise.resolve(BABYLON)]);return n(s),new t(e)})),ds("MSFT_lod"),cs("MSFT_lod",!0,e=>b(this,void 0,void 0,function*(){const{MSFT_lod:t}=yield Promise.resolve().then(function(){return Sa});return new t(e)})),ds("MSFT_minecraftMesh"),cs("MSFT_minecraftMesh",!0,e=>b(this,void 0,void 0,function*(){const{MSFT_minecraftMesh:t}=yield Promise.resolve().then(function(){return Ia});return new t(e)})),ds("MSFT_sRGBFactors"),cs("MSFT_sRGBFactors",!0,e=>b(this,void 0,void 0,function*(){const{MSFT_sRGBFactors:t}=yield Promise.resolve().then(function(){return Da});return new t(e)})),ds("KHR_node_visibility"),cs("KHR_node_visibility",!0,e=>b(this,void 0,void 0,function*(){const{KHR_node_visibility:t,_RegisterKHRNodeVisibilityRuntime:n}=yield Promise.resolve().then(function(){return Ml});return n(),new t(e)})),ds("KHR_node_hoverability"),cs("KHR_node_hoverability",!0,e=>b(this,void 0,void 0,function*(){const{KHR_node_hoverability:t,_RegisterKHRNodeHoverabilityRuntime:n}=yield Promise.resolve().then(function(){return Vl});return n(),new t(e)})),ds("KHR_node_selectability"),cs("KHR_node_selectability",!0,e=>b(this,void 0,void 0,function*(){const{KHR_node_selectability:t,_RegisterKHRNodeSelectabilityRuntime:n}=yield Promise.resolve().then(function(){return El});return n(),new t(e)})),ds("KHR_materials_coat"),cs("KHR_materials_coat",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_coat:t}=yield Promise.resolve().then(function(){return pr});return new t(e)})),ds("KHR_materials_fuzz"),cs("KHR_materials_fuzz",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_fuzz:t}=yield Promise.resolve().then(function(){return Vr});return new t(e)})),ds("KHR_materials_volume_scatter"),cs("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 Ai});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 nu});return new t(e[Zl.name])})})),t.RegisterSceneLoaderPlugin(Object.assign(Object.assign({},cu),{createPlugin:e=>b(this,void 0,void 0,function*(){const[{SPLATFileLoader:t},{RegisterEnginesExtensionsEngineDynamicTexture:n}]=yield Promise.all([Promise.resolve().then(function(){return Hu}),Promise.resolve(BABYLON)]);return n(),new t(e[cu.name])})})),t.RegisterSceneLoaderPlugin(Object.assign(Object.assign({},ou),{createPlugin:()=>b(this,void 0,void 0,function*(){const[{STLFileLoader:e},{RegisterStandardMaterial:t}]=yield Promise.all([Promise.resolve().then(function(){return lu}),Promise.resolve(BABYLON)]);return t(),new e})})),t.RegisterSceneLoaderPlugin(Object.assign(Object.assign({},Uu),{createPlugin:e=>b(this,void 0,void 0,function*(){const{USDFileLoader:t,_RegisterUSDLoaderDependencies:n}=yield Promise.resolve().then(function(){return xc});return n(),new t(e[Uu.name])})}))}bc();var Ac={__proto__:null,registerBuiltInLoaders:Tc};const Mc="undefined"!=typeof global?global:"undefined"!=typeof window?window:void 0;if(void 0!==Mc)for(const e in y)Mc.BABYLON[e]||(Mc.BABYLON[e]=y[e]);const wc="undefined"!=typeof global?global:"undefined"!=typeof window?window:void 0;if(void 0!==wc){wc.BABYLON=wc.BABYLON||{};for(const e in Ac)wc.BABYLON[e]=Ac[e]}const Cc="undefined"!=typeof global?global:"undefined"!=typeof window?window:void 0;if(void 0!==Cc){Cc.BABYLON=Cc.BABYLON||{};for(const e in Sn)Cc.BABYLON[e]=Sn[e];for(const e in on)Cc.BABYLON[e]=on[e]}const Rc="undefined"!=typeof global?global:"undefined"!=typeof window?window:void 0;if(void 0!==Rc){Rc.BABYLON=Rc.BABYLON||{},Rc.BABYLON.GLTF1=Rc.BABYLON.GLTF1||{};for(const e in as)Rc.BABYLON.GLTF1[e]=as[e]}const Sc=Object.assign({},jl),Oc=Object.assign(Object.assign({},{__proto__:null}),{Extensions:Sc}),Fc=Object.assign(Object.assign({},Xl),{Loader:Oc}),Ec="undefined"!=typeof global?global:"undefined"!=typeof window?window:void 0;if(void 0!==Ec){Ec.BABYLON=Ec.BABYLON||{};const e=Ec.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 Sc)e.GLTF2.Loader.Extensions[n]=Sc[n],t.push(n);for(const n in Oc)"Extensions"!==n&&(e.GLTF2.Loader[n]=Oc[n],t.push(n));for(const n in Fc)t.indexOf(n)>-1||(e.GLTF2[n]=Fc[n])}const Lc="undefined"!=typeof global?global:"undefined"!=typeof window?window:void 0;if(void 0!==Lc)for(const e in su)Lc.BABYLON[e]||(Lc.BABYLON[e]=su[e]);const Ic="undefined"!=typeof global?global:"undefined"!=typeof window?window:void 0;if(void 0!==Ic)for(const e in uu)Ic.BABYLON[e]||(Ic.BABYLON[e]=uu[e]);e.AddGaussianSplattingStreamPart=function(e,t,n,s,o={}){return new Bu(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 Bu(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=Gt,e.FBXFileLoaderMetadata=Dt,e.GLTF1=as,e.GLTF2=Fc,e.GLTFFileLoader=_n,e.GLTFLoaderDefaultOptions=mn,e.GLTFValidation=sn,e.GaussianSplattingStream=Bu,e.MTLFileLoader=Yl,e.OBJFileLoader=Jl,e.ReadBvh=f,e.RegisterBVHFileLoader=g,e.RegisterGLTFFileLoader=vn,e.RegisterOBJFileLoader=tu,e.RegisterSPLATFileLoader=Vu,e.RegisterSTLFileLoader=au,e.RegisterUSDFileLoader=bc,e.SPLATFileLoader=Du,e.STLFileLoader=ru,e.SolidParser=Ql,e.USDFileLoader=_c,e._RegisterUSDLoaderDependencies=yc,e.registerBuiltInLoaders=Tc});
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",o="Yposition",s="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,o=e.offset.y,s=e.offset.z;return t.Matrix.Translation(n,o,s)}(e),h=new t.Bone(e.name,u.skeleton,l,d),f=function(e,l){if(0===e.frames.length)return[];const u=[],c=e.channels.some(e=>e===n||e===o||e===s),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),f=new t.Animation(`${e.name}_rot`,"rotationQuaternion",l.frameRate,t.Animation.ANIMATIONTYPE_QUATERNION,l.loopMode),p=[],m=[];for(let t=0;t<e.frames.length;t++){const n=e.frames[t];c&&n.position&&p.push({frame:n.frame,value:n.position.clone()}),d&&m.push({frame:n.frame,value:n.rotation.clone()})}return p.length>0&&(h.setKeys(p),u.push(h)),m.length>0&&(f.setKeys(m),u.push(f)),u}(e,u);for(const e of f)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 f=t.Matrix.Identity();for(let l=0;l<u.channels.length;++l){const d=u.channels[l],p=e[c.i++];if(!p)continue;const m=parseFloat(p.trim());if(d.endsWith("position"))switch(d){case n:h.position.x=m;break;case o:h.position.y=m;break;case s:h.position.z=m}else if(d.endsWith("rotation")){const e=t.Tools.ToRadians(m);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)}f=n.multiply(f)}}t.Quaternion.FromRotationMatrixToRef(f,h.rotation);for(const t of u.children)d(e,l,t,c)}function h(e,n,o,s){var r,i,a,l;const c=u();c.parent=o,s.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 f=null===(i=e.shift())||void 0===i?void 0:i.trim().split(/\s+/);if(!f)throw new Error("Unexpected end of file: missing OFFSET");if(d=f,"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 p=new t.Vector3(parseFloat(d[1]),parseFloat(d[2]),parseFloat(d[3]));if(isNaN(p.x)||isNaN(p.y)||isNaN(p.z))throw new Error("OFFSET: Invalid values");if(c.offset=p,"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,s))}throw new Error("Unexpected end of file: missing closing brace")}function f(e,n,o,s){const r=e.split("\n"),{loopMode:i}=s;n._blockEntityCollection=!!o;const a=new t.Skeleton("","",n);a._parentContainer=o,n._blockEntityCollection=!1;const u=new l(a);u.loopMode=i;const f=r.shift();if(!f||"HIERARCHY"!==f.trim().toUpperCase())throw new Error("HIERARCHY expected");const p=r.shift();if(!p)throw new Error("Unexpected end of file after HIERARCHY");const m=h(r,p.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 v=g.trim().split(/[\s]+/);if(v.length<2)throw new Error("Invalid frame count line");const y=parseInt(v[1]);if(isNaN(y))throw new Error("Failed to read number of frames.");u.numFrames=y;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<y;++e){const t=r.shift();t&&d(t.trim().split(/[\s]+/)||[],e,m,{i:0})}return u.root=m,c(u.root,null,u),u.skeleton.returnToRest(),u.skeleton}const p={name:"bvh",extensions:{".bvh":{isBinary:!1}}};class m{constructor(e){this.name=p.name,this.extensions=p.extensions,this._loadingOptions=Object.assign(Object.assign({},m._DefaultLoadingOptions),null!=e?e:{})}static get _DefaultLoadingOptions(){return{loopMode:t.Animation.ANIMATIONLOOPMODE_CYCLE}}createPlugin(e){return new m(e[p.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=f(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 o=new t.AssetContainer(e);try{const t=f(n,e,o,this._loadingOptions);return o.skeletons.push(t),Promise.resolve(o)}catch(e){return Promise.reject(e)}}}let _=!1;function g(){_||(_=!0,t.RegisterSceneLoaderPlugin(new m))}var v={__proto__:null,BVHFileLoader:m,RegisterBVHFileLoader:g};g();var y={__proto__:null,BVHFileLoader:m,ReadBvh:f,RegisterBVHFileLoader:g};function b(e,t,n,o){return new(n||(n=Promise))(function(s,r){function i(e){try{l(o.next(e))}catch(e){r(e)}}function a(e){try{l(o.throw(e))}catch(e){r(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(i,a)}l((o=o.apply(e,t||[])).next())})}function x(e,t,n,o){if("a"===n&&!o)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!o:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?o:"a"===n?o.call(e):o?o.value:t.get(e)}function T(e,t,n,o,s){if("m"===o)throw new TypeError("Private method is not writable");if("a"===o&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===o?s.call(e,n):s?s.value=n:t.set(e,n),n}Object.create,Object.create,"function"==typeof SuppressedError&&SuppressedError;const A=[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],M=[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],w=[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],S=[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],C=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];class R{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 I{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 O{constructor(e,t={}){const n=new Array(16).fill(0);let o=0,s=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]++,o++,s=Math.max(s,t))}if(0===o){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!==o)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 o=new Int16Array(1<<t);return o.fill(-1),o});for(let t=0;t<e.length;t++){const n=e[t];0!==n&&(this.symbolsByLength[n][i[n]++]=t)}this.maxCodeLength=s}decode(e){var t,n;if(0===this.maxCodeLength)throw new Error("deflate: invalid huffman code");let o=0;for(let s=1;s<=this.maxCodeLength;s++){o=o<<1|e.readBit();const r=null!==(n=null===(t=this.symbolsByLength[s])||void 0===t?void 0:t[o])&&void 0!==n?n:-1;if(r>=0)return r}throw new Error("deflate: invalid huffman code")}}let F,E;function L(){if(!F){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;F=new O(e)}return F}function N(){return E||(E=new O(new Array(32).fill(5))),E}function k(e,t){e.alignToByte();const n=e.readUint16LE();if(65535&(n^~e.readUint16LE()))throw new Error("deflate: invalid stored block length");for(let o=0;o<n;o++)t.writeByte(e.readByte())}function B(e,t,n,o){for(;;){const s=n.decode(e);if(s<256){t.writeByte(s);continue}if(256===s)return;if(s>285)throw new Error("deflate: invalid literal/length symbol");const r=s-257,i=A[r]+e.readBits(M[r]),a=o.decode(e);if(a>29)throw new Error("deflate: invalid distance symbol");const l=w[a]+e.readBits(S[a]);t.copy(l,i)}}function P(e){const t=e.readBits(5)+257,n=e.readBits(5)+1,o=e.readBits(4)+4,s=new Array(19).fill(0);for(let t=0;t<o;t++)s[C[t]]=e.readBits(3);const r=function(e,t,n){const o=[];for(;o.length<n;){const s=t.decode(e);if(s<=15){o.push(s);continue}let r,i;switch(s){case 16:if(0===o.length)throw new Error("deflate: invalid code length repeat");i=o[o.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(o.length+r>n)throw new Error("deflate: invalid code length repeat");for(let e=0;e<r;e++)o.push(i)}return o}(e,new O(s),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 O(i),distanceTree:new O(a,{allowEmpty:!0})}}let D=!0;function V(e,t,n,o,s){let r,i,a,l;if(o?(U(t,n,25,s,"FBX node header"),r=H(e,n),i=H(e,n+8),a=H(e,n+16),l=25):(U(t,n,13,s,"FBX node header"),r=e.getUint32(n,D),i=e.getUint32(n+4,D),a=e.getUint32(n+8,D),l=13),0===r)return null;if(r<=n||r>s)throw new Error(`Invalid FBX node end offset ${r} at offset ${n}`);const u=t[n+l-1];U(t,n+l,u,r,"FBX node name");const c=W(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 f=[];for(let n=0;n<i;n++){const n=G(e,t,d,h);f.push(n.property),d=n.nextOffset}if(d!==h)throw new Error(`Invalid FBX property list length for node '${c}' at offset ${n}`);const p=[];if(d<r)for(;d<r;){const n=V(e,t,d,o,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}`);p.push(n.node),d=n.endOffset}return{node:{name:c,properties:f,children:p},endOffset:r}}function G(e,t,n,o){U(t,n,1,o,"FBX property type");const s=String.fromCharCode(t[n]);switch(n+=1,s){case"C":{U(t,n,1,o,"FBX boolean property");const e=t[n];return e>1?{property:{type:"int32",value:e},nextOffset:n+1}:{property:{type:"boolean",value:0!==e},nextOffset:n+1}}case"Z":return U(t,n,1,o,"FBX byte property"),{property:{type:"int32",value:t[n]},nextOffset:n+1};case"Y":return U(t,n,2,o,"FBX int16 property"),{property:{type:"int16",value:e.getInt16(n,D)},nextOffset:n+2};case"I":return U(t,n,4,o,"FBX int32 property"),{property:{type:"int32",value:e.getInt32(n,D)},nextOffset:n+4};case"F":return U(t,n,4,o,"FBX float32 property"),{property:{type:"float32",value:e.getFloat32(n,D)},nextOffset:n+4};case"D":return U(t,n,8,o,"FBX float64 property"),{property:{type:"float64",value:e.getFloat64(n,D)},nextOffset:n+8};case"L":{U(t,n,8,o,"FBX int64 property");const s=K(e,n),r={type:"int64",value:s};return Number.isSafeInteger(s)||(r.raw=function(e,t){let n=e.getUint32(D?t:t+4,D),o=e.getUint32(D?t+4:t,D);const s=!!(2147483648&o);s&&(n=1+~n>>>0,o=~o+(0===n?1:0)>>>0);const r=[];for(;0!==o||0!==n;){const e=Math.floor(o/10),t=o%10*4294967296+n;r.push(t%10),o=e,n=Math.floor(t/10)}return(s?"-":"")+(r.length>0?r.reverse().join(""):"0")}(e,n)),{property:r,nextOffset:n+8}}case"S":{U(t,n,4,o,"FBX string property length");const s=e.getUint32(n,D);U(t,n+4,s,o,"FBX string property data");const r=function(e,t,n){return new TextDecoder("utf-8").decode(e.subarray(t,t+n))}(t,n+4,s);return{property:{type:"string",value:r},nextOffset:n+4+s}}case"R":{U(t,n,4,o,"FBX raw property length");const s=e.getUint32(n,D);return U(t,n+4,s,o,"FBX raw property data"),{property:{type:"raw",value:t.slice(n+4,n+4+s)},nextOffset:n+4+s}}case"f":return $(e,t,n,"float32[]",4,o);case"d":return $(e,t,n,"float64[]",8,o);case"i":return $(e,t,n,"int32[]",4,o);case"l":return $(e,t,n,"int64[]",8,o);case"b":case"c":return $(e,t,n,"boolean[]",1,o);default:throw new Error(`Unknown FBX property type: '${s}' at offset ${n-1}`)}}function $(e,t,n,o,s,r){U(t,n,12,r,`FBX array property header for ${o}`);const i=e.getUint32(n,D),a=e.getUint32(n+4,D),l=e.getUint32(n+8,D),u=i*s;let c;if(U(t,n+=12,l,r,`FBX array property data for ${o}`),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],o=e[1];if(8!=(15&n)||n>>4>7||((n<<8)+o)%31!=0)throw new Error("zlib: invalid header");if(32&o)throw new Error("zlib: preset dictionary not supported");const s=new R(e,2,e.byteLength-4),r=new I(t);let i=!1;for(;!i;)switch(i=1===s.readBits(1),s.readBits(2)){case 0:k(s,r);break;case 1:B(s,r,L(),N());break;case 2:{const{literalLengthTree:e,distanceTree:t}=P(s);B(s,r,e,t);break}default:throw new Error("deflate: invalid block type")}if(s.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 ${o}`);c=t.slice(n,n+l)}!D&&s>1&&"int64[]"!==o&&function(e,t){for(let n=0;n+t<=e.length;n+=t)for(let o=n,s=n+t-1;o<s;o++,s--){const t=e[o];e[o]=e[s],e[s]=t}}(c,s);const d=c.buffer.slice(c.byteOffset,c.byteOffset+c.byteLength);let h;switch(o){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]=K(t,8*e);return n}(c);break;default:throw new Error(`Unexpected array type: ${o}`)}return{property:{type:o,value:h},nextOffset:n+l}}function U(e,t,n,o,s){if(t<0||n<0||t+n>o||t+n>e.byteLength)throw new Error(`${s}: unexpected end of input`)}function H(e,t){const n=e.getUint32(D?t:t+4,D);return 4294967296*e.getUint32(D?t+4:t,D)+n}function K(e,t){const n=e.getUint32(D?t:t+4,D);return 4294967296*e.getInt32(D?t+4:t,D)+n}function W(e,t,n){let o="";for(let s=0;s<n;s++)o+=String.fromCharCode(e[t+s]);return o}function q(e){const t=new X(e),n=function(e){const t=e.match(/;\s*FBX\s+(\d+)\.(\d+)\.(\d+)/);if(t)return 1e3*parseInt(t[1])+100*parseInt(t[2])+parseInt(t[3]);const n=e.match(/FBXVersion:\s*(\d+)/);return n?parseInt(n[1]):e.includes("Properties70")?7e3:6e3}(e),o=[];for(;!t.isEOF()&&(t.skipWhitespaceAndComments(),!t.isEOF());){const e=Y(t);e&&o.push(e)}return n>=7200&&z(o),{version:n,nodes:o}}function z(e){for(const t of e){if("KeyAttrDataFloat"===t.name&&1===t.properties.length&&t.properties[0].value instanceof Float64Array){const e=t.properties[0].value,n=new Int32Array(e.length);for(let t=0;t<e.length;t++)n[t]=0|e[t];t.properties[0]={type:"float32[]",value:new Float32Array(n.buffer)}}t.children.length>0&&z(t.children)}}var j;!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"}(j||(j={}));let X=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++,t.includes("&quot;")&&(t=t.split("&quot;").join('"')),{type:2,value:t,pos:e}}readNumber(){const e=this.pos;if("-"!==this.text[this.pos]&&"+"!==this.text[this.pos]||this.pos++,this.pos<this.len&&this.isIdentStart(this.text[this.pos])){for(;this.pos<this.len&&this.isIdentStart(this.text[this.pos]);)this.pos++;return this.skipSpecialNumberSuffix(),{type:1,value:this.text.substring(e,this.pos),pos:e}}for(;this.pos<this.len&&this.isDigit(this.text[this.pos]);)this.pos++;if(this.pos<this.len&&"."===this.text[this.pos])for(this.pos++;this.pos<this.len&&this.isDigit(this.text[this.pos]);)this.pos++;if(this.pos<this.len&&("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++;if(this.pos<this.len&&"#"===this.text[this.pos]){for(this.pos++;this.pos<this.len&&(this.isIdentStart(this.text[this.pos])||this.isDigit(this.text[this.pos]));)this.pos++;this.skipSpecialNumberSuffix()}return{type:1,value:this.text.substring(e,this.pos),pos:e}}readIdentifier(){const e=this.pos;for(;this.pos<this.len&&this.isIdentChar(this.text[this.pos]);)this.pos++;return this.skipSpecialNumberSuffix(),{type:0,value:this.text.substring(e,this.pos),pos:e}}skipSpecialNumberSuffix(){if(this.pos<this.len&&"("===this.text[this.pos])for(;this.pos<this.len;){const e=this.text[this.pos];if("("!==e&&")"!==e&&!this.isIdentChar(e))break;this.pos++}}isDigit(e){return e>="0"&&e<="9"}isNumberStart(e){if(this.isDigit(e)||"."===e)return!0;if(("-"===e||"+"===e)&&this.pos+1<this.len){const e=this.text[this.pos+1];return this.isDigit(e)||"."===e||Q(this.text.substring(this.pos+1,this.pos+10))}return!!Q(this.text.substring(this.pos,this.pos+9))&&!this.isFollowedByColon(this.pos)}isFollowedByColon(e){let t=e;for(;t<this.len&&this.isIdentChar(this.text[t]);)t++;for(;t<this.len&&(" "===this.text[t]||"\t"===this.text[t]);)t++;return t<this.len&&":"===this.text[t]}isIdentStart(e){return e>="a"&&e<="z"||e>="A"&&e<="Z"||"_"===e}isIdentChar(e){return this.isIdentStart(e)||this.isDigit(e)||"|"===e||"-"===e}};function Y(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 o=n.value;e.expect(5);const s=[],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){const t=e.next();n.push(Z(t.value))}else{if(0!==t.type||e.isNextNodeStart())break;{const t=e.next();n.push(Z(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);s.push({type:"float64[]",value:new Float64Array(t)})}return e.expect(4),{name:o,properties:s,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);if(!Number.isInteger(n)||t.value.includes(".")||t.value.includes("e")||t.value.includes("E"))s.push({type:"float64",value:n});else{const e={type:ee(n)?"int32":"int64",value:n};Number.isSafeInteger(n)||(e.raw=J(t.value)),s.push(e)}}else if(2===i.type){const t=e.next();s.push({type:"string",value:t.value})}else if(0===i.type){if(e.isNextNodeStart())break;const t=e.next();s.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=Y(e);if(!t)break;r.push(t)}e.expect(4)}return{name:o,properties:s,children:r}}function Q(e){return/^(?:inf(?:inity)?|nan|ind)(?![A-Za-z0-9_|])/i.test(e)}function Z(e){const t=Number(e);if(!Number.isNaN(t))return t;const n=e.startsWith("-")?-1:1,o=e.replace(/^[+-]/,"").replace(/\(.*$/,"");return/#INF/i.test(o)||/^inf/i.test(o)?n*(1/0):NaN}function J(e){const t=e.startsWith("-"),n=e.replace(/^[+-]/,"").replace(/^0+(?=\d)/,"");return t&&"0"!==n?`-${n}`:n}function ee(e){return e>=-2147483648&&e<=2147483647}function te(e,t){return e.children.find(e=>e.name===t)}function ne(e,t){return e.nodes.find(e=>e.name===t)}function oe(e,t){if(t<e.properties.length)return e.properties[t].value}function se(e){if(!e||0===e.properties.length)return null;const t=e.properties[0].value;if(1===e.properties.length&&(t instanceof Float32Array||t instanceof Float64Array||t instanceof Int32Array||t instanceof Uint8Array))return t;const n=new Float64Array(e.properties.length);for(let t=0;t<e.properties.length;t++){const o=e.properties[t].value;if("number"==typeof o)n[t]=o;else{if("boolean"!=typeof o)return null;n[t]=o?1:0}}return n}function re(e){const t=e.indexOf("\0");if(t>=0)return e.substring(0,t);const n=e.indexOf("::");return n>=0?e.substring(n+2):e}function ie(e,t,n){const o=e.get(t);if(o)return n?o.get(n):o.values().next().value}function ae(e,t,n,o=0){var s;return null===(s=ce(e,t,n))||void 0===s?void 0:s[o]}function le(e,t,n,o){var s;return null!==(s=de(ae(e,t,n)))&&void 0!==s?s:o}function ue(e,t,n,o){const s=ce(e,t,n);if(!s)return o;const r=de(s[0]),i=de(s[1]),a=de(s[2]);return void 0!==r&&void 0!==i&&void 0!==a?[r,i,a]:o}function ce(e,t,n){var o,s;return null!==(o=function(e,t){const n=[te(e,"Properties70"),te(e,"Properties60")].filter(e=>void 0!==e);let o;for(const e of n)for(const n of e.children)"P"!==n.name&&"Property"!==n.name||oe(n,0)===t&&(o=n.properties.slice("Property"===n.name?3:4).map(e=>e.value));return o}(e,n))&&void 0!==o?o:null===(s=null==t?void 0:t.properties.get(n))||void 0===s?void 0:s.values}function de(e){if("number"==typeof e)return e}function he(e,t,n){var o;const s=new Map,r=te(n,"Properties70");for(const e of null!==(o=null==r?void 0:r.children)&&void 0!==o?o:[]){if("P"!==e.name)continue;const t=ge(e);t&&s.set(t.name,t)}return{objectType:e,templateName:t,properties:s}}function fe(e){const t=[];if(!e)return t;for(const n of e.children)if("Properties70"===n.name||"Properties60"===n.name)for(const e of n.children){if("P"!==e.name&&"PS"!==e.name&&"Property"!==e.name)continue;const n=oe(e,0);if("string"!=typeof n)continue;const o="Property"!==e.name,s=oe(e,1),r=oe(e,o?3:2);t.push({name:n,type:"string"==typeof s?s:"",flags:"string"==typeof r?r:"",values:e.properties.slice(o?4:3).map(e=>e.value)})}return t}function pe(e){const t={};let n=!1;for(const o of fe(e)){if(!o.flags.includes("U"))continue;const e=_e(o.values,o.type);void 0!==e&&(t[o.name]=e,n=!0)}return n?t:void 0}const me=new Set(["Integer","int","Number","double","Float","float","Bool","bool","Enum","enum","Visibility","Roll","Weight","Distance","KTime","Time"]);function _e(e,t){if(0===e.length)return;const n=e[0];if(void 0!==t&&me.has(t)&&("number"==typeof n||"boolean"==typeof n))return n;if(1===e.length)return"string"==typeof n||"number"==typeof n||"boolean"==typeof n?n:void 0;const o=[];for(const t of e)if("number"==typeof t)o.push(t);else{if("boolean"!=typeof t)break;o.push(t?1:0)}return o.length===e.length?o:"string"==typeof n?n:void 0}function ge(e){var t,n,o;const s=oe(e,0);return s?{name:s,propertyType:null!==(t=oe(e,1))&&void 0!==t?t:"",label:null!==(n=oe(e,2))&&void 0!==n?n:"",flags:null!==(o=oe(e,3))&&void 0!==o?o:"",values:e.properties.slice(4).map(e=>e.value)}:null}function ve(e,t){const n=ue(e,t,"Lcl Translation",[0,0,0]),o=ue(e,t,"Lcl Rotation",[0,0,0]),s=ue(e,t,"Lcl Scaling",[1,1,1]);let r=ue(e,t,"PreRotation",[0,0,0]),i=ue(e,t,"PostRotation",[0,0,0]);const a=ue(e,t,"RotationPivot",[0,0,0]),l=ue(e,t,"ScalingPivot",[0,0,0]),u=ue(e,t,"RotationOffset",[0,0,0]),c=ue(e,t,"ScalingOffset",[0,0,0]),d=ue(e,t,"GeometricTranslation",[0,0,0]),h=ue(e,t,"GeometricRotation",[0,0,0]),f=ue(e,t,"GeometricScaling",[1,1,1]);let p=le(e,t,"RotationOrder",0);const m=le(e,t,"InheritType",1),_=le(e,t,"RotationActive",1),g=le(e,t,"RotationSpaceForLimitOnly",0),v=0!==_&&0===g;return v||(p=0,r=[0,0,0],i=[0,0,0]),{translation:n,rotation:o,scale:s,preRotation:r,postRotation:i,rotationPivot:a,scalingPivot:l,rotationOffset:u,scalingOffset:c,geometricTranslation:d,geometricRotation:h,geometricScaling:f,rotationOrder:p,inheritType:m,rotationActive:v,diagnostics:0===m||1===m||2===m?[]:[`InheritType ${m} is unknown; treated as RSrs.`]}}function ye(e,t,n){var o;const s=null!==(o=e.childrenOf.get(t))&&void 0!==o?o:[],r=[];for(const t of s){const o=e.objects.get(t.id);!o||n&&o.name!==n||r.push({id:t.id,node:o,propertyName:t.propertyName})}return r}function be(e){return{name:"Version",properties:[{type:"int32",value:e}],children:[]}}function xe(e,t,n,o,s){return{name:e,properties:[{type:"int64",value:t},{type:"string",value:n},{type:"string",value:o}],children:s}}function Te(e,t,n,o,s,r,i,a,l){e.push({type:s,childId:r,parentId:i,propertyName:a}),t.has(i)||t.set(i,[]),t.get(i).push({id:r,propertyName:a}),n.get(r)&&o.push({reason:"duplicate-parent",message:"FBX object has multiple parents; preserving the existing last-parent behavior.",connectionIndex:l,type:s,childId:r,parentId:i,propertyName:a}),n.set(r,{id:i,propertyName:a})}function Ae(e,t){var n,o;const s=re(null!==(n=oe(e,0))&&void 0!==n?n:e.name),r=null!==(o=oe(e,1))&&void 0!==o?o:"";return Object.assign(Object.assign({},e),{properties:[{type:"int64",value:t},{type:"string",value:s},{type:"string",value:r}]})}function Me(e,t){var n;return{name:"Geometry",properties:[{type:"int64",value:t},{type:"string",value:re(null!==(n=oe(e,0))&&void 0!==n?n:"Geometry")},{type:"string",value:"Mesh"}],children:e.children}}function we(e,t){var n,o,s;const r=re(null!==(n=oe(e,1))&&void 0!==n?n:"Geometry"),i=te(e,"Vertices"),a=i?Fe(Le(i)):new Float64Array(0),l=te(e,"PolygonVertexIndex"),u=[],c=function(e){const t=[];let n=[],o=0;for(let s=0;s<e.length;s++){const r=e[s];r<0?(n.push(-(r+1)),t.push({indices:n,startIndex:o}),n=[],o=s+1):n.push(r)}return t}(l?Ee(Le(l)):new Int32Array(0)),d=function(e,t,n){const o=[];for(let s=0;s<e.length;s++){const r=e[s];o.push(...Se(r,s,t,n))}return o}(c,a,u),h=function(e){const t=[];for(let n=0;n<e.length;n++){const o=e[n];for(let e=0;e<o.indices.length;e++)t.push({polyIndex:n,vertexInPoly:e,controlPointIndex:o.indices[e],globalIndex:o.startIndex+e})}return t}(c),f=te(e,"LayerElementNormal");let p=null;f&&(p=Ie(f,"Normals","NormalsIndex",h,a.length,3,u));const m=e.children.filter(e=>"LayerElementUV"===e.name),_=[];for(const e of m){const t=te(e,"Name"),n=t&&null!==(o=oe(t,0))&&void 0!==o?o:`UVSet${_.length}`,s=Ie(e,"UV","UVIndex",h,a.length,2,u);s&&_.push({name:n,data:s})}const g=_.length>0?_[0].data:null,v=te(e,"LayerElementColor");let y=null;if(v){const e=Ie(v,"Colors","ColorIndex",h,a.length,4,u);if(e){y=new Float32Array(e.length);for(let t=0;t<e.length;t++)y[t]=e[t]}}const b=te(e,"LayerElementTangent"),x=te(e,"LayerElementBinormal"),T=x?Ie(x,"Binormals","BinormalsIndex",h,a.length,3,u):null,A=b?function(e,t,n,o,s,r){const i=function(e,t,n,o,s,r){var i,a,l,u;const c=te(e,"Tangents");if(!c)return 3;const d=Fe(Le(c)),h=null!==(a=oe(null!==(i=te(e,"MappingInformationType"))&&void 0!==i?i:{name:"",properties:[],children:[]},0))&&void 0!==a?a:"",f=null!==(u=oe(null!==(l=te(e,"ReferenceInformationType"))&&void 0!==l?l:{name:"",properties:[],children:[]},0))&&void 0!==u?u:"",p=te(e,"TangentsIndex"),m=p?Ee(Le(p)):null,_="IndexToDirect"===f&&m?Math.max(...Array.from(m),0)+1:"ByControlPoint"===h||"ByVertice"===h?s:"AllSame"===h?1:o.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=Ie(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]:Oe(e,l,o,s)}return l}(b,h,a.length/3,p,T,u):null,M=te(e,"LayerElementMaterial");let w=null;M&&(w=function(e,t){var n,o;const s=te(e,"MappingInformationType"),r=te(e,"ReferenceInformationType");if(!s||!r)return null;const i=null!==(n=oe(s,0))&&void 0!==n?n:"",a=null!==(o=oe(r,0))&&void 0!==o?o:"";if("AllSame"===i){const n=te(e,"Materials"),o=n?Ee(Le(n)):null,s=o&&o.length>0?o[0]:0,r=new Int32Array(t);return 0!==s&&r.fill(s),r}if("ByPolygon"===i){const t=te(e,"Materials");if(!t)return null;const n=Ee(Le(t));if("Direct"===a||"IndexToDirect"===a)return n}return null}(M,c.length));const S=function(e,t,n,o,s,r,i,a,l){const u=n.length,c=new Uint32Array(u),d=[],h=new Map,f=r.length;for(let e=0;e<u;e++){let t=String(n[e].controlPointIndex);o&&(t+=`|${o[3*e]},${o[3*e+1]},${o[3*e+2]}`);for(let n=0;n<f;n++){const o=r[n].data;t+=`|${o[2*e]},${o[2*e+1]}`}i&&(t+=`|${i[4*e]},${i[4*e+1]},${i[4*e+2]},${i[4*e+3]}`),a&&(t+=`|${a[4*e]},${a[4*e+1]},${a[4*e+2]},${a[4*e+3]}`);let s=h.get(t);void 0===s&&(s=d.length,h.set(t,s),d.push(e)),c[e]=s}const p=d.length,m=new Float64Array(3*p),_=new Uint32Array(p),g=(e,t,n)=>{if(!e)return null;const o=new n(p*t);for(let n=0;n<p;n++){const s=d[n]*t;for(let r=0;r<t;r++)o[n*t+r]=e[s+r]}return o};for(let t=0;t<p;t++){const o=n[d[t]].controlPointIndex;m[3*t]=e[3*o],m[3*t+1]=e[3*o+1],m[3*t+2]=e[3*o+2],_[t]=o}const v=3*t.length,y=new Uint32Array(v);for(let e=0;e<t.length;e++)y[3*e]=c[t[e].vertices[0]],y[3*e+1]=c[t[e].vertices[1]],y[3*e+2]=c[t[e].vertices[2]];const b=r.map(e=>({name:e.name,data:g(e.data,2,Float64Array)}));return{positions:m,indices:y,normals:g(o,3,Float64Array),uvs:b.length>0?b[0].data:g(s,2,Float64Array),uvSets:b,colors:g(i,4,Float32Array),tangents:g(a,4,Float64Array),binormals:g(l,3,Float64Array),controlPointIndices:_}}(a,d,h,p,g,_,y,A,T);let C=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=S.indices.length/3;C=new Int32Array(e);for(let e=0;e<d.length;e++)C[e]=null!==(s=w[d[e].polyIndex])&&void 0!==s?s:0}}return{id:t,name:r,positions:S.positions,indices:S.indices,normals:S.normals,uvs:S.uvs,uvSets:S.uvSets,colors:S.colors,tangents:S.tangents,binormals:S.binormals,controlPointIndices:S.controlPointIndices,materialIndices:C,diagnostics:u}}function Se(e,t,n,o){if(e.indices.length<3)return o.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 s=function(e,t){const n=function(e,t){let n=0,o=0,s=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],f=t[a+2];n+=(u-h)*(c+f),o+=(c-f)*(l+d),s+=(l-d)*(u+h)}return[n,o,s]}(e,t),o=Math.abs(n[0]),s=Math.abs(n[1]),r=Math.abs(n[2]);if(o+s+r<1e-12)return null;const i=o>s&&o>r?0:s>r?1:2;return e.indices.map(e=>{const o=t[3*e],s=t[3*e+1],r=t[3*e+2];return 0===i?n[0]>=0?[s,r]:[r,s]:1===i?n[1]>=0?[r,o]:[o,r]:n[2]>=0?[o,s]:[s,o]})}(e,n);if(!s)return o.push({type:"degenerate-polygon",message:`Polygon ${t} has a near-zero normal; using fan triangulation.`,polygonIndex:t}),Ce(e,t);const r=function(e){let t=0;for(let n=0;n<e.length;n++){const o=e[n],s=e[(n+1)%e.length];t+=o[0]*s[1]-s[0]*o[1]}return t/2}(s);if(Math.abs(r)<1e-12)return o.push({type:"degenerate-polygon",message:`Polygon ${t} projects to near-zero area; using fan triangulation.`,polygonIndex:t}),Ce(e,t);const i=function(e,t,n){const o=e.length,s=new Int32Array(o),r=new Int32Array(o);for(let e=0;e<o;e++)s[e]=(e+o-1)%o,r[e]=(e+1)%o;const i=1e-12*Math.abs(n)+1e-300,a=t?1:-1,l=t=>a*Re(e[s[t]],e[t],e[r[t]]),u=new Uint8Array(o);for(let e=0;e<o;e++)u[e]=l(e)<-i?1:0;const c=(e,t,n,o)=>a*Re(t,n,e)>=-i&&a*Re(n,o,e)>=-i&&a*Re(o,t,e)>=-i,d=[];let h=o,f=0,p=0;for(;h>3;){const t=s[f],n=r[f];let o=!1;if(!u[f])if(l(f)<=i)o=!0,d.push([t,f,n]);else{o=!0;for(let s=r[n];s!==t;s=r[s])if(u[s]&&c(e[s],e[t],e[f],e[n])){o=!1;break}o&&d.push([t,f,n])}if(o)r[t]=n,s[n]=t,h--,u[t]=l(t)<-i?1:0,u[n]=l(n)<-i?1:0,f=n,p=0;else if(f=n,++p>h)return null}const m=f;return d.push([s[m],m,r[m]]),d}(s,r>0,r);return i?i.map(([n,o,s])=>({vertices:[e.startIndex+n,e.startIndex+o,e.startIndex+s],polyIndex:t})):(o.push({type:"triangulation-fallback",message:`Polygon ${t} could not be fully ear-clipped; using fan triangulation.`,polygonIndex:t}),Ce(e,t))}function Ce(e,t){const n=[];for(let o=1;o<e.indices.length-1;o++)n.push({vertices:[e.startIndex,e.startIndex+o,e.startIndex+o+1],polyIndex:t});return n}function Re(e,t,n){return(t[0]-e[0])*(n[1]-e[1])-(t[1]-e[1])*(n[0]-e[0])}function Ie(e,t,n,o,s,r,i){var a,l;const u=te(e,"MappingInformationType"),c=te(e,"ReferenceInformationType");if(!u||!c)return null;const d=null!==(a=oe(u,0))&&void 0!==a?a:"",h=null!==(l=oe(c,0))&&void 0!==l?l:"",f=te(e,t);if(!f)return null;const p=Fe(Le(f));let m=null;if("IndexToDirect"===h){const t=te(e,n);t&&(m=Ee(Le(t)))}const _=new Float64Array(o.length*r);for(let t=0;t<o.length;t++){const n=o[t];let s;s="ByPolygonVertex"===d?"IndexToDirect"===h&&m?m[n.globalIndex]:n.globalIndex:"ByControlPoint"===d||"ByVertice"===d?"IndexToDirect"===h&&m?m[n.controlPointIndex]:n.controlPointIndex:"ByPolygon"===d?"IndexToDirect"===h&&m?m[n.polyIndex]:n.polyIndex:"AllSame"===d?0:n.globalIndex;for(let n=0;n<r;n++){const o=s*r+n;s<0||o>=p.length?(i.push({type:o>=p.length?"layer-data-too-short":"layer-index-out-of-bounds",message:`Layer '${e.name}' references unavailable element ${s}.`,layerName:e.name,index:s}),_[t*r+n]=0):_[t*r+n]=p[o]}}return _}function Oe(e,t,n,o){if(!n||!o)return 1;const s=4*e,r=3*e,i=n[r],a=n[r+1],l=n[r+2],u=t[s],c=t[s+1],d=t[s+2];return(a*d-l*c)*o[r]+(l*u-i*d)*o[r+1]+(i*c-a*u)*o[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||e instanceof Uint8Array)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 Ee(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||e instanceof Uint8Array){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 Le(e){var t;return null!==(t=se(e))&&void 0!==t?t:new Float64Array(0)}function Ne(e){return"Closed"===e?"closed":"Periodic"===e?"periodic":"open"}function ke(e,t,n){const o={order:e,topology:Ne(t),knots:n,tMin:0,tMax:0,spans:new Float64Array(0),valid:!1};if(e>1&&e<=128){const t=e-1;if(n.length>=2*t+1){o.tMin=n[t],o.tMax=n[n.length-t-1];const e=n.length-2*t,s=[];let r=-1/0;for(let o=0;o<e;o++){const e=n[t+o];e!==r&&(s.push(e),r=e)}o.spans=Float64Array.from(s),o.valid=!0;for(let e=1;e<n.length;e++)if(!(n[e-1]<=n[e])){o.valid=!1;break}}}return o}function Be(e,t,n,o){if(t<0||t>=e.length||e.length-t<n)return 0;const s=e[t],r=e[t+n];return s>=r||o<=s?0:o>=r?1:(o-s)/(r-s)}function Pe(e,t,n){if(t<0||t>=e.length||e.length-t<n)return 0;const o=e[t],s=e[t+n];return o>=s?0:n/(s-o)}function De(e,t,n,o){if(e.order<=1||!e.valid)return-1;const s=e.order-1,r=e.knots;let i;if(t<=e.tMin)i=s,t=e.tMin;else if(t>=e.tMax)i=r.length-s-2,t=e.tMax;else{let e=0,n=r.length-1;for(;e<n;){const o=e+n>>1;r[o+1]<=t?e=o+1:n=o}if(!(r[e]<=t&&t<r[e+1]))return-1;i=e}if(i<s)return-1;n[0]=1;for(let e=1;e<=s;e++){let a=0,l=1-Be(r,i-e+1,e,t),u=0;const c=null!==o&&e===s;c&&(u=Pe(r,i-e+1,e));for(let s=e;s>0;s--){const d=Be(r,i-e+s,e,t),h=n[s-1];if(n[s]=d*h+l*a,c){const t=Pe(r,i-e+s,e);o[s]=t*h-u*a,u=t}a=h,l=1-d}n[0]=l*a,c&&(o[0]=-u*a)}return i-s}function Ve(e,t,n,o,s){const r=De(e.basis,t,o,s);if(r<0||0===e.numControlPoints)return!1;const i=e.basis.order;let a=0,l=0,u=0,c=0,d=0,h=0,f=0,p=0;const m=e.controlPoints;for(let t=0;t<i;t++){const n=(r+t)%e.numControlPoints*4,i=o[t]*m[n+3],_=s[t]*m[n+3];a+=m[n]*i,l+=m[n+1]*i,u+=m[n+2]*i,c+=i,d+=m[n]*_,h+=m[n+1]*_,f+=m[n+2]*_,p+=_}const _=0!==c?1/c:0;return n[0]=a*_,n[1]=l*_,n[2]=u*_,n[3]=(d-p*n[0])*_,n[4]=(h-p*n[1])*_,n[5]=(f-p*n[2])*_,!0}function Ge(e,t,n,o,s){const r=De(e.basisU,t,s.wu,s.du),i=De(e.basisV,n,s.wv,s.dv);if(r<0||i<0||0===e.numU||0===e.numV)return!1;const a=e.basisU.order,l=e.basisV.order,u=e.controlPoints;let c=0,d=0,h=0,f=0,p=0,m=0,_=0,g=0,v=0,y=0,b=0,x=0;for(let t=0;t<l;t++){const n=(i+t)%e.numV,o=s.wv[t],l=s.dv[t];for(let t=0;t<a;t++){const i=(r+t)%e.numU,a=s.wu[t],T=s.du[t],A=4*(n*e.numU+i),M=u[A+3],w=a*o*M,S=T*o*M,C=l*a*M,R=u[A],I=u[A+1],O=u[A+2];c+=R*w,d+=I*w,h+=O*w,f+=w,p+=R*S,m+=I*S,_+=O*S,g+=S,v+=R*C,y+=I*C,b+=O*C,x+=C}}const T=0!==f?1/f:0;return o[0]=c*T,o[1]=d*T,o[2]=h*T,o[3]=(p-g*o[0])*T,o[4]=(m-g*o[1])*T,o[5]=(_-g*o[2])*T,o[6]=(v-x*o[0])*T,o[7]=(y-x*o[1])*T,o[8]=(b-x*o[2])*T,!0}function $e(e,t){return void 0!==t&&Number.isFinite(t)&&t>0?Math.min(64,Math.max(1,Math.floor(t))):e>0?Math.min(16,Math.floor(e)):4}function Ue(e,t){const n=te(e,t);if(!n)return null;const o=se(n);return o?o instanceof Float64Array?o:Float64Array.from(o):null}function He(e){const t=fe(e).find(e=>"Color"===e.name);return t&&"number"==typeof t.values[0]&&"number"==typeof t.values[1]&&"number"==typeof t.values[2]?[t.values[0],t.values[1],t.values[2]]:null}function Ke(e,t,n){var o;const s=re(null!==(o=oe(e,1))&&void 0!==o?o:"NurbsSurface"),r=function(e){var t,n,o,s,r,i;const a=te(e,"NurbsSurfaceOrder"),l=te(e,"Dimensions"),u=te(e,"Step"),c=te(e,"Form"),d=te(e,"FlipNormals"),h=a&&null!==(t=oe(a,0))&&void 0!==t?t:0,f=a&&null!==(n=oe(a,1))&&void 0!==n?n:0,p=l&&null!==(o=oe(l,0))&&void 0!==o?o:0,m=l&&null!==(s=oe(l,1))&&void 0!==s?s:0,_=u&&null!==(r=oe(u,0))&&void 0!==r?r:0,g=u&&null!==(i=oe(u,1))&&void 0!==i?i:0,v=c?oe(c,0):void 0,y=c?oe(c,1):void 0,b=d?oe(d,0):0,x=Ue(e,"Points"),T=Ue(e,"KnotVectorU"),A=Ue(e,"KnotVectorV");return!x||!T||!A||x.length%4!=0||x.length/4!==p*m||p<=0||m<=0?null:{basisU:ke(h,v,T),basisV:ke(f,y,A),numU:p,numV:m,controlPoints:x,flipNormals:!0===b||1===b,stepU:"number"==typeof _?_:0,stepV:"number"==typeof g?g:0}}(e),i=[];if(!r)return null;const a=function(e,t,n){const o=e.basisU,s=e.basisV;if(!o.valid||!s.valid||0===e.numU||0===e.numV||o.spans.length<2||s.spans.length<2)return null;const r="open"===o.topology,i="open"===s.topology,a=o.spans.length,l=s.spans.length,u=(a-1)*t,c=(l-1)*n,d=a+(a-1)*(t-1),h=d*(l+(l-1)*(n-1));if(h>1073741823||u*c>1073741823)return null;const f=new Uint32Array(h),p=new Float64Array(3*h);let m=0;const _=new Float64Array(2*h),g={wu:new Float64Array(o.order+1),wv:new Float64Array(s.order+1),du:new Float64Array(o.order+1),dv:new Float64Array(s.order+1)},v=new Float64Array(9);for(let u=0;u<l;u++){const c=u+1===l?1:n;for(let h=0;h<c;h++){const y=u*n+h;let b=s.spans[u];if(h>0){const e=h/c;b=b*(1-e)+e*s.spans[u+1]}const x=b;u+1!==l||i||(b=s.spans[0]);for(let n=0;n<a;n++){const s=n+1===a?1:t;for(let i=0;i<s;i++){const c=n*t+i;let T=o.spans[n];if(i>0){const e=i/s;T=T*(1-e)+e*o.spans[n+1]}const A=T;n+1!==a||r||(T=o.spans[0]);let M=0,w=0,S=0;Ge(e,T,b,v,g)&&(M=v[0],w=v[1],S=v[2]);const C=[];(0===u&&(n>0||i>0)||0===n&&(u>0||h>0))&&C.push(0),u+1===l&&(C.push(c),(n>0||i>0)&&C.push(y*d)),n+1===a&&(C.push(y*d),(u>0||h>0)&&C.push(d-1));const R=y*d+c;let I=m;for(const e of C){if(e>=R)continue;const t=f[e],n=p[3*t]-M,o=p[3*t+1]-w,s=p[3*t+2]-S;if(n*n+o*o+s*s<1e-7){I=t;break}}f[R]=I,I===m&&(p[3*I]=M,p[3*I+1]=w,p[3*I+2]=S,m++),_[2*R]=A,_[2*R+1]=x}}}}const y=[],b=[0,0,0,0],x=[0,0,0,0];for(let e=0;e<c;e++)for(let t=0;t<u;t++){b[0]=e*d+t,b[1]=e*d+t+1,b[2]=(e+1)*d+t+1,b[3]=(e+1)*d+t;for(let e=0;e<4;e++)x[e]=f[b[e]];let n=4;for(let e=0;e<4;e++){const t=(e+1)%4;if(x[e]===x[t]){for(let e=t;e<3;e++)b[e]=b[e+1],x[e]=x[e+1];n=3;break}}y.push(b[0],b[1],b[2]),4===n&&y.push(b[0],b[2],b[3])}const T=new Float64Array(3*m);for(let e=0;e<y.length;e+=3){const t=3*f[y[e]],n=3*f[y[e+1]],o=3*f[y[e+2]],s=p[n]-p[t],r=p[n+1]-p[t+1],i=p[n+2]-p[t+2],a=p[o]-p[t],l=p[o+1]-p[t+1],u=p[o+2]-p[t+2],c=r*u-i*l,d=i*a-s*u,h=s*l-r*a;for(const e of[t,n,o])T[e]+=c,T[e+1]+=d,T[e+2]+=h}const A=e.flipNormals?-1:1;for(let e=0;e<m;e++){const t=T[3*e],n=T[3*e+1],o=T[3*e+2],s=Math.hypot(t,n,o);s>0&&(T[3*e]=t/s*A,T[3*e+1]=n/s*A,T[3*e+2]=o/s*A)}const M=new Float64Array(3*h),w=new Float64Array(3*h);for(let e=0;e<h;e++){const t=3*f[e];M[3*e]=p[t],M[3*e+1]=p[t+1],M[3*e+2]=p[t+2],w[3*e]=T[t],w[3*e+1]=T[t+1],w[3*e+2]=T[t+2]}return{positions:M,indices:Uint32Array.from(y),normals:w,uvs:_}}(r,$e(r.stepU,n),$e(r.stepV,n));return a?{id:t,name:s,positions:a.positions,indices:a.indices,normals:a.normals,uvs:a.uvs,uvSets:[{name:"map1",data:a.uvs}],colors:null,tangents:null,binormals:null,controlPointIndices:null,materialIndices:null,diagnostics:i}:(i.push({type:"nurbs-invalid",message:`NURBS surface '${s}' has an invalid basis and was skipped.`}),{id:t,name:s,positions:new Float64Array(0),indices:new Uint32Array(0),normals:null,uvs:null,uvSets:[],colors:null,tangents:null,binormals:null,controlPointIndices:null,materialIndices:null,diagnostics:i})}function We(e,t,n=4){var o;const s=re(null!==(o=oe(e,1))&&void 0!==o?o:"NurbsCurve"),r=[],i=function(e){var t;const n=te(e,"Order"),o=te(e,"Form"),s=n&&null!==(t=oe(n,0))&&void 0!==t?t:0,r=o?oe(o,0):void 0,i=Ue(e,"Points"),a=Ue(e,"KnotVector");return i&&a&&i.length%4==0?{basis:ke(s,r,a),controlPoints:i,numControlPoints:i.length/4}:null}(e),a=i?function(e,t=4){const n=e.basis;if(!n.valid||0===e.numControlPoints||0===n.spans.length)return null;const o=Math.max(1,Math.floor(t)),s=n.spans.length,r=s+(s-1)*(o-1),i=r-("open"===n.topology?0:1),a=new Float64Array(3*r),l=new Float64Array(n.order+1),u=new Float64Array(n.order+1),c=new Float64Array(6);for(let t=0;t<s;t++){const r=t+1===s?1:o;for(let s=0;s<r;s++){const r=t*o+s;if(r<i){let i=n.spans[t];if(s>0){const e=s/o;i=i*(1-e)+e*n.spans[t+1]}Ve(e,i,c,l,u)&&(a[3*r]=c[0],a[3*r+1]=c[1],a[3*r+2]=c[2])}else a[3*r]=a[0],a[3*r+1]=a[1],a[3*r+2]=a[2]}}return a}(i,n):null;return a||r.push({type:"nurbs-invalid",message:`NURBS curve '${s}' has an invalid basis and was skipped.`}),{id:t,name:s,kind:"nurbsCurve",polylines:a?[a]:[],color:He(e),diagnostics:r}}function qe(e,t){var n;const o=re(null!==(n=oe(e,1))&&void 0!==n?n:"Line"),s=[],r=Ue(e,"Points"),i=te(e,"PointsIndex"),a=i?se(i):null,l=[];if(r&&r.length%3==0){const e=r.length/3,t=a?Array.from(a):Array.from({length:e},(e,t)=>t);let n=[];const i=()=>{n.length>=2?l.push(Float64Array.from(n)):1===n.length&&s.push({type:"degenerate-polygon",message:`Line '${o}' has a single-point segment that was skipped.`}),n=[]};for(let a=0;a<t.length;a++){let l=t[a];const u=l<0;u&&(l=~l),l>=0&&l<e?n.push(r[3*l],r[3*l+1],r[3*l+2]):s.push({type:"layer-index-out-of-bounds",message:`Line '${o}' references point ${l} outside its ${e} points.`,index:a}),u&&i()}i()}return{id:t,name:o,kind:"line",polylines:l,color:He(e),diagnostics:s}}const ze=e=>({type:"string",value:e}),je=e=>({type:"float64",value:e}),Xe=e=>({type:"int32",value:e}),Ye=(e,t=[],n=[])=>({name:e,properties:t,children:n});function Qe(e,t,n,...o){return Ye("Property",[ze(e),ze(t),ze(n),...o.map(e=>"string"==typeof e?ze(e):je(e))])}function Ze(e,t,n,...o){return Ye("P",[ze(e),ze(t),ze(""),ze(n),...o.map(e=>"string"==typeof e?ze(e):je(e))])}const Je=(e,t)=>Ye(e,[{type:t instanceof Int32Array?"int32[]":"float64[]",value:t}]);function et(e,t=0){var n;const o=null===(n=null==e?void 0:e.properties[t])||void 0===n?void 0:n.value;return"number"==typeof o?o:"boolean"==typeof o?o?1:0:void 0}function tt(e){if(!e)return[];const t=se(e);return t?Array.from(t):[]}function nt(e){const t=e?se(e):null;return t?t instanceof Float64Array?t:Float64Array.from(t):null}function ot(e){const t=e?se(e):null;return t?t instanceof Int32Array?t:Int32Array.from(t,e=>Math.trunc(e)):null}function st(e,t){if(e)for(const n of e.children){if("Channel"!==n.name)continue;const e=oe(n,0),o="T"===e?"t":"R"===e?"r":"S"===e?"s":void 0;if(!o||t[o])continue;const s=[0,0,0];let r=!1;for(const e of n.children){if("Channel"!==e.name)continue;const t=oe(e,0),n="X"===t?0:"Y"===t?1:"Z"===t?2:-1,o=et(te(e,"Default"));n>=0&&void 0!==o&&(s[n]=o,r=!0)}r&&(t[o]=s)}}function rt(e){const t=te(e,"Key");return!!(t&&t.properties.length>0)||e.children.some(e=>"Channel"===e.name&&rt(e))}function it(e,t){var n;const o=null!==(n=e.usedNames.get(t))&&void 0!==n?n:0;return e.usedNames.set(t,o+1),0===o?t:`${t} (${o+1})`}function at(e,t,n){e.connections.push(Ye("C",[ze("OO"),ze(t),ze(n)]))}function lt(e){const t=new Float64Array(e.length);for(let n=0;n+2<e.length;n+=3){const o=e[n],s=e[n+1],r=e[n+2],i=Math.hypot(o,s,r);i>0&&(t[n]=o/i,t[n+1]=s/i,t[n+2]=r/i)}return t}function ut(e,t){var n,o,s,r,i,a,l;const u=null!==(n=oe(t,0))&&void 0!==n?n:"Model",c=oe(null!==(o=te(t,"Type"))&&void 0!==o?o:Ye("x"),0),d=!!te(t,"Vertices"),h="Light"===c?"Light":"Camera"===c?"Camera":"LimbNode"===c?"LimbNode":d?"Mesh":"Null",f={};st(t.children.find(e=>"Channel"===e.name&&"Transform"===oe(e,0)),f),st(e.takeDefaults.get(u),f);const p=null!==(s=f.t)&&void 0!==s?s:[0,0,0],m=null!==(r=f.r)&&void 0!==r?r:[0,0,0],_=null!==(i=f.s)&&void 0!==i?i:[1,1,1],g=[Qe("Lcl Translation","Lcl Translation","A+",p[0],p[1],p[2]),Qe("Lcl Rotation","Lcl Rotation","A+",m[0],m[1],m[2]),Qe("Lcl Scaling","Lcl Scaling","A+",_[0],_[1],_[2])],v=t.children.find(e=>"Channel"===e.name&&"Visibility"===oe(e,0)),y=et(te(null!=v?v:Ye("x"),"Default"));if(void 0!==y&&y<=0&&g.push(Qe("Visibility","Visibility","A+",0)),"Light"===h)g.push(...function(e){const t=[],n=et(te(e,"LightType"));void 0!==n&&t.push(Qe("LightType","enum","",n));const o=tt(te(e,"Color"));o.length>=3&&t.push(Qe("Color","ColorRGB","",o[0],o[1],o[2]));const s=[["Intensity","Intensity"],["ConeAngle","OuterAngle"],["HotSpot","InnerAngle"]];for(const[n,o]of s){const s=et(te(e,n));void 0!==s&&t.push(Qe(o,"double","",s))}const r=et(te(e,"CastShadows"));return void 0!==r&&t.push(Qe("CastShadows","bool","",r)),t}(t));else if("Camera"===h)g.push(...function(e){const t=[],n=[["Aperture","FieldOfView"],["FieldOfViewXProperty","FieldOfViewX"],["FieldOfViewYProperty","FieldOfViewY"],["SqueezeRatio","FilmSqueezeRatio"],["FocalLength","FocalLength"],["AspectType","AspectRatioMode"],["AspectW","AspectWidth"],["AspectH","AspectHeight"],["ApertureMode","ApertureMode"],["NearPlane","NearPlane"],["FarPlane","FarPlane"],["Roll","Roll"]];for(const[o,s]of n){const n=et(te(e,o));void 0!==n&&t.push(Qe(s,"AspectRatioMode"===s||"ApertureMode"===s?"enum":"double","",n))}const o=tt(te(e,"CameraAperture"));return o.length>=2&&(t.push(Qe("FilmWidth","double","",o[0])),t.push(Qe("FilmHeight","double","",o[1]))),t}(t));else if("LimbNode"===h){const e=et(te(null!==(a=te(t,"Properties"))&&void 0!==a?a:Ye("x"),"Size"));void 0!==e&&g.push(Qe("Size","double","",e))}const b=[Ye("Version",[Xe(232)]),Ye("Properties60",[],g)];for(const e of["Culling","Position","Up","LookAt"]){const n=te(t,e);n&&b.push(n)}"Mesh"===h&&b.push(...function(e,t){var n;const o=nt(te(e,"Vertices")),s=ot(te(e,"PolygonVertexIndex"));if(!o||!s)return[];const r=Math.floor(o.length/3),i=s.length;i>0&&s[i-1]>=0&&(s[i-1]=~s[i-1]);const a=[Ye("GeometryVersion",[Xe(124)]),Je("Vertices",o),Je("PolygonVertexIndex",s)],l=nt(te(e,"Normals"));if(l){const e=Math.floor(l.length/3),n=e===i,o=e!==r||n&&5e3!==t?n?"ByPolygonVertex":void 0:"ByVertice";o&&a.push(Ye("LayerElementNormal",[Xe(0)],[Ye("Version",[Xe(101)]),Ye("Name",[ze("")]),Ye("MappingInformationType",[ze(o)]),Ye("ReferenceInformationType",[ze("Direct")]),Je("Normals",lt(l))]))}const u=te(e,"GeometryUVInfo"),c=u?nt(te(u,"TextureUV")):null;if(u&&c){const e=ot(te(u,"TextureUVVerticeIndex")),t=Math.floor(c.length/2);let n;const o=[Ye("Version",[Xe(101)]),Ye("Name",[ze("")])];e&&e.length===i?n=Ye("LayerElementUV",[Xe(0)],[...o,Ye("MappingInformationType",[ze("ByPolygonVertex")]),Ye("ReferenceInformationType",[ze("IndexToDirect")]),Je("UV",c),Je("UVIndex",e)]):t===i?n=Ye("LayerElementUV",[Xe(0)],[...o,Ye("MappingInformationType",[ze("ByPolygonVertex")]),Ye("ReferenceInformationType",[ze("Direct")]),Je("UV",c)]):t===r&&(n=Ye("LayerElementUV",[Xe(0)],[...o,Ye("MappingInformationType",[ze("ByVertice")]),Ye("ReferenceInformationType",[ze("Direct")]),Je("UV",c)])),n&&a.push(n)}const d=oe(null!==(n=te(e,"MaterialAssignation"))&&void 0!==n?n:Ye("x"),0),h=ot(te(e,"Materials"));if(h&&h.length>0){const e="ByPolygon"===d?"ByPolygon":"AllSame";a.push(Ye("LayerElementMaterial",[Xe(0)],[Ye("Version",[Xe(101)]),Ye("Name",[ze("")]),Ye("MappingInformationType",[ze(e)]),Ye("ReferenceInformationType",[ze("IndexToDirect")]),Je("Materials","AllSame"===e?Int32Array.of(h[0]):h)]))}for(const t of e.children)"Shape"===t.name&&a.push(t);return a}(t,e.version)),e.objects.push(Ye("Model",[ze(u),ze(h)],b)),function(e,t,n){var o;for(const s of t.children){if("Material"!==s.name)continue;const t=null!==(o=oe(s,0))&&void 0!==o?o:"Material",r=it(e,t.includes("::")?t:`Material::${t}`),i=(e,t)=>{const n=tt(te(s,e));return n.length>=3?Qe(t,"ColorRGB","",n[0],n[1],n[2]):null},a=(e,t)=>{const n=et(te(s,e));return void 0!==n?Qe(t,"double","",n):null},l=[i("Ambient","AmbientColor"),i("Diffuse","DiffuseColor"),i("Specular","SpecularColor"),i("Emissive","EmissiveColor"),a("Shininess","Shininess"),a("Alpha","Opacity"),a("Reflectivity","ReflectionFactor")].filter(e=>null!==e),u=te(s,"ShadingModel");e.objects.push(Ye("Material",[ze(r),ze("")],[Ye("Version",[Xe(100)]),null!=u?u:Ye("ShadingModel",[ze("phong")]),Ye("Properties60",[],l)])),at(e,r,n)}}(e,t,u),function(e,t,n){var o;const s=t.children.filter(e=>"Link"===e.name);if(0===s.length)return;const r=it(e,`Deformer::Skin ${re(n)}`);e.objects.push(Ye("Deformer",[ze(r),ze("Skin")],[Ye("Version",[Xe(100)]),Ye("Link_DeformAcuracy",[je(50)])])),at(e,r,n);for(const t of s){const s=null!==(o=oe(t,0))&&void 0!==o?o:"",i=it(e,`SubDeformer::Cluster ${re(n)} ${re(s)}`),a=[Ye("Version",[Xe(100)]),Ye("Mode",[ze("Normalize")])];for(const e of["Indexes","Weights","Transform","TransformLink"]){const n=te(t,e);if(!n)continue;const o="Indexes"===e?ot(n):nt(n);o&&a.push(Je(e,o))}e.objects.push(Ye("Deformer",[ze(i),ze("Cluster")],a)),at(e,i,r),at(e,s,i)}}(e,t,u);const x=te(t,"Children");for(const t of null!==(l=null==x?void 0:x.properties)&&void 0!==l?l:[])"string"==typeof t.value&&at(e,t.value,u)}const ct={Aim:"aim","Parent-Child":"parent","Position From Positions":"position","Rotation From Rotations":"rotation","Scale From Scales":"scale","Single Chain IK":"singleChainIK"};function dt(e,t){return e&&"number"==typeof e[0]&&"number"==typeof e[1]&&"number"==typeof e[2]?[e[0],e[1],e[2]]:t}function ht(e,t){const n=null==e?void 0:e[0];return"number"==typeof n?n:"boolean"==typeof n?n?1:0:t}function ft(e,t,n){var o,s,r,i,a;const l=t.children.find(e=>"Type"===e.name),u=null!==(s=null!==(o=l?oe(l,0):void 0)&&void 0!==o?o:oe(t,2))&&void 0!==s?s:"",c=null!==(r=ct[u])&&void 0!==r?r:"unknown",d=new Map;for(const e of fe(t))d.set(e.name,e.values);const h=(e,t)=>[0!==ht(d.get(`${e}X`),t?1:0),0!==ht(d.get(`${e}Y`),t?1:0),0!==ht(d.get(`${e}Z`),t?1:0)],f={id:e,name:re(null!==(i=oe(t,1))&&void 0!==i?i:"Constraint"),type:c,typeName:u,targets:[],weight:ht(d.get("Weight"),100)/100,active:0!==ht(d.get("Active"),1),affectTranslation:[!0,!0,!0],affectRotation:[!0,!0,!0],affectScale:[!1,!1,!1],offsetTranslation:[0,0,0],offsetRotation:[0,0,0],offsetScale:[1,1,1],aimVector:dt(d.get("AimVector"),[1,0,0]),upVector:dt(d.get("UpVector"),[0,1,0]),worldUpVector:dt(d.get("WorldUpVector"),[0,1,0]),worldUpType:ht(d.get("WorldUpType"),0),ikPoleVector:dt(d.get("PoleVector"),[0,0,0])};switch(c){case"aim":f.affectRotation=h("Affect",!0),f.offsetRotation=dt(d.get("RotationOffset"),[0,0,0]);break;case"parent":f.affectTranslation=h("AffectTranslation",!0),f.affectRotation=h("AffectRotation",!0),f.affectScale=h("AffectScale",!1);break;case"position":f.affectTranslation=h("Affect",!0),f.offsetTranslation=dt(d.get("Translation"),[0,0,0]);break;case"rotation":f.affectRotation=h("Affect",!0),f.offsetRotation=dt(d.get("Rotation"),[0,0,0]);break;case"scale":f.affectScale=h("Affect",!0),f.offsetScale=dt(d.get("Scaling"),[1,1,1])}const p="singleChainIK"===c?1:100;for(const t of n.connections){if(t.parentId!==e||"OP"!==t.type||!t.propertyName)continue;const o=n.objects.get(t.childId);if(!o||"Model"!==o.name)continue;const s=t.propertyName,r=re(null!==(a=oe(o,1))&&void 0!==a?a:"");switch(s){case"Constrained Object":case"Constrained object (Child)":f.nodeId=t.childId;break;case"Source":case"Source (Parent)":case"Aim At Object":case"Pole Vector Object":f.targets.push({modelId:t.childId,weight:ht(d.get(`${r}.Weight`),p)/p,offsetTranslation:dt(d.get(`${r}.Offset T`),[0,0,0]),offsetRotation:dt(d.get(`${r}.Offset R`),[0,0,0]),offsetScale:dt(d.get(`${r}.Offset S`),[1,1,1])});break;case"World Up Object":f.worldUpNodeId=t.childId;break;case"First Joint":f.ikFirstJointId=t.childId;break;case"End Joint":f.ikEndJointId=t.childId;break;case"Effector":f.ikEffectorId=t.childId}}return f}var pt,mt,_t;!function(e){e[e.DefaultW1=1]="DefaultW1",e[e.WidenToRgb=2]="WidenToRgb",e[e.MultiplyValue=4]="MultiplyValue"}(pt||(pt={})),function(e){e[e.None=0]="None",e[e.InvertX=1]="InvertX",e[e.UnknownShininess=2]="UnknownShininess"}(mt||(mt={})),function(e){e[e.Inverted=1]="Inverted",e[e.IfExists=2]="IfExists",e[e.IfTexture=4]="IfTexture",e[e.IfAround1=8]="IfAround1"}(_t||(_t={}));const gt=[["diffuseColor",1,0,"Diffuse"],["diffuseColor",1,0,"DiffuseColor"],["diffuseFactor",0,0,"DiffuseFactor"],["specularColor",1,0,"Specular"],["specularColor",1,0,"SpecularColor"],["specularFactor",0,0,"SpecularFactor"],["specularExponent",0,0,"Shininess"],["specularExponent",0,0,"ShininessExponent"],["reflectionColor",1,0,"Reflection"],["reflectionColor",1,0,"ReflectionColor"],["reflectionFactor",0,0,"ReflectionFactor"],["transparencyColor",1,0,"Transparent"],["transparencyColor",1,0,"TransparentColor"],["transparencyFactor",0,0,"TransparentFactor"],["transparencyFactor",0,0,"TransparencyFactor"],["emissionColor",1,0,"Emissive"],["emissionColor",1,0,"EmissiveColor"],["emissionFactor",0,0,"EmissiveFactor"],["ambientColor",1,0,"Ambient"],["ambientColor",1,0,"AmbientColor"],["ambientFactor",0,0,"AmbientFactor"],["normalMap",0,0,"NormalMap"],["bump",0,0,"Bump"],["bumpFactor",0,0,"BumpFactor"],["displacement",0,0,"Displacement"],["displacementFactor",0,0,"DisplacementFactor"],["vectorDisplacement",0,0,"VectorDisplacement"],["vectorDisplacementFactor",0,0,"VectorDisplacementFactor"]],vt=[["baseColor",1,0,"Diffuse"],["baseColor",1,0,"DiffuseColor"],["baseFactor",0,0,"DiffuseFactor"],["specularColor",1,0,"Specular"],["specularColor",1,0,"SpecularColor"],["specularFactor",0,0,"SpecularFactor"],["roughness",0,2,"Shininess"],["roughness",0,2,"ShininessExponent"],["transmissionColor",1,0,"Transparent"],["transmissionColor",1,0,"TransparentColor"],["transmissionFactor",0,0,"TransparentFactor"],["transmissionFactor",0,0,"TransparencyFactor"],["emissionColor",1,0,"Emissive"],["emissionColor",1,0,"EmissiveColor"],["emissionFactor",0,0,"EmissiveFactor"],["normalMap",0,0,"NormalMap"]],yt=[["roughnessAsGlossiness",8,"useGlossiness"]],bt=["pbr","metalness","diffuse","specular","coat","sheen","transmission","opacity","ior","diffuseRoughness"],xt={unknown:{maps:vt,features:[],defaultFeatures:["diffuse","specular","emission","transmission"]},fbxLambert:{maps:[["baseColor",1,0,"Diffuse"],["baseColor",1,0,"DiffuseColor"],["baseFactor",0,0,"DiffuseFactor"],["transmissionColor",1,0,"Transparent"],["transmissionColor",1,0,"TransparentColor"],["transmissionFactor",0,0,"TransparentFactor"],["transmissionFactor",0,0,"TransparencyFactor"],["emissionColor",1,0,"Emissive"],["emissionColor",1,0,"EmissiveColor"],["emissionFactor",0,0,"EmissiveFactor"],["normalMap",0,0,"NormalMap"]],features:[],defaultFeatures:["diffuse","emission","transmission"]},fbxPhong:{maps:vt,features:[],defaultFeatures:["diffuse","specular","emission","transmission"]},oslStandardSurface:{maps:[["baseFactor",0,0,"base"],["baseColor",1,0,"base_color"],["roughness",0,0,"specular_roughness"],["diffuseRoughness",0,0,"diffuse_roughness"],["metalness",0,0,"metalness"],["specularFactor",0,0,"specular"],["specularColor",1,0,"specular_color"],["specularIor",0,0,"specular_IOR"],["specularAnisotropy",0,0,"specular_anisotropy"],["specularRotation",0,0,"specular_rotation"],["transmissionFactor",0,0,"transmission"],["transmissionColor",1,0,"transmission_color"],["transmissionDepth",0,0,"transmission_depth"],["transmissionScatter",2,0,"transmission_scatter"],["transmissionScatterAnisotropy",0,0,"transmission_scatter_anisotropy"],["transmissionDispersion",0,0,"transmission_dispersion"],["transmissionExtraRoughness",0,0,"transmission_extra_roughness"],["subsurfaceFactor",0,0,"subsurface"],["subsurfaceColor",1,0,"subsurface_color"],["subsurfaceRadius",2,0,"subsurface_radius"],["subsurfaceScale",0,0,"subsurface_scale"],["subsurfaceAnisotropy",0,0,"subsurface_anisotropy"],["sheenFactor",0,0,"sheen"],["sheenColor",1,0,"sheen_color"],["sheenRoughness",0,0,"sheen_roughness"],["coatFactor",0,0,"coat"],["coatColor",1,0,"coat_color"],["coatRoughness",0,0,"coat_roughness"],["coatIor",0,0,"coat_IOR"],["coatAnisotropy",0,0,"coat_anisotropy"],["coatRotation",0,0,"coat_rotation"],["coatNormal",0,0,"coat_normal"],["coatAffectBaseColor",1,0,"coat_affect_color"],["coatAffectBaseRoughness",0,0,"coat_affect_roughness"],["thinFilmThickness",0,0,"thin_film_thickness"],["thinFilmIor",0,0,"thin_film_IOR"],["emissionFactor",0,0,"emission"],["emissionColor",1,0,"emission_color"],["opacity",2,0,"opacity"],["normalMap",0,0,"NormalMap"],["normalMap",0,0,"normalCamera"],["tangentMap",0,0,"tangent"]],features:[["thinWalled",0,"thin_walled"]],defaultFeatures:bt},arnoldStandardSurface:{maps:[["baseFactor",0,0,"base"],["baseColor",1,0,"baseColor"],["roughness",0,0,"specularRoughness"],["diffuseRoughness",0,0,"diffuseRoughness"],["metalness",0,0,"metalness"],["specularFactor",0,0,"specular"],["specularColor",1,0,"specularColor"],["specularIor",0,0,"specularIOR"],["specularAnisotropy",0,0,"specularAnisotropy"],["specularRotation",0,0,"specularRotation"],["transmissionFactor",0,0,"transmission"],["transmissionColor",1,0,"transmissionColor"],["transmissionDepth",0,0,"transmissionDepth"],["transmissionScatter",2,0,"transmissionScatter"],["transmissionScatterAnisotropy",0,0,"transmissionScatterAnisotropy"],["transmissionDispersion",0,0,"transmissionDispersion"],["transmissionExtraRoughness",0,0,"transmissionExtraRoughness"],["subsurfaceFactor",0,0,"subsurface"],["subsurfaceColor",1,0,"subsurfaceColor"],["subsurfaceRadius",2,0,"subsurfaceRadius"],["subsurfaceScale",0,0,"subsurfaceScale"],["subsurfaceAnisotropy",0,0,"subsurfaceAnisotropy"],["sheenFactor",0,0,"sheen"],["sheenColor",1,0,"sheenColor"],["sheenRoughness",0,0,"sheenRoughness"],["coatFactor",0,0,"coat"],["coatColor",1,0,"coatColor"],["coatRoughness",0,0,"coatRoughness"],["coatIor",0,0,"coatIOR"],["coatAnisotropy",0,0,"coatAnisotropy"],["coatRotation",0,0,"coatRotation"],["coatNormal",0,0,"coatNormal"],["thinFilmThickness",0,0,"thinFilmThickness"],["thinFilmIor",0,0,"thinFilmIOR"],["emissionFactor",0,0,"emission"],["emissionColor",1,0,"emissionColor"],["opacity",2,0,"opacity"],["indirectDiffuse",0,0,"indirectDiffuse"],["indirectSpecular",0,0,"indirectSpecular"],["normalMap",0,0,"NormalMap"],["normalMap",0,0,"normalCamera"],["tangentMap",0,0,"tangent"],["matteColor",1,0,"aiMatteColor"],["matteFactor",0,0,"aiMatteColorA"],["subsurfaceType",0,0,"subsurfaceType"],["transmissionPriority",0,0,"dielectricPriority"],["transmissionEnableInAov",0,0,"transmitAovs"]],features:[["matte",0,"aiEnableMatte"],["thinWalled",0,"thinWalled"],["caustics",0,"caustics"],["internalReflections",0,"internalReflections"],["exitToBackground",0,"exitToBackground"]],defaultFeatures:bt},"3dsMaxPhysicalMaterial":{maps:[["baseFactor",0,0,"base_weight"],["baseColor",1,0,"base_color"],["roughness",0,0,"roughness"],["diffuseRoughness",0,0,"diff_rough"],["diffuseRoughness",0,0,"diff_roughness"],["metalness",0,0,"metalness"],["specularFactor",0,0,"reflectivity"],["specularColor",1,0,"refl_color"],["specularAnisotropy",0,0,"anisotropy"],["specularRotation",0,0,"aniso_angle"],["specularRotation",0,0,"anisoangle"],["specularIor",0,0,"trans_ior"],["transmissionFactor",0,0,"transparency"],["transmissionColor",1,0,"trans_color"],["transmissionDepth",0,0,"trans_depth"],["transmissionRoughness",0,0,"trans_rough"],["transmissionRoughness",0,0,"trans_roughness"],["subsurfaceFactor",0,0,"scattering"],["subsurfaceTintColor",1,0,"sss_color"],["subsurfaceColor",1,0,"sss_scatter_color"],["subsurfaceRadius",2,0,"sss_depth"],["subsurfaceScale",0,0,"sss_scale"],["coatFactor",0,0,"coat"],["coatFactor",0,0,"coating"],["coatColor",1,0,"coat_color"],["coatRoughness",0,0,"coat_rough"],["coatRoughness",0,0,"coat_roughness"],["coatIor",0,0,"coat_ior"],["coatNormal",0,0,"coat_bump"],["coatNormal",0,0,"clearcoat_bump_map_amt"],["coatAffectBaseColor",1,0,"coat_affect_color"],["coatAffectBaseRoughness",0,0,"coat_affect_roughness"],["emissionFactor",0,0,"emission"],["emissionColor",1,0,"emit_color"],["opacity",2,0,"cutout"],["normalMap",0,0,"bump"],["normalMap",0,0,"bump_map_amt"],["displacementMap",0,0,"displacement"],["displacementMap",0,0,"displacement_map_amt"],["subsurfaceType",0,0,"subsurfaceType"]],features:[["thinWalled",0,"thin_walled"],["specular",0,"material_mode"],["diffuseRoughness",0,"material_mode"],["transmissionRoughness",1,"trans_roughness_lock"],["roughnessAsGlossiness",0,"roughness_inv"],["transmissionRoughnessAsGlossiness",0,"trans_roughness_inv"],["coatRoughnessAsGlossiness",0,"coat_roughness_inv"]],defaultFeatures:["pbr","metalness","diffuse","coat","sheen","transmission","opacity","ior"],textureSuffix:"_map",textureEnabledSuffix:"_map_on"},"3dsMaxPbrMetalRough":{maps:[["baseColor",1,0,"base_color"],["baseColor",1,0,"baseColor"],["roughness",0,0,"roughness"],["roughness",0,0,"Roughness_Map"],["metalness",0,0,"metalness"],["ambientOcclusion",0,0,"ao"],["normalMap",0,0,"norm"],["emissionColor",1,0,"emit_color"],["displacementMap",0,0,"displacement"],["displacementMap",0,0,"displacement_amt"],["opacity",2,0,"opacity"]],features:yt,defaultFeatures:["pbr","metalness","diffuse","opacity"],textureSuffix:"_map"},"3dsMaxPbrSpecGloss":{maps:[["baseColor",1,0,"base_color"],["baseColor",1,0,"baseColor"],["specularColor",1,0,"Specular"],["specularColor",1,0,"specular"],["roughness",0,0,"glossiness"],["ambientOcclusion",0,0,"ao"],["normalMap",0,0,"norm"],["emissionColor",1,0,"emit_color"],["displacementMap",0,0,"displacement"],["displacementMap",0,0,"displacement_amt"],["opacity",2,0,"opacity"]],features:yt,defaultFeatures:["pbr","specular","diffuse","opacity"],textureSuffix:"_map"},gltfMaterial:{maps:[["baseColor",1,0,"main|baseColor"],["roughness",0,0,"main|roughness"],["metalness",0,0,"main|metalness"],["normalMap",0,0,"main|normal"],["ambientOcclusion",0,0,"main|ambientOcclusion"],["emissionColor",1,0,"main|emission"],["emissionColor",1,0,"main|emissionColor"],["opacity",2,0,"main|Alpha"],["coatFactor",0,0,"extension|clearcoat"],["coatRoughness",0,0,"extension|clearcoatRoughness"],["coatNormal",0,0,"extension|clearcoatNormal"],["sheenColor",1,0,"extension|sheenColor"],["sheenRoughness",0,0,"extension|sheenRoughness"],["specularFactor",0,0,"extension|specular"],["specularFactor",0,0,"extension|Specular"],["specularColor",1,0,"extension|specularcolor"],["specularColor",1,0,"extension|specularColor"],["transmissionFactor",0,0,"extension|transmission"],["specularIor",0,0,"extension|indexOfRefraction"]],features:[["doubleSided",0,"main|DoubleSided"],["sheen",0,"extension|enableSheen"],["coat",0,"extension|enableClearCoat"],["transmission",0,"extension|enableTransmission"],["ior",0,"extension|enableIndexOfRefraction"],["specular",0,"extension|enableSpecular"],["unlit",0,"extension|unlit"]],defaultFeatures:["pbr","metalness","diffuse","emission","opacity","ambientOcclusion"],textureSuffix:"Map"},openPbrMaterial:{maps:[["baseFactor",0,0,"base_weight"],["baseColor",1,0,"base_color"],["roughness",0,0,"specular_roughness"],["diffuseRoughness",0,0,"base_diffuse_roughness"],["metalness",0,0,"base_metalness"],["specularFactor",0,0,"specular_weight"],["specularColor",1,0,"specular_color"],["specularAnisotropy",0,0,"specular_roughness_anisotropy"],["specularIor",0,0,"specular_ior"],["transmissionFactor",0,0,"transmission_weight"],["transmissionColor",1,0,"transmission_color"],["transmissionDepth",0,0,"transmission_depth"],["transmissionScatter",2,0,"transmission_scatter"],["transmissionScatterAnisotropy",0,0,"transmission_scatter_anisotropy"],["transmissionDispersion",0,0,"transmission_dispersion_scale"],["subsurfaceFactor",0,0,"subsurface_weight"],["subsurfaceColor",1,0,"subsurface_color"],["subsurfaceRadius",2,0,"subsurface_radius_scale"],["subsurfaceScale",0,0,"subsurface_radius"],["subsurfaceAnisotropy",0,0,"subsurface_scatter_anisotropy"],["coatFactor",0,0,"coat_weight"],["coatColor",1,0,"coat_color"],["coatRoughness",0,0,"coat_roughness"],["coatAnisotropy",0,0,"coat_roughness_anisotropy"],["coatIor",0,0,"coat_ior"],["coatNormal",0,0,"coat_normal_map"],["sheenFactor",0,0,"fuzz_weight"],["sheenColor",1,0,"fuzz_color"],["sheenRoughness",0,0,"fuzz_roughness"],["emissionFactor",0,0,"emission_weight"],["emissionFactor",4,0,"emission_luminance"],["emissionColor",1,0,"emission_color"],["thinFilmFactor",0,0,"thin_film_weight"],["thinFilmThickness",0,0,"thin_film_thickness"],["thinFilmIor",0,0,"thin_film_ior"],["normalMap",0,0,"bump"],["normalMap",0,0,"bump_map_amt"],["displacementMap",0,0,"displacement"],["displacementMap",0,0,"displacement_map_amt"],["coatNormal",0,0,"coat_bump"],["coatNormal",0,0,"coat_bump_map_amt"],["tangentMap",0,0,"geometry_tangent_map"],["opacity",2,0,"geometry_opacity"]],features:[["thinWalled",0,"geometry_thin_walled"]],defaultFeatures:bt,textureSuffix:"_map",textureEnabledSuffix:"_map_on"},shaderFxGraph:{maps:[["baseColor",1,0,"color"],["baseColor",1,0,"base_color"],["roughness",0,0,"roughness"],["metalness",0,0,"metallic"],["normalMap",0,0,"normal"],["emissionFactor",0,0,"emissive_intensity"],["emissionColor",1,0,"emissive"],["ambientOcclusion",0,0,"ao"]],features:[],defaultFeatures:["pbr","metalness","diffuse","emission","ambientOcclusion"],texturePrefix:"TEX_",textureSuffix:"_map",textureEnabledPrefix:"use_",textureEnabledSuffix:"_map"}};function Tt(e){return"unknown"!==e&&"fbxLambert"!==e&&"fbxPhong"!==e}function At(e,t){switch(e){case 1:t[0]=1-t[0];break;case 2:t[0]>=0&&(t[0]=1-.1*Math.sqrt(t[0]),t[0]<0&&(t[0]=0))}}function Mt(e){const t=[];for(const n of e)if("number"==typeof n)t.push(n);else{if("boolean"!=typeof n)break;t.push(n?1:0)}return t}function wt(e){var t,n,o,s,r,i,a,l,u,c;const{shaderType:d,shaderPropPrefix:h}=function(e){var t,n,o,s,r,i;let a="unknown";const l=e.shadingModelName.toLowerCase();if("lambert"===l?a="fbxLambert":"phong"===l&&(a="fbxPhong"),e.shader)switch(e.shader.renderApi){case"ARNOLD_SHADER_ID":return{shaderType:"arnoldStandardSurface",shaderPropPrefix:""};case"OSL":return{shaderType:"oslStandardSurface",shaderPropPrefix:""};case"SFX_PBS_SHADER":return{shaderType:"shaderFxGraph",shaderPropPrefix:""};default:return{shaderType:"unknown",shaderPropPrefix:""}}if("unknown"===a){const a=(null!==(o=Mt(null!==(n=null===(t=e.props.get("3dsMax|ClassIDa"))||void 0===t?void 0:t.values)&&void 0!==n?n:[])[0])&&void 0!==o?o:0)>>>0,l=(null!==(i=Mt(null!==(r=null===(s=e.props.get("3dsMax|ClassIDb"))||void 0===s?void 0:s.values)&&void 0!==r?r:[])[0])&&void 0!==i?i:0)>>>0;if(1030429932===a&&3735928833===l)return{shaderType:"3dsMaxPhysicalMaterial",shaderPropPrefix:"3dsMax|Parameters|"};if(4048887347===a&&939201335===l)return{shaderType:"openPbrMaterial",shaderPropPrefix:"3dsMax|Parameters|"};if(943849874===a&&1174294043===l)return{shaderType:"gltfMaterial",shaderPropPrefix:"3dsMax|"};if(3490651648===a&&3195528448===l)return{shaderType:"3dsMaxPbrMetalRough",shaderPropPrefix:"3dsMax|main|"};if(3490651648===a&&31173939===l)return{shaderType:"3dsMaxPbrSpecGloss",shaderPropPrefix:"3dsMax|main|"}}return{shaderType:a,shaderPropPrefix:""}}(e),f=xt[d],p={shaderType:d,shaderPropPrefix:h,fbx:{},pbr:{},features:{}};for(const e of f.defaultFeatures)p.features[e]={enabled:!0,explicit:!1};const m=t=>{var n;const o=null===(n=e.shader)||void 0===n?void 0:n.bindings.get(t);return o&&o.length>0?o:[t]},_=e.shader?"":h,g=(t,n,o,s,r,i,a)=>{var l,u,c,d,h;for(const[f,p,g,v]of t){const t=_+o+v+s;for(const o of m(t)){const t=e.props.get(o),s=null!==(l=n[f])&&void 0!==l?l:n[f]={valueComponents:0,textureEnabled:!1};if(r&&t&&"Reference"!==t.type){const e=Mt(t.values);if(e.length>0){const t=e.slice(0,4);4&p?(t[0]*=null!==(c=null===(u=s.value)||void 0===u?void 0:u[0])&&void 0!==c?c:1,s.value=[t[0],...null!==(h=null===(d=s.value)||void 0===d?void 0:d.slice(1))&&void 0!==h?h:[]]):s.value=t,At(g,s.value);const n=e.length>=4?4:3===e.length?3:2===e.length?2:1;1&p&&n<4&&(s.value[3]=1),2&p&&1===n&&(s.value[1]=s.value[0],s.value[2]=s.value[0]),s.valueComponents=n}}if(i){const t=e.texturesByProp.get(o);t&&(s.texture=t,s.textureEnabled=!0)}if(a&&t){const e=Mt(t.values);e.length>0&&(s.textureEnabled=0!==e[0])}}}};g(gt,p.fbx,"","",!0,!0,!1),(f.texturePrefix||f.textureSuffix)&&g(f.maps,p.pbr,null!==(t=f.texturePrefix)&&void 0!==t?t:"",null!==(n=f.textureSuffix)&&void 0!==n?n:"",!1,!0,!1),g(f.maps,p.pbr,"","",!0,!0,!1),(f.textureEnabledPrefix||f.textureEnabledSuffix)&&g(f.maps,p.pbr,null!==(o=f.textureEnabledPrefix)&&void 0!==o?o:"",null!==(s=f.textureEnabledSuffix)&&void 0!==s?s:"",!1,!1,!0);for(const[t,n,o]of f.features){const s=_+o;for(const o of m(s)){const s=e.props.get(o),i=null!==(r=(c=p.features)[t])&&void 0!==r?r:c[t]={enabled:!1,explicit:!1};if(s&&"Reference"!==s.type){const e=Mt(s.values);e.length>0&&(i.enabled=0!==e[0],i.explicit=!0,8&n&&(i.enabled=e[0]>=.5&&e[0]<=1.5),1&n&&(i.enabled=!i.enabled),2&n&&(i.enabled=!0))}4&n&&e.texturesByProp.has(o)&&(i.enabled=!0)}}const v=(e,t,n)=>{var o;const s=null!==(o=e[t])&&void 0!==o?o:e[t]={valueComponents:0,textureEnabled:!1};if(s.value)return;const r=e[n],i=(null==r?void 0:r.value)&&r.value.some(e=>0!==e);s.value=[i?1:0],s.valueComponents=1};v(p.fbx,"diffuseFactor","diffuseColor"),v(p.fbx,"specularFactor","specularColor"),v(p.fbx,"reflectionFactor","reflectionColor"),v(p.fbx,"transparencyFactor","transparencyColor"),v(p.fbx,"emissionFactor","emissionColor"),v(p.fbx,"ambientFactor","ambientColor"),v(p.pbr,"baseFactor","baseColor"),v(p.pbr,"specularFactor","specularColor"),v(p.pbr,"emissionFactor","emissionColor"),v(p.pbr,"sheenFactor","sheenColor"),v(p.pbr,"thinFilmFactor","thinFilmThickness"),v(p.pbr,"transmissionFactor","transmissionColor"),!(null===(i=p.pbr.transmissionRoughness)||void 0===i?void 0:i.value)&&(null===(a=p.pbr.roughness)||void 0===a?void 0:a.value)&&(null===(l=p.pbr.transmissionExtraRoughness)||void 0===l?void 0:l.value)&&(p.pbr.transmissionRoughness={value:[p.pbr.roughness.value[0]+p.pbr.transmissionExtraRoughness.value[0]],valueComponents:1,textureEnabled:!1});const y=[["roughnessAsGlossiness","roughness","glossiness"],["coatRoughnessAsGlossiness","coatRoughness","coatGlossiness"],["transmissionRoughnessAsGlossiness","transmissionRoughness","transmissionGlossiness"]];for(const[e,t,n]of y){const o=p.pbr[t];(null===(u=p.features[e])||void 0===u?void 0:u.enabled)?o&&(p.pbr[n]=o,p.pbr[t]=o.value?{value:[1-o.value[0]],valueComponents:1,textureEnabled:!1}:{valueComponents:0,textureEnabled:!1}):(null==o?void 0:o.value)&&(p.pbr[n]={value:[1-o.value[0]],valueComponents:1,textureEnabled:!1})}return p}function St(e){var t,n;if(!(null==e?void 0:e.value))return;const o=e.value;return 1===e.valueComponents?[o[0],o[0],o[0]]:[o[0],null!==(t=o[1])&&void 0!==t?t:o[0],null!==(n=o[2])&&void 0!==n?n:o[0]]}function Ct(e){return(null==e?void 0:e.value)?e.value[0]:void 0}function Rt(e,t,n,o){var s,r,i,a,l;const u=re(null!==(s=oe(e,1))&&void 0!==s?s:"Material"),c=function(e,t){var n,o;if(!t)return;const s=te(e,"ShadingModel"),r=s?oe(s,0):void 0;return"phong"===(null==r?void 0:r.toLowerCase())?null!==(n=ie(t,"Material","FbxSurfacePhong"))&&void 0!==n?n:ie(t,"Material"):"lambert"===(null==r?void 0:r.toLowerCase())&&null!==(o=ie(t,"Material","FbxSurfaceLambert"))&&void 0!==o?o:ie(t,"Material")}(e,o),d=te(e,"ShadingModel"),h=d?null!==(r=oe(d,0))&&void 0!==r?r:"Lambert":null!==(i=ae(e,c,"ShadingModel"))&&void 0!==i?i:"Lambert",f="phong"===h.toLowerCase()?"Phong":"Lambert",p=function(e,t){var n,o,s,r,i;const a={};return a.diffuseColor=null!==(n=Ft(e,t,"DiffuseColor"))&&void 0!==n?n:Ft(e,t,"Diffuse"),a.diffuseFactor=Et(e,t,"DiffuseFactor"),a.ambientColor=null!==(o=Ft(e,t,"AmbientColor"))&&void 0!==o?o:Ft(e,t,"Ambient"),a.ambientFactor=Et(e,t,"AmbientFactor"),a.specularColor=null!==(s=Ft(e,t,"SpecularColor"))&&void 0!==s?s:Ft(e,t,"Specular"),a.specularFactor=Et(e,t,"SpecularFactor"),a.shininess=null!==(r=Et(e,t,"Shininess"))&&void 0!==r?r:Et(e,t,"ShininessExponent"),a.emissiveColor=null!==(i=Ft(e,t,"EmissiveColor"))&&void 0!==i?i:Ft(e,t,"Emissive"),a.emissiveFactor=Et(e,t,"EmissiveFactor"),a.opacity=Et(e,t,"Opacity"),a.transparencyFactor=Et(e,t,"TransparencyFactor"),a}(e,c),m=function(e,t,n){const o=[],s=ye(t,e,"Texture");for(const{id:e,node:r,propertyName:i}of s)o.push(Ot(e,r,i,t,n));for(const{id:s,propertyName:r}of ye(t,e,"LayeredTexture")){const e=ye(t,s,"Texture");if(0===e.length)continue;const i=Ot(e[0].id,e[0].node,r,t,n);i.layeredTextureId=s,o.push(i)}return o}(t,n,o?null!==(a=ie(o,"Texture","FbxFileTexture"))&&void 0!==a?a:ie(o,"Texture"):void 0),_=new Map;for(const e of null!==(l=null==c?void 0:c.properties.values())&&void 0!==l?l:[])_.set(e.name,{type:e.propertyType,values:e.values});for(const t of fe(e))_.set(t.name,{type:t.type,values:t.values});const g=new Map;for(const e of m)g.has(e.propertyName)||g.set(e.propertyName,e);return{id:t,name:u,type:f,properties:p,textures:m,model:wt({shadingModelName:h,props:_,texturesByProp:g,shader:It(t,n)}),userProperties:pe(e)}}function It(e,t){var n;const o=t.connections.filter(n=>{var o;return"OO"===n.type&&n.childId===e&&"Implementation"===(null===(o=t.objects.get(n.parentId))||void 0===o?void 0:o.name)}).map(e=>({id:e.parentId,node:t.objects.get(e.parentId)}));if(0===o.length)return;const s=o[0],r=null===(n=fe(s.node).find(e=>"RenderAPI"===e.name))||void 0===n?void 0:n.values[0],i=new Map,a=(e,t)=>{const n=i.get(e);n?n.push(t):i.set(e,[t])};for(const e of ye(t,s.id,"BindingTable"))for(const t of e.node.children){if("Entry"!==t.name)continue;const e=oe(t,0),n=oe(t,1),o=oe(t,2),s=oe(t,3);"string"==typeof e&&"string"==typeof o&&("FbxPropertyEntry"===n&&"FbxSemanticEntry"===s?a(o,e):"FbxSemanticEntry"===n&&"FbxPropertyEntry"===s&&a(e,o))}return{renderApi:"string"==typeof r?r:"",bindings:i}}function Ot(e,t,n,o,s){var r,i,a,l,u;{const c=te(t,"FileName"),d=te(t,"RelativeFilename"),h=c&&null!==(r=oe(c,0))&&void 0!==r?r:"",f=d&&null!==(i=oe(d,0))&&void 0!==i?i:"";let p,m;const _=null!==(a=Et(t,s,"UVRotation"))&&void 0!==a?a:Et(t,s,"Rotation");let g;p=null!==(l=Lt(t,s,"UVTranslation"))&&void 0!==l?l:Lt(t,s,"Translation"),m=null!==(u=Lt(t,s,"UVScaling"))&&void 0!==u?u:Lt(t,s,"Scaling");const v=ae(t,s,"UVSet");v&&v.length>0&&(g=v),null!=p||(p=kt(t,"ModelUVTranslation")),null!=m||(m=kt(t,"ModelUVScaling"));const y=Et(t,s,"WrapModeU"),b=Et(t,s,"WrapModeV");let x=null;const T=ye(o,e,"Video");for(const{node:e}of T){const t=te(e,"Content");if(t&&t.properties.length>0){const e=t.properties[0].value;e instanceof Uint8Array&&e.length>0?x=e:e instanceof ArrayBuffer&&e.byteLength>0&&(x=new Uint8Array(e))}}return{propertyName:null!=n?n:"DiffuseColor",fileName:h,relativeFileName:f,id:e,embeddedData:x,uvTranslation:p,uvScaling:m,uvRotation:_,uvSetName:g,wrapU:y,wrapV:b}}}function Ft(e,t,n){const o=ce(e,t,n);if(!o||o.length<3)return;const s=Nt(o[0]),r=Nt(o[1]),i=Nt(o[2]);return void 0!==s&&void 0!==r&&void 0!==i?[s,r,i]:void 0}function Et(e,t,n){return Nt(ae(e,t,n))}function Lt(e,t,n){const o=ce(e,t,n);if(!o)return;const s=Nt(o[0]),r=Nt(o[1]);return void 0!==s&&void 0!==r?[s,r]:void 0}function Nt(e){if("number"==typeof e)return e}function kt(e,t){var n,o;const s=te(e,t);if(!s)return;const r=Nt(null===(n=s.properties[0])||void 0===n?void 0:n.value),i=Nt(null===(o=s.properties[1])||void 0===o?void 0:o.value);return void 0!==r&&void 0!==i?[r,i]:void 0}let Bt;function Pt(e,t,n){var o;const s=n.parentOf.get(e);if(!s)return null;const r=s.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=ye(n,e,"Deformer");if(0===c.length)return null;const d=new Map;for(const{id:e,node:t}of c){if("Cluster"!==oe(t,2))continue;const o=ye(n,e,"Model");o.length>0&&d.set(o[0].id,{clusterId:e,clusterNode:t})}const h=function(e,t){var n;const o=t.parentOf.get(e),s=o?t.objects.get(o.id):void 0,r="Model"===(null==s?void 0:s.name)?o.id:void 0;if(void 0===r)return new Map;for(const[,e]of Array.from(t.objects)){if("Pose"!==e.name||"BindPose"!==oe(e,2))continue;const t=new Map;for(const o of e.children){if("PoseNode"!==o.name)continue;const e=te(o,"Node"),s=te(o,"Matrix"),r=null===(n=null==e?void 0:e.properties[0])||void 0===n?void 0:n.value,i=se(s);if("number"!=typeof r)continue;const a=Kt(i);16===(null==a?void 0:a.length)&&t.set(r,a)}if(t.has(r))return t}return new Map}(r,n),f=[],p=function(e,t,n,o){var s,r,i,a,l;const u=[],c=new Set,d=function(e,t){const n=new Set(Array.from(e.keys()));for(const o of Array.from(e.keys())){let e=Dt(o,t);for(;void 0!==e;){const o=t.objects.get(e);if(!o||"Model"!==o.name)break;n.add(e),e=Dt(e,t)}}return n}(e,n),h=function(e,t){const n=new Map;for(const o of Array.from(e)){let s=Dt(o,t);for(;void 0!==s;){if(e.has(s)){n.set(o,s);break}s=Dt(s,t)}}return n}(d,n),f=function(e,t){const n=new Map;for(const o of Array.from(e)){const e=t.get(o);void 0!==e&&(n.has(e)||n.set(e,[]),n.get(e).push(o))}return n}(d,h),p=Array.from(d).filter(e=>!h.has(e)).map(e=>({modelId:e,parentIndex:-1}));for(;p.length>0;){const{modelId:d,parentIndex:h}=p.shift();if(c.has(d))continue;c.add(d);const m=n.objects.get(d);if(!m)continue;const _=u.length,g=e.get(d),v=Gt(m),{bindPoseMatrix:y,transformLinkMatrix:b,transformAssociateModelMatrix:x,clusterMode:T}=g?$t(g.clusterNode):{bindPoseMatrix:null,transformLinkMatrix:null,transformAssociateModelMatrix:null,clusterMode:"Unknown"},A=Ut(d,re(null!==(s=oe(m,1))&&void 0!==s?s:`Bone${_}`),void 0!==g,T,y,b,x,null!==(r=t.get(d))&&void 0!==r?r:null);o.push(...A),u.push({modelId:d,name:re(null!==(i=oe(m,1))&&void 0!==i?i:`Bone${_}`),index:_,parentIndex:h,isCluster:void 0!==g,translation:v.translation,rotation:v.rotation,preRotation:v.preRotation,postRotation:v.postRotation,rotationPivot:v.rotationPivot,scalingPivot:v.scalingPivot,rotationOffset:v.rotationOffset,scalingOffset:v.scalingOffset,scale:v.scale,rotationOrder:v.rotationOrder,inheritType:v.inheritType,clusterMode:T,bindPoseMatrix:y,transformLinkMatrix:b,transformAssociateModelMatrix:x,modelBindPoseMatrix:null!==(a=t.get(d))&&void 0!==a?a:null,diagnostics:A});for(const e of null!==(l=f.get(d))&&void 0!==l?l:[])c.has(e)||p.push({modelId:e,parentIndex:_})}return u}(d,h,n,f);if(0===p.length)return null;const{boneIndices:m,boneWeights:_}=function(e,t){let n=0;for(const o of e){const e=t.get(o.modelId);if(!e)continue;const s=te(e.clusterNode,"Indexes");if(!s)continue;const r=Ht(se(s));if(r)for(let e=0;e<r.length;e++)r[e]>n&&(n=r[e])}const o=n+1,s=new Array(o),r=new Array(o);for(let e=0;e<o;e++)s[e]=[],r[e]=[];for(const n of e){const e=t.get(n.modelId);if(!e)continue;const o=te(e.clusterNode,"Indexes"),i=te(e.clusterNode,"Weights");if(!o||!i)continue;const a=Ht(se(o)),l=Kt(se(i));if(a&&l)for(let e=0;e<a.length;e++){const t=a[e];s[t].push(n.index),r[t].push(l[e])}}for(let e=0;e<o;e++){if(0===s[e].length)continue;const t=s[e].map((t,n)=>({index:t,weight:r[e][n]}));t.sort((e,t)=>t.weight-e.weight);const n=t.slice(0,8);s[e]=n.map(e=>e.index),r[e]=n.map(e=>e.weight)}for(let e=0;e<o;e++){const t=r[e].reduce((e,t)=>e+t,0);if(t>0)for(let n=0;n<r[e].length;n++)r[e][n]/=t}return{boneIndices:s,boneWeights:r}}(p,d);return{id:e,geometryId:r,meshBindPoseMatrix:void 0!==u&&null!==(o=h.get(u))&&void 0!==o?o:null,bones:p,boneIndices:m,boneWeights:_,diagnostics:f}}function Dt(e,t){const n=t.connections.find(n=>{var o;return"OO"===n.type&&n.childId===e&&"Model"===(null===(o=t.objects.get(n.parentId))||void 0===o?void 0:o.name)});return null==n?void 0:n.parentId}function Vt(e){const t=oe(e,2);return"Root"===t||"LimbNode"===t}function Gt(e,t){return ve(e,null!=t?t:Bt)}function $t(e){let t=null,n=null,o=null,s="Normalize";const r=te(e,"Transform");if(r&&r.properties[0]){const e=se(r);e instanceof Float64Array&&16===e.length?t=e:e instanceof Float32Array&&16===e.length&&(t=new Float64Array(e))}const i=te(e,"TransformLink");if(i&&i.properties[0]){const e=se(i);e instanceof Float64Array&&16===e.length?n=e:e instanceof Float32Array&&16===e.length&&(n=new Float64Array(e))}const a=te(e,"TransformAssociateModel");if(a&&a.properties[0]){const e=se(a);e instanceof Float64Array&&16===e.length?o=e:e instanceof Float32Array&&16===e.length&&(o=new Float64Array(e))}const l=te(e,"Mode"),u=l?oe(l,0):void 0;return"Normalize"===u||"Additive"===u||"TotalOne"===u?s=u:u&&(s="Unknown"),{bindPoseMatrix:t,transformLinkMatrix:n,transformAssociateModelMatrix:o,clusterMode:s}}function Ut(e,t,n,o,s,r,i,a){if(!n)return[];const l=[];return"Additive"!==o&&"TotalOne"!==o||l.push({type:"cluster-mode-runtime-unsupported",message:`Cluster mode '${o}' is preserved but not applied by Babylon linear blend skinning.`,boneModelId:e,boneName:t,clusterMode:o}),s||l.push({type:"missing-cluster-transform",message:"Cluster is missing Transform matrix; falling back to rest/bind-pose data.",boneModelId:e,boneName:t,clusterMode:o}),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:o}),a||l.push({type:"missing-bind-pose-matrix",message:"No BindPose matrix was found for this bone model.",boneModelId:e,boneName:t,clusterMode:o}),i&&l.push({type:"associate-model-present",message:"TransformAssociateModel is preserved for future associate-model skinning semantics.",boneModelId:e,boneName:t,clusterMode:o}),l}function Ht(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 Kt(e){return e instanceof Float64Array?e:e instanceof Float32Array?new Float64Array(e):null}function Wt(e,t){var n;const o=null!==(n=function(e,t){if(0===e.length)return;const n=e.map(e=>qt(e,t)),o=new Set(n[0]);for(const e of n.slice(1))for(const t of Array.from(o))e.includes(t)||o.delete(t);return n[0].find(e=>o.has(e))}(e,t))&&void 0!==n?n:e[0];let s=o,r=zt(s,t);for(;void 0!==r;){const e=t.objects.get(r);if(!e||"Model"!==e.name||!Vt(e))break;s=r,r=zt(r,t)}return s}function qt(e,t){const n=[];let o=e;for(;void 0!==o;){const e=t.objects.get(o);if(!e||"Model"!==e.name)break;n.push(o),o=zt(o,t)}return n}function zt(e,t){const n=t.connections.find(n=>{var o;return"OO"===n.type&&n.childId===e&&"Model"===(null===(o=t.objects.get(n.parentId))||void 0===o?void 0:o.name)});return null==n?void 0:n.parentId}function jt(e){var t,n,o;return null!==(o=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!==o?o:e[0]}function Xt(e,t,n){if(e.length!==t.length)return!1;for(let o=0;o<e.length;o++)if(Math.abs(e[o]-t[o])>n)return!1;return!0}function Yt(e,t){var n;const o=t.objects.get(e);if(!o||"Model"!==o.name)return null;const s=Gt(o);return{modelId:e,name:re(null!==(n=oe(o,1))&&void 0!==n?n:`Bone${e.toString()}`),index:-1,parentIndex:-1,isCluster:!1,translation:s.translation,rotation:s.rotation,preRotation:s.preRotation,postRotation:s.postRotation,rotationPivot:s.rotationPivot,scalingPivot:s.scalingPivot,rotationOffset:s.rotationOffset,scalingOffset:s.scalingOffset,scale:s.scale,rotationOrder:s.rotationOrder,inheritType:s.inheritType,clusterMode:"Unknown",bindPoseMatrix:null,transformLinkMatrix:null,transformAssociateModelMatrix:null,modelBindPoseMatrix:null,diagnostics:[]}}function Qt(e,t){return e<t?-1:e>t?1:0}function Zt(e,t,n){var o,s;return(null!==(o=n.get(e))&&void 0!==o?o:Number.MAX_SAFE_INTEGER)-(null!==(s=n.get(t))&&void 0!==s?s:Number.MAX_SAFE_INTEGER)||Qt(e,t)}const Jt=46186158e3,en=.333333,tn=1e-5,nn=new Float32Array(1),on=new Uint32Array(nn.buffer);function sn(e){return nn[0]=e,on[0]}function rn(e,t,n,o,s,r){const i=r?1:.5;return{left:i*(1-e)*(1+n)*(1-t)*o+i*(1-e)*(1-n)*(1+t)*s,right:i*(1-e)*(1+n)*(1+t)*o+i*(1-e)*(1-n)*(1-t)*s}}function an(e,t,n,o,s,r,i,a,l,u){if(4096&u&&Math.min(Math.abs(o-s),Math.abs(r-s))<=tn)return 0;let c=(r-o)/(n-e);if(!(8192&u)){const i=(s-o)/(t-e),a=(r-s)/(n-t),u=(t-e)/(n-e);c=.5*c+.5*(i*(1-u)+a*u);const d=Math.abs(l)/100;if(d>1e-4){const e=l>0?a:i,t=e-c;c=c*(1-d)+e*d;const n=d-5;if(n>0){let e=Math.abs(t)>1e-5?t:l;e=e>0?1:-1,c+=n*n*e*40}}}if(16384&u){const l=c>=0?1:-1;let u=l*c;const d=i*(t-e),h=a*(n-t);let f=d>0?l*(s-o)/d:0,p=h>0?l*(r-s)/h:0;f>0||(f=0),p>0||(p=0),u=Math.min(u,f,p),c=l*u}return c}function ln(e,t,n,o,s,r){if(16384&r)return 0;if(4096&r&&Math.abs(o-n)<=tn)return 0;let i=(o-n)/(t-e);if(!(8192&r)){const e=Math.abs(s)/100-5;e>0&&(i+=e*e*(s>0?1:-1)*40)}return i}function un(e,t,n){const o=3*e,s=3*t,r=o-s+1,i=s-o-o,a=o,l=3*r,u=2*i;let c,d=n;for(let e=0;e<11;e++){const t=d*d;c=r*(t*d)+i*t+a*d-n;const o=l*t+u*d+a;if(0===o)break;if(d-=c/o,e>=2&&Math.abs(c)<=8881784197001252e-31)break}return d}function cn(e,t){var n,o;const s=t.time-e.time;if(Number.isFinite(e.rightDx)&&Number.isFinite(e.rightDy)&&Number.isFinite(t.leftDx)&&Number.isFinite(t.leftDy)&&(e.rightDx>0||t.leftDx>0))return{rightDx:e.rightDx,rightDy:e.rightDy,leftDx:t.leftDx,leftDy:t.leftDy};const r=null!==(n=e.rightSlope)&&void 0!==n?n:0;return{rightDx:s/3,rightDy:s/3*r,leftDx:s/3,leftDy:s/3*(null!==(o=e.nextLeftSlope)&&void 0!==o?o:t.leftDx>0?t.leftDy/t.leftDx:r)}}function dn(e,t,n,o=!1){if(!e||0===e.keys.length)return n;const s=e.keys;if(1===s.length)return s[0].value;const r=s[0].time,i=s[s.length-1].time;if(!o&&(t<r||t>i))return function(e,t){var n;const o=e.keys,s=o[0].time,r=o[o.length-1].time,i=t<s,a=i?o[0]:o[o.length-1],l=null!==(n=i?e.preExtrapolation:e.postExtrapolation)&&void 0!==n?n:{mode:"constant",repeatCount:-1};if("constant"===l.mode)return a.value;if("slope"===l.mode){const e=i?a.rightDx:a.leftDx,n=i?a.rightDy:a.leftDy;return 0!==e?a.value+n*((t-a.time)/e):a.value}if(0===l.repeatCount)return a.value;const u=Jt,c=Math.round(s*u),d=Math.round(r*u),h=t*u,f=i?c-h:h-d,p=d-c;if(!(p>=1))return a.value;const m=f/p;let _=Math.floor(m),g=f-_*p;l.repeatCount>0&&_>=l.repeatCount&&(_=l.repeatCount-1,g=p),"mirror"===l.mode&&.5*_-Math.floor(.5*_)<=.25&&(g=p-g),i&&(g=p-g);let v=dn(e,(c+g)/u,a.value,!0);if("repeatRelative"===l.mode){let e=o[o.length-1].value-o[0].value;i&&(e=-e),v+=e*(_+1)}return v}(e,t);let a=0,l=s.length;for(;l-a>=8;){const e=a+l>>1;s[e].time<=t?a=e+1:l=e}for(l=s.length;a<l;a++){const e=s[a];if(e.time<=t)continue;if(0===a)return e.value;const n=s[a-1];if(n.time===t)return n.value;const o=1/(e.time-n.time);let r=(t-n.time)*o;switch(n.interpolation){case"constant":return"next"===n.constantMode?e.value:n.value;case"linear":return n.value*(1-r)+e.value*r;default:{const t=cn(n,e);r=un(t.rightDx*o,1-t.leftDx*o,r);const s=r*r,i=s*r,a=1-r,l=a*a,u=l*a,c=n.value,d=e.value;return u*c+3*(l*r*(c+t.rightDy)+a*s*(d-t.leftDy))+i*d}}}return s[s.length-1].value}const hn=Math.PI/180,fn=180/Math.PI;function pn(e,t){const n=e[0]*(.5*hn),o=e[1]*(.5*hn),s=e[2]*(.5*hn),r=Math.cos(n),i=Math.sin(n),a=Math.cos(o),l=Math.sin(o),u=Math.cos(s),c=Math.sin(s);switch(t){case 1:return[r*l*c+a*u*i,r*u*l+a*i*c,r*a*c-u*i*l,r*a*u-i*l*c];case 2:return[-r*l*c+a*u*i,r*u*l-a*i*c,r*a*c+u*i*l,r*a*u+i*l*c];case 3:return[-r*l*c+a*u*i,r*u*l+a*i*c,r*a*c+u*i*l,r*a*u-i*l*c];case 4:return[r*l*c+a*u*i,r*u*l-a*i*c,r*a*c-u*i*l,r*a*u+i*l*c];case 5:return[r*l*c+a*u*i,r*u*l-a*i*c,r*a*c+u*i*l,r*a*u-i*l*c];default:return[-r*l*c+a*u*i,r*u*l+a*i*c,r*a*c-u*i*l,r*a*u+i*l*c]}}function mn(e,t){const n=.999999999,[o,s,r,i]=e;let a,l=0,u=0,c=0;const d=.5*Math.PI;switch(t){case 1:a=2*(i*r+o*s),Math.abs(a)<n?(c=Math.asin(a),u=Math.atan2(2*(i*s-o*r),2*(i*i+o*o)-1),l=-Math.atan2(-2*(i*o-s*r),2*(i*i+s*s)-1)):(c=Math.sign(a)*d,u=Math.atan2(2*a*(i*o+s*r),-a*(2*o*s-2*i*r)));break;case 2:a=2*(i*r-o*s),Math.abs(a)<n?(c=Math.asin(a),l=Math.atan2(2*(i*o+s*r),2*(i*i+s*s)-1),u=-Math.atan2(-2*(i*s+o*r),2*(i*i+o*o)-1)):(c=Math.sign(a)*d,l=Math.atan2(-2*a*(i*s-o*r),a*(2*i*r+2*o*s)));break;case 3:a=2*(i*o+s*r),Math.abs(a)<n?(l=Math.asin(a),c=Math.atan2(2*(i*r-o*s),2*(i*i+s*s)-1),u=-Math.atan2(-2*(i*s-o*r),2*(i*i+r*r)-1)):(l=Math.sign(a)*d,c=Math.atan2(2*a*(i*s+o*r),-a*(2*s*r-2*i*o)));break;case 4:a=2*(i*o-s*r),Math.abs(a)<n?(l=Math.asin(a),u=Math.atan2(2*(i*s+o*r),2*(i*i+r*r)-1),c=-Math.atan2(-2*(i*r+o*s),2*(i*i+s*s)-1)):(l=Math.sign(a)*d,u=Math.atan2(-2*a*(i*r-o*s),a*(2*i*o+2*s*r)));break;case 5:a=2*(i*s+o*r),Math.abs(a)<n?(u=Math.asin(a),l=Math.atan2(2*(i*o-s*r),2*(i*i+r*r)-1),c=-Math.atan2(-2*(i*r-o*s),2*(i*i+o*o)-1)):(u=Math.sign(a)*d,l=Math.atan2(2*a*(i*r+o*s),-a*(2*o*r-2*i*s)));break;default:a=2*(i*s-o*r),Math.abs(a)<n?(u=Math.asin(a),c=Math.atan2(2*(i*r+o*s),2*(i*i+o*o)-1),l=-Math.atan2(-2*(i*o+s*r),2*(i*i+r*r)-1)):(u=Math.sign(a)*d,c=Math.atan2(-2*a*(i*o-s*r),a*(2*i*s+2*o*r)))}return[l*fn,u*fn,c*fn]}function _n(e,t,n){let o,s,r=e[0]*t[0]+e[1]*t[1]+e[2]*t[2]+e[3]*t[3],i=t[0],a=t[1],l=t[2],u=t[3];if(r<0&&(r=-r,i=-i,a=-a,l=-l,u=-u),r>.9995)o=1-n,s=n;else{const e=Math.acos(Math.min(1,r)),t=1/Math.sin(e);o=Math.sin((1-n)*e)*t,s=Math.sin(n*e)*t}const c=e[0]*o+i*s,d=e[1]*o+a*s,h=e[2]*o+l*s,f=e[3]*o+u*s,p=Math.hypot(c,d,h,f)||1;return[c/p,d/p,h/p,f/p]}function gn(e,t){return e>=0?Math.pow(e,t):-Math.pow(-e,t)}function vn(e,t,n,o,s){const r=n.weight;if(n.additive)return n.composeScale&&"S"===o?[e[0]*gn(t[0],r),e[1]*gn(t[1],r),e[2]*gn(t[2],r)]:n.composeRotation&&"R"===o?mn((i=pn(e,s),a=_n([0,0,0,1],pn(t,s),r),[i[3]*a[0]+i[0]*a[3]+i[1]*a[2]-i[2]*a[1],i[3]*a[1]-i[0]*a[2]+i[1]*a[3]+i[2]*a[0],i[3]*a[2]+i[0]*a[1]-i[1]*a[0]+i[2]*a[3],i[3]*a[3]-i[0]*a[0]-i[1]*a[1]-i[2]*a[2]]),s):[e[0]+t[0]*r,e[1]+t[1]*r,e[2]+t[2]*r];var i,a;if(n.blended){const i=1-r;return n.composeScale&&"S"===o?[gn(e[0],i)*gn(t[0],r),gn(e[1],i)*gn(t[1],r),gn(e[2],i)*gn(t[2],r)]:n.composeRotation&&"R"===o?mn(_n(pn(e,s),pn(t,s),r),s):[e[0]*i+t[0]*r,e[1]*i+t[1]*r,e[2]*i+t[2]*r]}return[t[0],t[1],t[2]]}function yn(e,t,n,o){var s,r;const i=re(null!==(s=oe(t,1))&&void 0!==s?s:"Animation"),a=function(e){var t,n,o,s;const r=te(e,"Properties70");if(!r)return null;let i=0,a=null;for(const e of r.children){if("P"!==e.name)continue;const r=oe(e,0);"LocalStart"===r||"ReferenceStart"===r?i=null!==(n=Fn(null===(t=e.properties[4])||void 0===t?void 0:t.value))&&void 0!==n?n:i:"LocalStop"!==r&&"ReferenceStop"!==r||(a=null!==(s=Fn(null===(o=e.properties[4])||void 0===o?void 0:o.value))&&void 0!==s?s:a)}return null!==a?{start:i,stop:a}:null}(t),l=ye(n,e,"AnimationLayer");if(0===l.length)return null;const u=[],c=[],d=[],h=[];let f=1/0,p=-1/0;for(const{id:e,node:t}of l){const o=re(null!==(r=oe(t,1))&&void 0!==r?r:"Layer");let s=100,i=0,a=0,l=0;for(const e of fe(t)){const t=e.values[0];"number"==typeof t&&("Weight"===e.name?s=t:"BlendMode"===e.name?i=t:"RotationAccumulationMode"===e.name?a=t:"ScaleAccumulationMode"===e.name&&(l=t))}const m=d.length,_=ye(n,e,"AnimationCurveNode"),g=[],v=[],y=[];let b;for(const{id:t,node:s}of _){const r=xn(t,s,n,m);if(!r){const r=Tn(t,s,n,m);if(r){if(r.targetId===e&&"Weight"===r.propertyName&&r.curves.length>0){b=r.curves[0];continue}An(r.curves,e=>{e<f&&(f=e),e>p&&(p=e)}),v.push(r),c.push(r);const n={type:"unsupported-curve-node",message:`AnimationCurveNode '${r.type}' is preserved as diagnostic data but not evaluated at runtime.`,layerName:o,curveNodeId:t,curveNodeType:r.type,targetId:r.targetId,propertyName:r.propertyName};y.push(n),h.push(n)}continue}for(const e of r.curves)for(const t of e.keys)t.time<f&&(f=t.time),t.time>p&&(p=t.time);g.push(r),u.push(r)}d.push({name:o,weight:s,normalizedWeight:s/100,blendMode:i,blend:Rn(i,s,a,l),weightCurve:b,curveNodes:g,unsupportedCurveNodes:v,diagnostics:y})}return 0===u.length&&0===c.length?null:bn(i,d,u,c,h,f,p,a,o)}function bn(e,t,n,o,s,r,i,a,l){const u=isFinite(r)&&isFinite(i),c=l&&u&&r>0?r:0;if(c>0){for(const e of n)for(const t of e.curves)for(const e of t.keys)e.time-=c;for(const e of o)for(const t of e.curves)for(const e of t.keys)e.time-=c;i-=c}const d=a?l?Math.max(a.start-c,0):a.start:0,h=a?Math.max(a.stop-c,d):0,f=h>d,p=u?r-c:0,m=u?i:0,_=f?d:l?Math.min(0,p):p,g=f?h:Math.max(m,_);return{name:e,startTime:_,stopTime:g,duration:Math.max(g-_,0),curveNodes:n,layers:t,unsupportedCurveNodes:o,diagnostics:s}}function xn(e,t,n,o){var s,r,i,a;const l=re(null!==(s=oe(t,1))&&void 0!==s?s:""),u=wn(t),c="d|X"in u||"d|Y"in u||"d|Z"in u?[null!==(r=u["d|X"])&&void 0!==r?r:0,null!==(i=u["d|Y"])&&void 0!==i?i:0,null!==(a=u["d|Z"])&&void 0!==a?a:0]:void 0;if("T"===l||"R"===l||"S"===l){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=Mn(e,n);return 0!==s.length||c?{type:l,targetModelId:t,curves:s,layerIndex:o,defaultValues:c}:null}const d=function(e,t){var n;for(const o of t.connections){if(o.childId!==e||"OP"!==o.type||!o.propertyName)continue;const s=t.objects.get(o.parentId);if(s&&"Geometry"===s.name)for(const e of ye(t,o.parentId,"Deformer"))if("BlendShape"===oe(e.node,2))for(const s of ye(t,e.id,"Deformer"))if("BlendShapeChannel"===oe(s.node,2)&&re(null!==(n=oe(s.node,1))&&void 0!==n?n:"")===o.propertyName)return s.id}return null}(e,n);if(null!==d){const t=Mn(e,n);return 0===t.length?null:{type:"DeformPercent",targetModelId:d,curves:t,layerIndex:o,defaultValues:c}}if("DeformPercent"===l){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"===oe(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"===oe(e,2))return n.parentId}return null}(e,n);if(null===t)return null;const s=Mn(e,n);return 0===s.length?null:{type:"DeformPercent",targetModelId:t,curves:s,layerIndex:o,defaultValues:c}}return null}function Tn(e,t,n,o){var s;const r=re(null!==(s=oe(t,1))&&void 0!==s?s:""),i=Mn(e,n),a=wn(t);if(0===i.length&&0===Object.keys(a).length)return null;let l,u=null;for(const t of n.connections)if(t.childId===e&&"OP"===t.type){u=t.parentId,l=t.propertyName;break}return{type:r,id:e,layerIndex:o,targetId:u,propertyName:l,curveCount:i.length,curves:i,defaultValues:a}}function An(e,t){for(const n of e)for(const e of n.keys)t(e.time)}function Mn(e,t){var n;const o=[];for(const s of t.connections)if(s.parentId===e&&"OP"===s.type){const e=t.objects.get(s.childId);if(!e||"AnimationCurve"!==e.name)continue;const r=null!==(n=s.propertyName)&&void 0!==n?n:"d|X",i=Sn(e);i.length>0&&o.push(Object.assign({channel:r,keys:i},Cn(e)))}if(0===o.length){const n=ye(t,e,"AnimationCurve"),s=["d|X","d|Y","d|Z"];for(let e=0;e<n.length&&e<3;e++){const t=Sn(n[e].node);t.length>0&&o.push(Object.assign({channel:s[e],keys:t},Cn(n[e].node)))}}return o}function wn(e){var t,n;const o={},s=te(e,"Properties70");for(const e of null!==(t=null==s?void 0:s.children)&&void 0!==t?t:[]){if("P"!==e.name)continue;const t=oe(e,0);if(!(null==t?void 0:t.startsWith("d|")))continue;const s=En(null===(n=e.properties[4])||void 0===n?void 0:n.value);null!==s&&(o[t]=s)}return o}function Sn(e){const t=te(e,"KeyTime"),n=te(e,"KeyValueFloat");if(!t||!n)return[];const o=(l=se(t))instanceof Float64Array?l:null,s=Ln(se(n)),r=On(se(te(e,"KeyAttrFlags"))),i=Ln(se(te(e,"KeyAttrDataFloat"))),a=On(se(te(e,"KeyAttrRefCount")));var l;if(!o||!s)return[];if(o.length!==s.length)return[];const u=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 o=n[t];for(let n=0;n<o;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))}(o.length,r,a);return function(e,t,n){const o=Math.min(e.length,t.length),s=[];if(0===o)return s;let r=0,i=en,a=0,l=Number(e[0])/Jt;for(let u=0;u<o;u++){const c=l,d=t[u];u+1<o&&(l=Number(e[u+1])/Jt);const h=u>0?t[u-1]:d,f=u+1<o?t[u+1]:d,p=n(u),m=p.flags;let _,g=p.data[0],v=en,y=p.data[1],b=en;if(50331648&m){const e=sn(p.data[2]);16777216&m&&(v=1e-4*(65535&e)),33554432&m&&(b=1e-4*(e>>>16))}let x="standard";if(2&m)_="constant",x=256&m?"next":"standard",v=b=en,g=y=0;else if(8&m)if(_="cubic",512&m){let e=0,t=0,n=!1;u>0&&c>a?e=(d-h)/(c-a):n=!0,u+1<o&&l>c?t=(f-d)/(l-c):n=!0;const s=rn(p.data[0],p.data[1],p.data[2],e,t,n);r=s.left,g=s.right,y=0,b=en}else 1024&m||(u>0&&u+1<o&&c>a&&l>c?Math.abs(r+g)<=1e-4?r=g=an(a,c,l,h,d,f,i,v,g,m):(r=an(a,c,l,h,d,f,i,v,-r,m),g=an(a,c,l,h,d,f,i,v,g,m)):r=g=u>0&&c>a?ln(a,c,h,d,-r,m):u+1<o&&l>c?ln(c,l,d,f,g,m):0);else{_="linear",v=en,b=en;const e=l-c;g=y=e>0?(f-d)/e:0}const T={time:c,value:d,interpolation:_,constantMode:x,leftDx:0,leftDy:0,rightDx:0,rightDy:0};c>a&&(T.leftDx=i*(c-a),T.leftDy=T.leftDx*r),l>c&&(T.rightDx=v*(l-c),T.rightDy=T.rightDx*g),T.rightSlope=g,s.push(T),r=y,i=b,a=c}for(let e=0;e+1<s.length;e++){const t=s[e+1];s[e].nextLeftSlope=t.leftDx>0?t.leftDy/t.leftDx:0}return s}(o,s,e=>{var t,n,o,s,a;const l=u[e],c=4*l;return{flags:l>=0&&null!==(t=null==r?void 0:r[l])&&void 0!==t?t:0,data:[null!==(n=Nn(i,c))&&void 0!==n?n:0,null!==(o=Nn(i,c+1))&&void 0!==o?o:0,null!==(s=Nn(i,c+2))&&void 0!==s?s:0,null!==(a=Nn(i,c+3))&&void 0!==a?a:0]}})}function Cn(e){const t=t=>{var n,o,s,r;const i=te(e,t);return function(e,t){const n="string"==typeof e?e.charCodeAt(0):"number"==typeof e?e:0;let o;switch(String.fromCharCode(n)){case"A":o="repeatRelative";break;case"K":o="slope";break;case"M":o="mirror";break;case"R":o="repeat";break;default:o="constant"}let s="number"==typeof t?t:-1;return s<0&&(s=-1),{mode:o,repeatCount:s}}(null===(o=null===(n=te(null!=i?i:e,"Type"))||void 0===n?void 0:n.properties[0])||void 0===o?void 0:o.value,null===(r=null===(s=te(null!=i?i:e,"Repetition"))||void 0===s?void 0:s.properties[0])||void 0===r?void 0:r.value)};return{preExtrapolation:t("Pre-Extrapolation"),postExtrapolation:t("Post-Extrapolation")}}function Rn(e,t,n,o){let s=!1,r=!1;switch(e){case 0:s=!0,r=!0;break;case 2:s=!0}let i=t/100;return i<0&&(i=0),i>.99999&&(i=1),{blended:s,additive:r,composeRotation:0===n,composeScale:0===o,weight:i}}function In(e,t){return e&&0!==e.keys.length?dn(e,t,e.keys[0].value):null}function On(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 Fn(e){return"number"==typeof e?e/Jt:null}function En(e){return"number"==typeof e?e:null}function Ln(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 Nn(e,t){if(!e||t<0||t>=e.length)return;const n=e[t];return Number.isFinite(n)?n:void 0}const kn=new Set(["Color","Intensity","OuterAngle","InnerAngle","ConeAngle","HotSpot","FieldOfView","FieldOfViewX","FieldOfViewY","FocalLength","NearPlane","FarPlane","OrthoZoom","Roll","FilmWidth","FilmHeight"]);function Bn(e,t,n){var o;const s=n.endsWith(" (Shape)")?n.slice(0,-8):n;for(const n of ye(e,t,"Geometry"))for(const t of ye(e,n.id,"Deformer"))if("BlendShape"===oe(t.node,2))for(const n of ye(e,t.id,"Deformer"))if("BlendShapeChannel"===oe(n.node,2)&&re(null!==(o=oe(n.node,1))&&void 0!==o?o:"")===s)return n.id}function Pn(e){var t,n;if(!e)return null;const o=Fn(null===(t=e.properties[0])||void 0===t?void 0:t.value),s=Fn(null===(n=e.properties[1])||void 0===n?void 0:n.value);return null!==o&&null!==s?{start:o,stop:s}:null}function Dn(e,t){var n;const o=e=>e.children.some(e=>"Key"===e.name||"Default"===e.name);if(o(e)){const n=Vn(e,t);return n.length>0?[Object.assign({channel:"d|X",keys:n},Cn(e))]:[]}const s=[];for(const r of e.children){if("Channel"!==r.name||!o(r))continue;const e=null!==(n=oe(r,0))&&void 0!==n?n:"X",i=Vn(r,t);if(i.length>0&&s.push(Object.assign({channel:`d|${e}`,keys:i},Cn(r))),3===s.length)break}return s}function Vn(e,t){var n,o,s,r,i,a;const l=te(e,"Key");if(!l)return[];const u=l.properties.map(e=>e.value),c=e=>"number"==typeof e?e:"boolean"==typeof e?e?1:0:NaN,d=e=>"string"==typeof e?e:"number"==typeof e?String.fromCharCode(e):"boolean"==typeof e?e?"":"\0":"?";let h=null!==(s=En(null===(o=null===(n=te(e,"KeyVer"))||void 0===n?void 0:n.properties[0])||void 0===o?void 0:o.value))&&void 0!==s?s:0;h<=0&&(h=t<5e3?4003:t<6e3?4004:4005);const f=null!==(a=En(null===(i=null===(r=te(e,"KeyCount"))||void 0===r?void 0:r.properties[0])||void 0===i?void 0:i.value))&&void 0!==a?a:0,p=[],m=[],_=[],g=[],v=[],y=[],b=[],x=[],T=[];let A=0,M=1/3,w=0;for(let e=0;e<f&&!(w+3>u.length);e++){const e=c(u[w])/Jt,t=c(u[w+1]),n=d(u[w+2]);w+=3;let o=0,s=0,r=1/3,i=1/3,a=!1,l="cubic",f=!1;if("U"===n){const e=d(u[w]);w+=1;let t=1;if("s"===e||"b"===e)o=c(u[w]),s=c(u[w+1]),w+=2,4003===h&&(t=0);else if("a"===e)a=!0,h<=4004&&(t=0);else if("p"===e||"q"===e)a=!0,w+=2,t=h<=4004?1:2;else if("t"===e)a=!0,w+=3,t=0;else{if("d"!==e)break;a=!0,w+=1}for(;t>0;t--){const e=d(u[w]);if(w+=1,"n"===e||"c"===e);else if("a"===e)r=c(u[w]),i=c(u[w+1]),w+=2;else if("l"===e)i=c(u[w]),w+=1;else{if("r"!==e){w=u.length;break}r=c(u[w]),w+=1}}}else if("L"===n)l="linear";else{if("C"!==n)break;l="constant",h>=4004&&(f="n"===d(u[w]),w+=1)}p.push(e),m.push(t),_.push(l),g.push(f),v.push(A),y.push(o),b.push(M),x.push(r),T.push(a),A=s,M=i}for(let e=0;e<p.length;e++){if(T[e]){const t=e>0&&e+1<p.length?Gn(p[e-1],p[e],p[e+1],m[e-1],m[e],m[e+1],b[e],x[e]):0;v[e]=t,y[e]=t}if("linear"===_[e]&&e+1<p.length){const t=p[e+1]-p[e],n=t>0?(m[e+1]-m[e])/t:0;y[e]=n,T[e+1]||(v[e+1]=n)}}return function(e,t,n,o,s,r,i,a){var l,u;const c=[];for(let d=0;d<e.length;d++){const h={time:e[d],value:t[d],interpolation:n[d],constantMode:o[d]?"next":"standard",leftDx:0,leftDy:0,rightDx:0,rightDy:0,rightSlope:r[d],nextLeftSlope:d+1<e.length?s[d+1]:void 0};d>0&&e[d]>e[d-1]&&(h.leftDx=(null!==(l=null==i?void 0:i[d])&&void 0!==l?l:en)*(e[d]-e[d-1]),h.leftDy=h.leftDx*s[d]),d+1<e.length&&e[d+1]>e[d]&&(h.rightDx=(null!==(u=null==a?void 0:a[d])&&void 0!==u?u:en)*(e[d+1]-e[d]),h.rightDy=h.rightDx*r[d]),c.push(h)}return c}(p,m,_,g,v,y,b,x)}function Gn(e,t,n,o,s,r,i,a){if(!(n>e))return 0;const l=(r-o)/(n-e),u=l>=0?1:-1;let c=u*l;const d=i*(t-e),h=a*(n-t);let f=d>0?u*(s-o)/d:0,p=h>0?u*(r-s)/h:0;return f>0||(f=0),p>0||(p=0),c=Math.min(c,f,p),u*c}function $n(e,t,n,o,s,r){var i;let a=[o[0],o[1],o[2]];for(let o=0;o<Math.max(t.length,1);o++){const l=e.find(e=>e.type===n&&e.layerIndex===o);if(!l)continue;const u=null!==(i=l.defaultValues)&&void 0!==i?i:a,c=[dn(l.curves.find(e=>"d|X"===e.channel),r,u[0]),dn(l.curves.find(e=>"d|Y"===e.channel),r,u[1]),dn(l.curves.find(e=>"d|Z"===e.channel),r,u[2])],d=t[o];if(0!==o&&d){let e=d.blend;if(d.weightCurve&&e.blended){let t=dn(d.weightCurve,r,d.weight)/100;t=t<0?0:t>.99999?1:t,e=Object.assign(Object.assign({},e),{weight:t})}a=vn(a,c,e,n,s)}else a=c}return a}function Un(e,t,n,o,s){const r=n.map((e,t)=>{var n;return null!==(n=o[t])&&void 0!==n?n:0});for(let o=0;o<Math.max(t.length,1);o++){const i=e.find(e=>e.layerIndex===o);if(!i)continue;const a=n.map((e,t)=>{var n,o;return dn(i.curves.find(t=>t.channel===e),s,null!==(o=null===(n=i.defaultValues)||void 0===n?void 0:n[e])&&void 0!==o?o:r[t])}),l=t[o];if(0===o||!l){for(let e=0;e<r.length;e++)r[e]=a[e];continue}let u=l.blend;if(l.weightCurve&&u.blended){let e=dn(l.weightCurve,s,l.weight)/100;e=e<0?0:e>.99999?1:e,u=Object.assign(Object.assign({},u),{weight:e})}for(let e=0;e<r.length;e++)r[e]=vn([r[e],0,0],[a[e],0,0],u,"other",0)[0]}return r}function Hn(e,t,n){let o=!1;for(const s of e)if(s.type===t)for(const e of s.curves){const t=e.keys;if(t.length<2)continue;if(o=!0,n<t[0].time||n>=t[t.length-1].time)return!1;let s=0;for(;s+1<t.length&&t[s+1].time<=n;)s++;if("constant"!==t[s].interpolation)return!1}return o}function Kn(e,t,n){var o;const s=n.parentOf.get(e);if(!s)return null;const r=n.objects.get(s.id);if(!r||"Geometry"!==r.name)return null;const i=s.id,a=[],l=ye(n,e,"Deformer");for(const{id:e,node:t}of l){if("BlendShapeChannel"!==oe(t,2))continue;const s=re(null!==(o=oe(t,1))&&void 0!==o?o:"MorphTarget");let r=0;for(const e of fe(t))"DeformPercent"===e.name&&"number"==typeof e.values[0]&&(r=e.values[0]);const i=Wn(t),l=[],u=ye(n,e,"Geometry");for(const{node:e}of u){if("Shape"!==oe(e,2))continue;const t=jn(e);t&&l.push(t)}if(l.length>0){const t=[],n=qn(i,l,e,s,t);a.push({name:s,id:e,deformPercent:r,shapes:zn(l,n),fullWeights:n?[...n].sort((e,t)=>e-t):null,diagnostics:t})}}return 0===a.length?null:{id:e,geometryId:i,channels:a}}function Wn(e){const t=se(te(e,"FullWeights"));return t&&(t instanceof Float64Array||t instanceof Float32Array||t instanceof Int32Array)?Array.from(t,e=>Number(e)):null}function qn(e,t,n,o,s){return e?e.length!==t.length?(1===t.length||s.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:o}),null):e:(t.length>1&&s.push({type:"missing-full-weights",message:"Blend shape channel has multiple shapes but no FullWeights; using the first shape for compatibility.",channelId:n,channelName:o}),null)}function zn(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 jn(e){const t=te(e,"Indexes"),n=te(e,"Vertices");if(!t||!n)return null;const o=se(t),s=se(n);if(!o||!s)return null;const r=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}(o);if(!r)return null;let i;if(s instanceof Float64Array)i=s;else{if(!(s instanceof Float32Array))return null;i=new Float64Array(s)}let a=null;const l=te(e,"Normals");if(l){const e=se(l);e instanceof Float64Array?a=e:e instanceof Float32Array&&(a=new Float64Array(e))}return{indices:r,vertices:i,normals:a}}const Xn=new Set(["Character","CharacterPose","ControlSet","ControlSetPlug"]),Yn=new Set(["Camera","Light","Null","LodGroup","LimbNode","Limb","Root","Skeleton","Marker","CameraSwitcher","Mesh","NurbsCurve","NurbsSurface","TrimNurbsSurface","Line","Boundary"]);function Qn(e){return"Skin"===e||"Cluster"===e||"BlendShape"===e||"BlendShapeChannel"===e}function Zn(e,t,n,o,s){var r,i,a,l;return{type:o,message:s,objectId:t,objectName:re(null!==(r=oe(n,1))&&void 0!==r?r:n.name),nodeName:n.name,subType:null!==(i=oe(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 Jn(e,t,n){const o=ye(e,t,"Deformer").map(e=>{var t;return null!==(t=oe(e.node,2))&&void 0!==t?t:""}).filter(e=>"Skin"===e||"BlendShape"===e);0!==o.length&&n.diagnostics.push({type:"nurbs-deformer-ignored",message:`${Array.from(new Set(o)).join(" and ")} deformer on NURBS surface '${n.name}' is ignored: the tessellated mesh has no control point mapping.`})}function eo(e,t={}){var n;(function(e){return!ne(e,"Objects")&&e.nodes.some(e=>"Model"===e.name)})(e)&&(e=function(e){var t,n,o,s,r,i,a;const l=et(te(null!==(t=ne(e,"FBXHeaderExtension"))&&void 0!==t?t:Ye("x"),"FBXVersion")),u=Math.max(e.version,null!=l?l:0),c={version:u,objects:[],connections:[],usedNames:new Map,takeDefaults:new Map},d=ne(e,"Takes");for(const e of null!==(n=null==d?void 0:d.children)&&void 0!==n?n:[])if("Take"===e.name)for(const t of e.children){if("Model"!==t.name)continue;const e=oe(t,0),n=t.children.find(e=>"Channel"===e.name&&"Transform"===oe(e,0));e&&n&&!c.takeDefaults.has(e)&&c.takeDefaults.set(e,n)}const h=e.nodes.filter(e=>"Model"===e.name);for(const e of h)ut(c,e);const f=[];for(const e of h){const t=e.children.filter(e=>"Channel"===e.name&&rt(e));t.length>0&&f.push(Ye("Model",[ze(null!==(o=oe(e,0))&&void 0!==o?o:"")],t))}let p=d;if(f.length>0){const e=Ye("Take",[ze("(internal)")],f);p=d?Ye("Takes",d.properties,[...d.children,e]):Ye("Takes",[],[e])}const m=null!==(s=ne(e,"Settings"))&&void 0!==s?s:te(null!==(r=ne(e,"Version5"))&&void 0!==r?r:Ye("x"),"Settings"),_=m?te(m,"FrameRate"):void 0,g=null===(i=null==_?void 0:_.properties[0])||void 0===i?void 0:i.value,v="number"==typeof g?g:"string"==typeof g?Number.parseFloat(g):NaN,y=[];let b=!1;if(Number.isFinite(v)&&v>0){const t=ne(e,"GlobalSettings");if(t){const e=te(t,"Properties70"),n=null!==(a=null!=e?e:te(t,"Properties60"))&&void 0!==a?a:Ye("Properties60"),o=e?Ze:Qe,s=n.children.some(e=>"TimeMode"===oe(e,0))?[]:[o("TimeMode","enum","",14),o("CustomFrameRate","double","",v)],r=t.children.filter(e=>e!==n);y.push(Ye("GlobalSettings",t.properties,[...r,Ye(n.name,n.properties,[...n.children,...s])]))}else y.push(Ye("GlobalSettings",[],[Ye("Version",[Xe(1e3)]),Ye("Properties60",[],[Qe("TimeMode","enum","",14),Qe("CustomFrameRate","double","",v)])]));b=!0}const x=[...e.nodes.filter(e=>"Model"!==e.name&&"Takes"!==e.name&&"Settings"!==e.name&&("GlobalSettings"!==e.name||!b)),...y,Ye("Objects",[],c.objects),Ye("Connections",[],c.connections)];return p&&x.push(p),Object.assign(Object.assign({},e),{version:u,nodes:x})}(e));const o=function(e){var t,n,o,s,r;const i=new Map,a=[],l=new Map,u=new Map,c=[],d=[],h=[],f=new Map,p=new Map,m=new Map,_=new Map,g=ne(e,"Objects"),v=ne(e,"Connections"),y=new Set,b=e=>{const t=null==e?void 0:e.value;"number"==typeof t&&Number.isSafeInteger(t)&&y.add(t)};for(const e of null!==(t=null==g?void 0:g.children)&&void 0!==t?t:[])b(e.properties[0]);for(const e of null!==(n=null==v?void 0:v.children)&&void 0!==n?n:[])b(e.properties[1]),b(e.properties[2]),b(e.properties[3]);let x=-1;const T=()=>{for(;y.has(x);)x--;const e=x--;return y.add(e),e},A=new Map,M=e=>{if(e){if(void 0!==e.raw){let t=A.get(e.raw);return void 0===t&&(t=T(),A.set(e.raw,t)),t}return function(e){if("number"==typeof e&&Number.isFinite(e)&&Number.isInteger(e))return e}(e.value)}},w=e=>{const t=M(e);if(void 0!==t)return t;const n=null==e?void 0:e.value;if("string"!=typeof n)return;const o=f.get(n);if(void 0!==o)return o;const s=re(n);return"Scene"===s?0:p.get(s)},S=e=>{let t=f.get(e);if(void 0===t){t=T(),f.set(e,t);const n=re(e);p.has(n)||p.set(n,t)}return t},C=(e,t)=>{let n=m.get(e);n||(n=new Map,m.set(e,n));let o=n.get(t);return void 0===o&&(o=T(),n.set(t,o)),o},R=(e,t,n)=>{var o;const s=e.children.filter(e=>"Shape"===e.name);if(0===s.length)return;const r=C("BlendShape",n),d=xe("Deformer",r,`Deformer::${re(n)}`,"BlendShape",[be(100)]);i.set(r,d),a.push({id:r,node:d,source:"legacySyntheticBlendShape",legacyName:n,synthetic:!0}),Te(c,l,u,h,"OO",r,t);for(const e of s){const t=re(null!==(o=oe(e,0))&&void 0!==o?o:"Shape"),s=C("BlendShapeChannel",`${n}|${t}`),d=xe("Deformer",s,`SubDeformer::${t}`,"BlendShapeChannel",[be(100),{name:"DeformPercent",properties:[{type:"float64",value:0}],children:[]},{name:"Properties60",properties:[],children:[{name:"Property",properties:[{type:"string",value:"DeformPercent"},{type:"string",value:"Number"},{type:"string",value:"A"},{type:"float64",value:0}],children:[]}]}]);i.set(s,d),a.push({id:s,node:d,source:"legacySyntheticBlendShape",legacyName:`${n}|${t}`,synthetic:!0}),Te(c,l,u,h,"OO",s,r);const f=C("Shape",`${n}|${t}`),p=xe("Geometry",f,`Geometry::${t}`,"Shape",e.children);i.set(f,p),a.push({id:f,node:p,source:"legacySyntheticBlendShape",legacyName:`${n}|${t}`,synthetic:!0}),Te(c,l,u,h,"OO",f,s)}};if(g)for(const e of g.children){const t=e.properties[0];if(t){const n=M(t);if(void 0!==n)i.set(n,e),a.push({id:n,node:e,source:"Objects",synthetic:!1}),"Geometry"===e.name&&"Mesh"===oe(e,2)&&R(e,n,String(n));else if("string"==typeof t.value){const n=t.value,o=S(n),s=Ae(e,o);i.set(o,s),a.push({id:o,node:s,source:"Objects",legacyName:n,synthetic:!1});const r="Model"===e.name?oe(e,1):void 0;if("Mesh"===r){const t=C("Geometry",n),s=Me(e,t);i.set(t,s),a.push({id:t,node:s,source:"legacySyntheticGeometry",legacyName:n,synthetic:!0}),Te(c,l,u,h,"OO",t,o),_.set(o,t),R(e,t,n)}else if("Light"===r||"Camera"===r){const t=C("NodeAttribute",n),s=xe("NodeAttribute",t,`NodeAttribute::${re(n)}`,r,e.children);i.set(t,s),a.push({id:t,node:s,source:"legacySyntheticAttribute",legacyName:n,synthetic:!0}),Te(c,l,u,h,"OO",t,o)}}}}if(v)for(const e of v.children){if("C"!==e.name&&"Connect"!==e.name)continue;const t=d.length;let n,a=oe(e,0),f=e.properties[1],p=e.properties[2];"PO"===a&&"string"==typeof(null===(o=e.properties[2])||void 0===o?void 0:o.value)&&e.properties.length>3&&(a="OP",n=e.properties[2].value,f=e.properties[3],p=e.properties[1]);const m={source:e.name,rawType:a,accepted:!1};if(d.push(m),"OO"!==a&&"OP"!==a){const e=w(f),n=w(p);h.push({reason:"unsupported-connection-type",message:`Unsupported FBX connection type '${null!=a?a:""}' was not added to the graph.`,connectionIndex:t,type:a,childId:e,parentId:n});continue}if(void 0===f||void 0===p){h.push({reason:"missing-connection-endpoint",message:"FBX connection is missing a child or parent endpoint.",connectionIndex:t,type:a});continue}const g=w(f);let v=w(p);if(void 0!==g&&void 0!==v&&"Deformer"===(null===(s=i.get(g))||void 0===s?void 0:s.name)&&(v=null!==(r=_.get(v))&&void 0!==r?r:v),void 0===g||void 0===v){h.push({reason:"unresolved-legacy-endpoint",message:"FBX connection references a legacy string endpoint that is not present in the object table.",connectionIndex:t,type:a});continue}const y=null!=n?n:"OP"===a&&e.properties.length>3?oe(e,3):void 0;m.childId=g,m.parentId=v,m.propertyName=y,g===v&&h.push({reason:"self-loop",message:"FBX connection references the same object as child and parent.",connectionIndex:t,type:a,childId:g,parentId:v,propertyName:y}),i.has(g)||h.push({reason:"unresolved-object-reference",message:"FBX connection child ID is not present in the object table.",connectionIndex:t,type:a,childId:g,parentId:v,propertyName:y}),0===v||i.has(v)||h.push({reason:"unresolved-object-reference",message:"FBX connection parent ID is not present in the object table.",connectionIndex:t,type:a,childId:g,parentId:v,propertyName:y}),Te(c,l,u,h,a,g,v,y,t),m.accepted=!0}return{objects:i,objectEntries:a,childrenOf:l,parentOf:u,connections:c,connectionEntries:d,diagnostics:h}}(e),s=function(e){const t=new Map,n=ne(e,"Definitions");if(!n)return t;for(const e of n.children){if("ObjectType"!==e.name)continue;const n=oe(e,0);if(n)for(const o of e.children){if("PropertyTemplate"!==o.name)continue;const e=oe(o,0);if(!e)continue;const s=he(n,e,o);let r=t.get(n);r||(r=new Map,t.set(n,r)),r.set(e,s)}}return t}(e),r=function(e){var t;const n={upAxis:1,upAxisSign:1,frontAxis:2,frontAxisSign:1,coordAxis:0,coordAxisSign:1,unitScaleFactor:1,frameRate:30},o=ne(e,"GlobalSettings");if(!o)return n;let s=0,r=24;for(const{name:e,values:t}of fe(o)){const o=ao(t[0]);if(e&&void 0!==o)switch(e){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;break;case"TimeMode":s=o;break;case"CustomFrameRate":r=o}}return n.frameRate=14===s?r>0?r:24:null!==(t=oo[s])&&void 0!==t?t:30,n}(e),i=[];for(const[e,t]of Array.from(o.objects))"Material"===t.name&&i.push(Rt(t,e,o,s));!function(e,t,n){var o,s,r,i;const a=new Map(t.map(e=>[e.id,e])),l=null!==(o=ie(n,"Texture","FbxFileTexture"))&&void 0!==o?o:ie(n,"Texture");for(const[t,n]of Array.from(e.objects)){if("Model"!==n.name)continue;const o=ye(e,t,"Texture");if(0===o.length)continue;const u=ye(e,t,"Material").filter(e=>!e.propertyName).map(e=>a.get(e.id)).filter(e=>void 0!==e);if(0===u.length)continue;const c=null!==(r=null===(s=ye(e,t,"Geometry")[0])||void 0===s?void 0:s.node)&&void 0!==r?r:n,d=te(c,"LayerElementMaterial"),h=d?se(te(d,"Materials")):null,f=e=>{switch(e.replace(/^LayerElement/,"").replace(/Textures?$/,"")){case"":case"Diffuse":return{prop:"DiffuseColor",fbx:"diffuseColor",pbr:"baseColor"};case"Emissive":return{prop:"EmissiveColor",fbx:"emissionColor",pbr:"emissionColor"};case"Specular":return{prop:"SpecularColor",fbx:"specularColor",pbr:"specularColor"};case"Ambient":return{prop:"AmbientColor",fbx:"ambientColor",pbr:"ambientOcclusion"};case"Bump":case"NormalMap":return{prop:"NormalMap",fbx:"normalMap",pbr:"normalMap"};case"Transparent":return{prop:"TransparentColor",fbx:"transparencyColor",pbr:"opacity"};case"Reflection":return{prop:"ReflectionColor",fbx:"reflectionColor",pbr:"specularColor"};case"Shininess":return{prop:"ShininessExponent",fbx:"specularExponent",pbr:"roughness"};case"Displacement":return{prop:"DisplacementColor",fbx:"displacement",pbr:"displacementMap"};default:return null}},p=c.children.filter(e=>/^LayerElement\w*Textures?$/.test(e.name)),m=o.map(({id:t,node:n})=>Ot(t,n,void 0,e,l)),_=(e,t,n)=>{var o,s,r,i,a,l;const c=u[e],d=m[t];if(!c||!d||c.textures.some(e=>e.propertyName===n.prop))return;const h=Object.assign(Object.assign({},d),{propertyName:n.prop});c.textures.push(h);const f=null!==(o=(r=c.model.fbx)[i=n.fbx])&&void 0!==o?o:r[i]={valueComponents:0,textureEnabled:!1};f.texture=h,f.textureEnabled=!0;const p=null!==(s=(a=c.model.pbr)[l=n.pbr])&&void 0!==s?s:a[l]={valueComponents:0,textureEnabled:!1};p.texture=h,p.textureEnabled=!0};if(0!==p.length)for(const e of p){const t=f(e.name),n=se(te(e,"TextureId"));if(!t||!n||0===n.length)continue;const o=Math.max(n.length,null!==(i=null==h?void 0:h.length)&&void 0!==i?i:0);for(let e=0;e<o;e++){const o=n[Math.min(e,n.length-1)],s=h&&h.length>0?h[Math.min(e,h.length-1)]:0;o>=0&&_(s,o,t)}}else 1===u.length&&1===m.length&&_(0,0,f("LayerElementTexture"))}}(o,i,s);const a=[],l=[];for(const[e,n]of Array.from(o.objects))if("Geometry"===n.name){const s=oe(n,2);if("Mesh"===s){const t=we(n,e);t.positions.length>0&&t.indices.length>0&&a.push(t)}else if("NurbsSurface"===s){const s=Ke(n,e,t.nurbsSubdivision);s&&(Jn(o,e,s),a.push(s))}else if("TrimNurbsSurface"===s){const n=ye(o,e,"Geometry").find(e=>"NurbsSurface"===oe(e.node,2)),s=n?Ke(n.node,e,t.nurbsSubdivision):null;s&&(Jn(o,e,s),s.diagnostics.push({type:"nurbs-trim-ignored",message:`Trim curves of NURBS surface '${s.name}' are ignored; the surface is rendered untrimmed.`}),a.push(s))}else"NurbsCurve"===s?l.push(We(n,e)):"Line"===s&&l.push(qe(n,e))}const u=function(e,t){var n;Bt=t?null!==(n=ie(t,"Model","FbxNode"))&&void 0!==n?n:ie(t,"Model"):void 0;const o=[];for(const[t,n]of Array.from(e.objects))if("Deformer"===n.name&&"Skin"===oe(n,2)){const n=Pt(t,0,e);n&&o.push(n)}return o}(o,s),c=function(e,t){if(0===t.length)return[];const n=new Map;for(const o of t){const t=o.bones.filter(e=>e.isCluster).map(e=>e.modelId);if(0===t.length)continue;const s=Wt(t,e),r=n.get(s);r?r.push(o):n.set(s,[o])}return Array.from(n.entries()).sort(([e],[t])=>Qt(e,t)).map(([t,n])=>function(e,t,n){var o,s;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 qt(t.modelId,n))i.add(e)}}const u=Array.from(i);for(;u.length>0;){const e=u.pop();for(const t of n.connections){if("OO"!==t.type||t.parentId!==e||i.has(t.childId))continue;const o=n.objects.get(t.childId);o&&"Model"===o.name&&Vt(o)&&(i.add(t.childId),u.push(t.childId))}}const c=function(e){const t=[];for(const[n,o]of Array.from(e)){const e=o.filter(e=>e.isCluster&&e.transformLinkMatrix).map(e=>e.transformLinkMatrix);if(e.length<2)continue;const s=e[0];e.some(e=>!Xt(s,e,1e-5))&&t.push(`Model ${n.toString()} has differing Cluster.TransformLink matrices across skins`)}return t}(a),d=new Map;for(const[e,t]of Array.from(a))d.set(e,jt(t));const h=function(e,t){const n=new Map;for(const o of Array.from(e)){const s=zt(o,t);void 0!==s&&e.has(s)&&n.set(o,s)}return n}(i,n),f=function(e,t,n){var o;const s=new Map;for(const n of Array.from(e)){const e=t.get(n);if(void 0===e)continue;let o=s.get(e);o||(o=[],s.set(e,o)),o.push(n)}for(const e of Array.from(s.values()))e.sort((e,t)=>Zt(e,t,n));const r=[],i=[...Array.from(e).filter(e=>!t.has(e)).sort((e,t)=>Zt(e,t,n))];for(;i.length>0;){const e=i.shift();r.push(e),i.push(...null!==(o=s.get(e))&&void 0!==o?o:[])}return r}(i,h,l),p=[],m=new Map;for(const e of f){const t=null!==(o=d.get(e))&&void 0!==o?o:Yt(e,n);if(!t)continue;const i=h.get(e),a=void 0===i?-1:null!==(s=m.get(i))&&void 0!==s?s:-1,l=p.length,u=Object.assign(Object.assign({},t),{index:l,parentIndex:a,isCluster:r.has(e)});p.push(u),m.set(e,l)}const _=t.map(t=>function(e,t,n){const o=e.bones.map(e=>{const o=n.get(e.modelId);if(void 0===o&&e.isCluster)throw new Error(`FBX rig resolver: cluster bone ${e.name} is missing from resolved rig ${t}`);return null!=o?o:-1});return{skinId:e.id,geometryId:e.geometryId,rigId:t,skinBoneIndexToRigBoneIndex:o,clusterModelIds:new Set(e.bones.filter(e=>e.isCluster).map(e=>e.modelId))}}(t,`rig_${e.toString()}`,m));return{id:`rig_${e.toString()}`,rootModelIds:p.filter(e=>e.parentIndex<0).map(e=>e.modelId),bones:p,modelIdToBoneIndex:m,clusterModelIds:r,skinBindings:_,warnings:c}}(t,n,e))}(o,u),d=function(e){const t=[];for(const[n,o]of Array.from(e.objects))if("Deformer"===o.name&&"BlendShape"===oe(o,2)){const o=Kn(n,0,e);o&&t.push(o)}return t}(o),h=function(e,t,n={}){var o;const s=[],r=null===(o=n.rebaseKeyframes)||void 0===o||o;for(const[t,n]of Array.from(e.objects))if("AnimationStack"===n.name){const o=yn(t,n,e,r);o&&s.push(o)}return 0===s.length&&t&&s.push(...function(e,t,n=!0){var o,s,r,i,a,l;const u=ne(e,"Takes");if(!u)return[];const c=new Map,d=new Map;for(const e of t.objectEntries)if(void 0!==e.legacyName&&!e.synthetic&&!c.has(e.legacyName)){c.set(e.legacyName,e.id);const t=re(e.legacyName);d.has(t)||d.set(t,e.id)}const h=[];let f=-1e6;for(const p of u.children){if("Take"!==p.name)continue;const u=re(null!==(o=oe(p,0))&&void 0!==o?o:"Take"),m=null!==(s=Pn(te(p,"LocalTime")))&&void 0!==s?s:Pn(te(p,"ReferenceTime")),_=[],g=[];let v=1/0,y=-1/0;const b=e=>{for(const t of e)for(const e of t.keys)e.time<v&&(v=e.time),e.time>y&&(y=e.time)};for(const n of p.children){if("Model"!==n.name)continue;const o=null!==(r=oe(n,0))&&void 0!==r?r:"",s=null!==(i=c.get(o))&&void 0!==i?i:d.get(re(o));if(void 0!==s)for(const o of n.children){if("Channel"!==o.name)continue;const n=null!==(a=oe(o,0))&&void 0!==a?a:"";if("Transform"===n)for(const t of o.children){if("Channel"!==t.name)continue;const n=oe(t,0);if("T"!==n&&"R"!==n&&"S"!==n)continue;const o=Dn(t,e.version);o.length>0&&(b(o),_.push({type:n,targetModelId:s,curves:o,layerIndex:0}))}else{const r=Dn(o,e.version);if(r.length>0){b(r);const e=Bn(t,s,n);if(void 0!==e){_.push({type:"DeformPercent",targetModelId:e,curves:r,layerIndex:0});continue}const o=kn.has(n)?null===(l=ye(t,s,"NodeAttribute")[0])||void 0===l?void 0:l.id:void 0;g.push({type:n,id:f--,layerIndex:0,targetId:null!=o?o:s,propertyName:n,curveCount:r.length,curves:r,defaultValues:{}})}}}}if(0===_.length&&0===g.length)continue;const x={name:"BaseLayer",weight:100,normalizedWeight:1,blendMode:0,blend:Rn(0,100,0,0),curveNodes:_,unsupportedCurveNodes:g,diagnostics:[]};h.push(bn(u,[x],_,g,[],v,y,m,n))}return h}(t,e,r)),s}(o,e,{rebaseKeyframes:null===(n=t.rebaseKeyframes)||void 0===n||n}),f=function(e,t){var n,o,s,r;const i=[],a=null!==(n=ie(t,"NodeAttribute","FbxCamera"))&&void 0!==n?n:ie(t,"NodeAttribute");for(const[t,n]of Array.from(e.objects)){if("NodeAttribute"!==n.name)continue;if("Camera"!==oe(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=re(null!==(o=oe(u,1))&&void 0!==o?o:"Camera"),d=le(n,a,"NearPlane",.1),h=le(n,a,"FarPlane",1e4),f=1===le(n,a,"CameraProjectionType",0)||1===le(n,a,"ProjectionType",0)?"orthographic":"perspective",p=ao(ae(n,a,"FocalLength")),m=null!==(s=ao(ae(n,a,"FilmWidth")))&&void 0!==s?s:ao(ae(n,a,"ApertureWidth")),_=null!==(r=ao(ae(n,a,"FilmHeight")))&&void 0!==r?r:ao(ae(n,a,"ApertureHeight")),g=ao(ae(n,a,"OrthoZoom")),v=ao(ae(n,a,"Roll")),y=co(n,a),b=y.aspectRatio,x=y.fovDegY,T=[];"orthographic"===f&&void 0===g&&T.push("Orthographic camera has no OrthoZoom; runtime orthographic bounds use a fallback."),void 0!==p&&void 0===_&&void 0===ae(n,a,"FieldOfView")&&T.push("FocalLength is present without FilmHeight; default field of view fallback may be used."),i.push({modelId:l.id,attributeId:t,userProperties:pe(n),name:c,fieldOfView:x,fieldOfViewX:y.fovDegX,apertureMode:y.apertureMode,apertureSizeInch:y.apertureSizeInch,orthographicSize:y.orthographicSize,nearPlane:d,farPlane:h,aspectRatio:b,projectionType:f,focalLength:p,filmWidth:m,filmHeight:_,orthoZoom:g,roll:v,unknownProperties:ho(n,ro),diagnostics:T})}return i}(o,s),p=function(e,t){var n,o,s,r,i;const a=[],l=null!==(n=ie(t,"NodeAttribute","FbxLight"))&&void 0!==n?n:ie(t,"NodeAttribute");for(const[t,n]of Array.from(e.objects)){if("NodeAttribute"!==n.name)continue;if("Light"!==oe(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=re(null!==(o=oe(c,1))&&void 0!==o?o:"Light"),h=le(n,l,"LightType",0),f=ue(n,l,"Color",[1,1,1]),p=le(n,l,"Intensity",100)/100,m=null!==(s=ao(ae(n,l,"OuterAngle")))&&void 0!==s?s:ao(ae(n,l,"ConeAngle")),_=ao(ae(n,l,"InnerAngle")),g=null!=m?m:45,v=le(n,l,"DecayType",2),y=ao(ae(n,l,"DecayStart")),b=lo(ae(n,l,"EnableNearAttenuation")),x=lo(ae(n,l,"EnableFarAttenuation")),T=null!==(i=null!==(r=lo(ae(n,l,"CastShadow")))&&void 0!==r?r:lo(ae(c,void 0,"CastShadow")))&&void 0!==i?i:lo(ae(c,void 0,"Shadow")),A=[];2!==v&&A.push(`DecayType ${v} is preserved as metadata; Babylon falloff is not remapped in this pass.`),void 0!==y&&A.push("DecayStart is preserved as metadata and is not mapped to Babylon light range."),a.push({modelId:u.id,attributeId:t,userProperties:pe(n),nearAttenuationStart:ao(ae(n,l,"NearAttenuationStart")),nearAttenuationEnd:ao(ae(n,l,"NearAttenuationEnd")),farAttenuationStart:ao(ae(n,l,"FarAttenuationStart")),farAttenuationEnd:ao(ae(n,l,"FarAttenuationEnd")),areaLightShape:ao(ae(n,l,"AreaLightShape")),name:d,lightType:h,color:f,intensity:p,coneAngle:g,decayType:v,innerAngle:_,outerAngle:m,decayStart:y,enableNearAttenuation:b,enableFarAttenuation:x,castShadows:T,unknownProperties:ho(n,io),diagnostics:A})}return a}(o,s),m=function(e){var t,n,o;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[r,i]of Array.from(e.objects)){const a=null!==(t=oe(i,2))&&void 0!==t?t:"";if("Constraint"===i.name){const t=i.children.find(e=>"Type"===e.name),l=null!==(n=t?oe(t,0):void 0)&&void 0!==n?n:a;new Set(["Aim","Parent-Child","Position From Positions","Rotation From Rotations","Scale From Scales"]).has(l)||s.push(Zn(e,r,i,"unsupported-constraint",`Constraint '${l||re(null!==(o=oe(i,1))&&void 0!==o?o:"")}' is preserved as metadata but not evaluated at runtime.`));continue}Xn.has(i.name)?s.push(Zn(e,r,i,"unsupported-helper",`${i.name} helper data is preserved as diagnostic data but not evaluated at runtime.`)):"LayeredTexture"!==i.name?"Pose"!==i.name||"BindPose"===a?"Deformer"!==i.name||Qn(a)?"NodeAttribute"===i.name&&a&&!Yn.has(a)&&s.push(Zn(e,r,i,"unsupported-node-attribute",`NodeAttribute subtype '${a}' is preserved as diagnostic data but not converted to a Babylon object.`)):s.push(Zn(e,r,i,"unsupported-deformer",`Deformer subtype '${a}' is preserved as diagnostic data but not evaluated at runtime.`)):s.push(Zn(e,r,i,"unsupported-pose",`Pose subtype '${a}' is preserved as diagnostic data but not evaluated at runtime.`)):s.push(Zn(e,r,i,"unsupported-layered-texture","LayeredTexture is preserved as diagnostic data; runtime texture layer blending is not implemented."))}return s}(o),_=function(e){const t=[];for(const[n,o]of Array.from(e.objects))"Constraint"===o.name&&t.push(ft(n,o,e));return t}(o),g=function(e,t,n,o,s){var r;const i=new Map;for(const e of t)i.set(e.id,e);const a=new Map;for(const e of n)a.set(e.id,e);const l=new Map;for(const e of o)l.set(e.id,e);const u=null!==(r=e.childrenOf.get(0))&&void 0!==r?r:[],c=[],d=new Set,h=new Set;for(const{id:t}of u){const n=e.objects.get(t);n&&"Model"===n.name&&!d.has(t)&&(d.add(t),c.push(no(t,n,e,i,a,l,s,h)))}const f=new Set;for(const t of e.connections){if("OO"!==t.type)continue;const n=e.objects.get(t.parentId);0!==t.parentId&&"Model"!==(null==n?void 0:n.name)||f.add(t.childId)}for(const[t,n]of Array.from(e.objects))"Model"!==n.name||f.has(t)||d.has(t)||(d.add(t),c.push(no(t,n,e,i,a,l,s,h)));return c}(o,a,l,i,s),{displayLayers:v,selectionSets:y}=function(e,t){var n,o,s,r,i;const a=new Map,l=e=>{for(const t of e)a.set(t.id,t),l(t.children)};l(t);const u=[],c=[];for(const[t,l]of Array.from(e.objects))if("CollectionExclusive"===l.name){const s=fe(l),r=(e,t)=>{var n;const o=null===(n=s.find(t=>t.name===e))||void 0===n?void 0:n.values[0];return"number"==typeof o?o:"boolean"==typeof o?o?1:0:t},i=null===(n=s.find(e=>"Color"===e.name))||void 0===n?void 0:n.values,c=i&&"number"==typeof i[0]&&"number"==typeof i[1]&&"number"==typeof i[2]?[i[0],i[1],i[2]]:[.8,.8,.8],d={id:t,name:re(null!==(o=oe(l,1))&&void 0!==o?o:"DisplayLayer"),show:0!==r("Show",1),freeze:0!==r("Freeze",0),color:c,modelIds:ye(e,t,"Model").map(e=>e.id)};u.push(d);for(const e of d.modelIds){const t=a.get(e);t&&(t.displayLayer=d)}}else if("SelectionSet"===l.name||"Collection"===l.name&&"SelectionSet"===oe(l,2)){const n=[];for(const o of ye(e,t))if("Model"===o.node.name)n.push({modelId:o.id,includeNode:!0});else if("SelectionNode"===o.node.name){const t=e=>{const t=te(o.node,e);if(t)return Array.from(se(t))},i=null===(r=null===(s=te(o.node,"IsTheNodeInSet"))||void 0===s?void 0:s.properties[0])||void 0===r?void 0:r.value;for(const s of ye(e,o.id,"Model"))n.push({modelId:s.id,includeNode:void 0===i||1===i||!0===i,vertices:t("VertexIndexArray"),edges:t("EdgeIndexArray"),faces:t("PolygonIndexArray")})}c.push({id:t,name:re(null!==(i=oe(l,1))&&void 0!==i?i:"SelectionSet"),members:n})}return{displayLayers:u,selectionSets:c}}(o,g);return Object.assign({rootModels:g,displayLayers:v,selectionSets:y,constraints:_,geometries:a,curves:l,materials:i,skins:u,rigs:c,blendShapes:d,animations:h,cameras:f,lights:p,diagnostics:m},r)}const to=512;function no(e,t,n,o,s,r,i,a){var l,u,c,d;const h=re(null!==(l=oe(t,1))&&void 0!==l?l:"Model");a.add(e);const f=null!==(u=oe(t,2))&&void 0!==u?u:"Null",p=ye(n,e,"Geometry"),m=p.map(e=>o.get(e.id)).find(e=>void 0!==e),_=p.map(e=>s.get(e.id)).find(e=>void 0!==e),g=ye(n,e,"Material"),v=[];for(const{id:e}of g){const t=r.get(e);t&&v.push(t)}const y=function(e,t){return ve(e,t)}(t,null!==(c=ie(i,"Model","FbxNode"))&&void 0!==c?c:ie(i,"Model")),b=ye(n,e,"Model").filter(e=>!e.propertyName),x=[],T=[];for(const{id:e,node:t}of b){if(a.size>to){T.push(`Model hierarchy deeper than ${to} levels; deeper children were skipped.`);break}a.has(e)?T.push(`Model connection cycle detected at '${re(null!==(d=oe(t,1))&&void 0!==d?d:"")}'; the recursive child was skipped.`):x.push(no(e,t,n,o,s,r,i,a))}a.delete(e);const A=t.children.find(e=>"Culling"===e.name),M=!!A&&"CullingOff"===oe(A,0),w=function(e){const t=pe(e);if(!t)return;let n=!1;const o={};for(const e of Object.keys(t))so.has(e)||(o[e]=t[e],n=!0);return n?o:void 0}(t);let S;if("LodGroup"===f){const t=ye(n,e,"NodeAttribute").find(e=>"LodGroup"===oe(e.node,2)),o=t?fe(t.node):[],s=[],r=[];for(let e=0;;e++){const t=o.find(t=>t.name===`Thresholds|Level${e}`);if(!t)break;s.push("number"==typeof t.values[0]?t.values[0]:0)}for(let e=0;;e++){const t=o.find(t=>t.name===`DisplayLevels|Level${e}`);if(!t)break;r.push("number"==typeof t.values[0]?t.values[0]:0)}const i=o.find(e=>"ThresholdsUsedAsPercentage"===e.name);S={thresholds:s,relative:!!i&&0!==i.values[0]&&!1!==i.values[0],displayLevels:r}}return Object.assign(Object.assign({id:e,name:h,subType:f,geometry:m,materials:v,children:x,cullingOff:M,customProperties:w,lodGroup:S,curve:_},y),{diagnostics:[...y.diagnostics,...T]})}const oo=[30,120,100,60,50,48,30,30,29.97,29.97,25,24,1e3,23.976,24,96,72,59.94],so=new Set(["Lcl Translation","Lcl Rotation","Lcl Scaling","PreRotation","PostRotation","RotationPivot","ScalingPivot","RotationOffset","ScalingOffset","RotationOrder","GeometricTranslation","GeometricRotation","GeometricScaling","Visibility","InheritType","ScalingMax","DefaultAttributeIndex","currentUVSet","lockInfluenceWeights"]),ro=new Set(["FieldOfView","FieldOfViewX","FieldOfViewY","NearPlane","FarPlane","AspectWidth","AspectHeight","FilmAspectRatio","FocalLength","FilmWidth","FilmHeight","ApertureWidth","ApertureHeight","CameraProjectionType","ProjectionType","OrthoZoom","Roll","ApertureMode"]),io=new Set(["LightType","Color","Intensity","InnerAngle","OuterAngle","ConeAngle","DecayType","DecayStart","EnableNearAttenuation","EnableFarAttenuation","CastShadow","Shadow"]);function ao(e){if("number"==typeof e)return e}function lo(e){return"boolean"==typeof e?e:"number"==typeof e?0!==e:void 0}const uo=[[1e3,1e3],[404,295],[493,292],[864,630],[816,612],[980,735],[825,446],[864,732],[2066,906],[1485,991],[2080,1480],[2772,2072]];function co(e,t){const n=(n,o)=>{var s;return null!==(s=ao(ae(e,t,n)))&&void 0!==s?s:o},o=n("AspectRatioMode",0),s=n("ApertureMode",2),r=Math.max(0,Math.min(uo.length-1,Math.round(n("ApertureFormat",0)))),i=n("GateFit",0);let a=n("AspectW",0),l=n("AspectH",0);a=n("AspectWidth",a),l=n("AspectHeight",l);const u=n("FieldOfView",0),c=n("FieldOfViewX",0),d=n("FieldOfViewY",0),h=n("FocalLength",0),f=30*n("OrthoZoom",1),p=uo[r];let m=n("FilmWidth",.001*p[0]),_=n("FilmHeight",.001*p[1]);a<=0&&l<=0?(a=m>0?m:1,l=_>0?_:1):a<=0?a=m>0&&_>0?l/_*m:l:l<=0&&(l=m>0&&_>0?a/m*_:a),_*=n("FilmSqueezeRatio",7===r?2:1);let g=a,v=l;switch(o){case 3:g=a,v=a*l;break;case 4:g=l*a,v=l}const y=0!==v?g/v:1,b=0!==_?m/_:1;let x=i;3===x?x=y>b?2:1:4===x&&(x=y<b?2:1);let T=m,A=_,M=f,w=f;switch(x){case 1:T=_*y,A=_,M=f*y;break;case 2:T=m,A=m/y,w=f/y}m=T;const S=Math.PI/180,C=180/Math.PI;let R,I;switch(s){case 0:R=Math.tan(c*S*.5),I=Math.tan(d*S*.5);break;case 1:R=Math.tan(u*S*.5),I=R/y;break;case 3:{const e=h/25.4;R=e>0?T/e*.5:Math.tan(u*S*.5)*y,I=e>0?A/e*.5:Math.tan(u*S*.5);break}default:I=Math.tan(u*S*.5),R=I*y}return{fovDegX:Math.atan(R)*C*2,fovDegY:Math.atan(I)*C*2,aspectRatio:y,apertureMode:s,apertureSizeInch:[T,A],orthographicSize:[M,w]}}function ho(e,t){var n;const o=new Set;for(const s of["Properties70","Properties60"]){const r=te(e,s);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=oe(e,0);n&&!t.has(n)&&o.add(n)}}return Array.from(o).sort()}function fo(e,n,o){const s=t.Matrix.RotationX(e),r=t.Matrix.RotationY(n),i=t.Matrix.RotationZ(o);return s.multiply(r).multiply(i)}function po(e,n,o,s){const r=t.Matrix.RotationX(e),i=t.Matrix.RotationY(n),a=t.Matrix.RotationZ(o);switch(s){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 mo(e,n){const o=Math.PI/180,s=t.Matrix.Scaling(n[0],n[1],n[2]),r=fo(e[0]*o,e[1]*o,e[2]*o);return s.multiply(r)}const _o=Math.PI/180,go={invRoot:new t.Matrix,parent:new t.Matrix,invParent:new t.Matrix,world:new t.Matrix,local:new t.Matrix,mA:new t.Matrix,mB:new t.Matrix,mC:new t.Matrix,mD:new t.Matrix,position:new t.Vector3,scale:new t.Vector3,translation:new t.Vector3,decomposedScale:new t.Vector3,localValue:new t.Vector3,up:new t.Vector3,forward:new t.Vector3,origin:new t.Vector3,axisA:new t.Vector3,axisB:new t.Vector3,axisC:new t.Vector3,eulerA:new t.Vector3,eulerB:new t.Vector3,rotation:new t.Quaternion,decomposedRotation:new t.Quaternion,result:new t.Quaternion},vo=new WeakMap;class yo{constructor(e){this._behaviors=[],this._ordered=[],this._cyclic=[],this._dirty=!1,this._beforeAnimations=null,this._afterAnimations=null,this._scene=e}static Get(e){return vo.get(e)}static GetOrCreate(e){let t=vo.get(e);return t||(t=new yo(e),vo.set(e,t)),t}get constraints(){return this._ensureOrder(),this._ordered}get cyclicConstraints(){return this._ensureOrder(),this._cyclic}register(e){this._behaviors.indexOf(e)>=0||(this._behaviors.push(e),this._dirty=!0,this._beforeAnimations||(this._beforeAnimations=this._scene.onBeforeAnimationsObservable.add(()=>this.beginFrame()),this._afterAnimations=this._scene.onAfterAnimationsObservable.add(()=>this.solve())))}unregister(e){const t=this._behaviors.indexOf(e);t<0||(this._behaviors.splice(t,1),this._dirty=!0,0===this._behaviors.length&&(this._scene.onBeforeAnimationsObservable.remove(this._beforeAnimations),this._scene.onAfterAnimationsObservable.remove(this._afterAnimations),this._beforeAnimations=null,this._afterAnimations=null,vo.delete(this._scene)))}invalidateOrder(){this._dirty=!0}beginFrame(){for(const e of this._behaviors)e.restoreBase()}solve(){this._ensureOrder();for(const e of this._behaviors)e.captureBase();for(const e of this._ordered)e.evaluate()}_ensureOrder(){if(!this._dirty)return;this._dirty=!1;const e=this._behaviors,t=e.length,n=e.map(()=>[]);for(let o=0;o<t;o++){const s=e[o].dependencyNodes();for(let r=0;r<t;r++){if(o===r)continue;const t=e[r].attachedNode;t&&s.some(e=>yo._IsAncestorOrSelf(t,e))&&n[o].push(r)}}const o=n.map(e=>e.length),s=e.map(()=>!1),r=[];let i=!0;for(;i;){i=!1;for(let a=0;a<t;a++)if(!(s[a]||o[a]>0)){s[a]=!0,r.push(e[a]),i=!0;for(let e=0;e<t;e++)!s[e]&&n[e].indexOf(a)>=0&&o[e]--}}const a=[];for(let n=0;n<t;n++)s[n]||(a.push(e[n]),r.push(e[n]));this._ordered=r,this._cyclic=a}static _IsAncestorOrSelf(e,t){let n=t;for(;n;){if(n===e)return!0;n=n.parent}return!1}}class bo{constructor(e,n){this.constraint=e,this._options=n,this.attachedNode=null,this.enabled=!0,this._base={position:new t.Vector3,rotation:new t.Quaternion,scaling:new t.Vector3},this._hasBase=!1,this.name=`fbxConstraint:${e.name}`,this._offsetTranslation=new t.Vector3(e.offsetTranslation[0],e.offsetTranslation[1],e.offsetTranslation[2]),this._offsetRotation=fo(e.offsetRotation[0]*_o,e.offsetRotation[1]*_o,e.offsetRotation[2]*_o),this._offsetScale=new t.Vector3(e.offsetScale[0],e.offsetScale[1],e.offsetScale[2]);const o=new t.Matrix;this._localBasisTransposed=bo._OrthonormalBasisToRef(new t.Vector3(e.aimVector[0],e.aimVector[1],e.aimVector[2]),new t.Vector3(e.upVector[0],e.upVector[1],e.upVector[2]),o)?o.transpose():null}init(){}attach(e){this.attachedNode=e,yo.GetOrCreate(e.getScene()).register(this),this.captureBase(),this.evaluate()}detach(){var e;this.attachedNode&&(null===(e=yo.Get(this.attachedNode.getScene()))||void 0===e||e.unregister(this)),this.attachedNode=null,this._hasBase=!1}captureBase(){const e=this.attachedNode;e&&(e.rotationQuaternion||(e.rotationQuaternion=t.Quaternion.FromEulerVector(e.rotation)),this._base.position.copyFrom(e.position),this._base.rotation.copyFrom(e.rotationQuaternion),this._base.scaling.copyFrom(e.scaling),this._hasBase=!0)}restoreBase(){const e=this.attachedNode;e&&this._hasBase&&(e.position.copyFrom(this._base.position),e.rotationQuaternion.copyFrom(this._base.rotation),e.scaling.copyFrom(this._base.scaling))}dependencyNodes(){const e=this._options.targets.map(e=>e.node);return e.push(this._options.upNode),e.push(this.attachedNode?this.attachedNode.parent:null),e}evaluate(){const e=this.attachedNode,n=this.constraint;if(!e||!this.enabled||!n.active||n.weight<=0||0===this._options.targets.length)return;this._hasBase||this.captureBase(),this._options.root.computeWorldMatrix(!0).invertToRef(go.invRoot);const o=e.parent;switch(o&&"function"==typeof o.computeWorldMatrix?this._fbxWorld(o,go.parent):t.Matrix.IdentityToRef(go.parent),go.parent.invertToRef(go.invParent),n.type){case"position":this._solvePosition(e);break;case"rotation":this._solveRotation(e);break;case"scale":this._solveScale(e);break;case"parent":this._solveParent(e);break;case"aim":this._solveAim(e)}}_fbxWorld(e,t){return e.computeWorldMatrix(!0).multiplyToRef(go.invRoot,t),t}_blendTargets(e,n,o){e.set(0,0,0),o.set(0,0,0),n.set(0,0,0,1);let s=0;for(const r of this._options.targets){if(r.weight<=0)continue;r.offset.multiplyToRef(this._fbxWorld(r.node,go.world),go.local),go.local.decompose(go.decomposedScale,go.decomposedRotation,go.translation);const i=s+r.weight;e.addInPlace(go.translation.scaleInPlace(r.weight)),o.addInPlace(go.decomposedScale.scaleInPlace(r.weight)),0===s?n.copyFrom(go.decomposedRotation):t.Quaternion.SlerpToRef(n,go.decomposedRotation,r.weight/i,n),s=i}return s>0&&(e.scaleInPlace(1/s),o.scaleInPlace(1/s)),s}_applyWeighted(e,t,n,o){const s=this.constraint.weight;o.set(n[0]?e.x+(t.x-e.x)*s:e.x,n[1]?e.y+(t.y-e.y)*s:e.y,n[2]?e.z+(t.z-e.z)*s:e.z)}_applyRotation(e,n,o){const s=this._base.rotation,r=go.result;r.copyFrom(n),o[0]&&o[1]&&o[2]||(s.toEulerAnglesToRef(go.eulerA),n.toEulerAnglesToRef(go.eulerB),t.Quaternion.FromEulerAnglesToRef(o[0]?go.eulerB.x:go.eulerA.x,o[1]?go.eulerB.y:go.eulerA.y,o[2]?go.eulerB.z:go.eulerA.z,r)),this.constraint.weight<1&&t.Quaternion.SlerpToRef(s,r,this.constraint.weight,r),e.rotationQuaternion.copyFrom(r)}_writePosition(e,t){this._applyWeighted(this._base.position,t,this.constraint.affectTranslation,e.position)}_writeScaling(e,t){this._applyWeighted(this._base.scaling,t,this.constraint.affectScale,e.scaling)}_solvePosition(e){0!==this._blendTargets(go.position,go.rotation,go.scale)&&(t.Vector3.TransformCoordinatesToRef(go.position,go.invParent,go.localValue),go.localValue.addInPlace(this._offsetTranslation),this._writePosition(e,go.localValue))}_solveRotation(e){0!==this._blendTargets(go.position,go.rotation,go.scale)&&(t.Matrix.FromQuaternionToRef(go.rotation,go.mA),this._offsetRotation.multiplyToRef(go.mA,go.mB),go.mB.multiplyToRef(go.invParent,go.mC),go.mC.decompose(go.decomposedScale,go.decomposedRotation,go.translation),this._applyRotation(e,go.decomposedRotation,this.constraint.affectRotation))}_solveScale(e){if(0===this._blendTargets(go.position,go.rotation,go.scale))return;go.parent.decompose(go.decomposedScale,go.decomposedRotation,go.translation);const t=go.decomposedScale,n=go.scale;go.localValue.set((0!==t.x?n.x/t.x:n.x)*this._offsetScale.x,(0!==t.y?n.y/t.y:n.y)*this._offsetScale.y,(0!==t.z?n.z/t.z:n.z)*this._offsetScale.z),this._writeScaling(e,go.localValue)}_solveParent(e){0!==this._blendTargets(go.position,go.rotation,go.scale)&&(t.Matrix.ComposeToRef(go.scale,go.rotation,go.position,go.mA),go.mA.multiplyToRef(go.invParent,go.mB),go.mB.decompose(go.decomposedScale,go.decomposedRotation,go.translation),this._writePosition(e,go.translation),this._applyRotation(e,go.decomposedRotation,this.constraint.affectRotation),this._writeScaling(e,go.decomposedScale))}_solveAim(e){const n=this.constraint;if(!this._localBasisTransposed||0===this._blendTargets(go.position,go.rotation,go.scale))return;const o=this._fbxWorld(e,go.world);if(o.getTranslationToRef(go.origin),go.position.subtractToRef(go.origin,go.forward),go.forward.lengthSquared()<1e-20)return;go.forward.normalize();const s=go.up;switch(n.worldUpType){case 1:this._options.upNode?(this._fbxWorld(this._options.upNode,go.local).getTranslationToRef(s),s.subtractInPlace(go.origin)):s.copyFrom(this._options.sceneUp);break;case 2:this._options.upNode?(this._fbxWorld(this._options.upNode,go.local).decompose(go.decomposedScale,go.decomposedRotation,go.translation),s.set(n.worldUpVector[0],n.worldUpVector[1],n.worldUpVector[2]),s.rotateByQuaternionToRef(go.decomposedRotation,s)):s.copyFrom(this._options.sceneUp);break;case 3:s.set(n.worldUpVector[0],n.worldUpVector[1],n.worldUpVector[2]);break;case 4:go.localValue.set(n.upVector[0],n.upVector[1],n.upVector[2]),t.Vector3.TransformNormalToRef(go.localValue,o,s);break;default:s.copyFrom(this._options.sceneUp)}(s.lengthSquared()<1e-20||Math.abs(t.Vector3.Dot(s.normalizeToRef(go.localValue),go.forward))>.9999)&&(Math.abs(go.forward.y)<.9?s.set(0,1,0):s.set(1,0,0)),bo._OrthonormalBasisToRef(go.forward,s,go.mA)&&(this._localBasisTransposed.multiplyToRef(go.mA,go.mB),this._offsetRotation.multiplyToRef(go.mB,go.mC),go.mC.multiplyToRef(go.invParent,go.mD),go.mD.decompose(go.decomposedScale,go.decomposedRotation,go.translation),this._applyRotation(e,go.decomposedRotation,n.affectRotation))}static _OrthonormalBasisToRef(e,n,o){const s=go.axisA,r=go.axisB,i=go.axisC;return e.normalizeToRef(s),n.subtractToRef(s.scaleToRef(t.Vector3.Dot(s,n),r),r),!(s.lengthSquared()<1e-20||r.lengthSquared()<1e-20||(r.normalize(),t.Vector3.CrossToRef(s,r,i),t.Matrix.FromValuesToRef(s.x,s.y,s.z,0,r.x,r.y,r.z,0,i.x,i.y,i.z,0,0,0,0,1,o),0))}}const xo={name:"fbx",extensions:{".fbx":{isBinary:!0}}};class To{constructor(e={}){var t,n,o,s,r,i,a,l,u,c;this.name=xo.name,this.extensions=xo.extensions,this._bindRestBones=new WeakSet,this._sourceBonesBySkeleton=new WeakMap,this._scaleCompensationHelpersBySkeleton=new WeakMap,this._frameRate=30,this._activeLayers=[],this._parentModelById=new Map,this._curveNodesByModelId=new Map,this._inheritScaleHelpers=new Map,this._meshByGeometryKey=new Map,this._instanceSource=new Map,this._evaluatedCurveNodeIds=new Set,this._rigBoneModelIds=new Set;const d="full"===e.preset;this._options={preset:d?"full":"compatible",normalMapCoordinateSystem:null!==(t=e.normalMapCoordinateSystem)&&void 0!==t?t:"y-up",materials:null!==(n=e.materials)&&void 0!==n?n:d?"auto":"standard",unitScale:null!==(o=e.unitScale)&&void 0!==o?o:"preserve",shareGeometry:null!==(s=e.shareGeometry)&&void 0!==s?s:d,onWarning:null!==(r=e.onWarning)&&void 0!==r?r:()=>{},nurbsSubdivision:null!==(i=e.nurbsSubdivision)&&void 0!==i?i:0,curves:null!==(a=e.curves)&&void 0!==a?a:d?"lines":"skip",constraints:null!==(l=e.constraints)&&void 0!==l?l:d?"apply":"metadata",rebaseAnimations:null!==(u=e.rebaseAnimations)&&void 0!==u?u:!d,attachCamerasAndLights:null!==(c=e.attachCamerasAndLights)&&void 0!==c?c:d}}createPlugin(e){return new To(e[xo.name])}importMeshAsync(e,t,n,o,s,r){return b(this,void 0,void 0,function*(){const s=this._parseAndInterpret(n);return this._buildScene(s,t,o,e)})}loadAsync(e,t,n,o,s){return b(this,void 0,void 0,function*(){const o=this._parseAndInterpret(t);this._buildScene(o,e,n,null)})}loadAssetContainerAsync(e,n,o,s,r){return b(this,void 0,void 0,function*(){const s=this._parseAndInterpret(n),r=new t.AssetContainer(e),i=this._buildScene(s,e,o,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)e instanceof t.LinesMesh||this._addMaterialToContainer(e.material,r);return this._setAssetContainer(r),r.removeAllFromScene(),r})}_parseAndInterpret(e){return eo(this._parse(e),{nurbsSubdivision:this._options.nurbsSubdivision>0?this._options.nurbsSubdivision:void 0,rebaseKeyframes:this._options.rebaseAnimations})}_parse(e){if(e instanceof ArrayBuffer)return this._parseFromArrayBuffer(e);if(ArrayBuffer.isView(e)){const t=e,n=t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength);return this._parseFromArrayBuffer(n)}if("string"==typeof e)return q(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(D=!(n.length>22)||0===n[22],"Kaydara FBX Binary \0"!==W(n,0,21))throw new Error("Not a valid binary FBX file");if(e.byteLength<27)throw new Error("Truncated binary FBX header");const o=t.getUint32(23,D),s=o>=7500,r=[];let i=27;for(;i<e.byteLength;){const o=V(t,n,i,s,e.byteLength);if(null===o)break;r.push(o.node),i=o.endOffset}return{version:o,nodes:r}}(e);const n=new TextDecoder("utf-8").decode(e),o=n.substring(0,4096);if(o.trimStart().startsWith("; FBX")||/^\s*(?:;[^\n]*\n\s*)*(?:FBXHeaderExtension|Definitions|Objects|Connections)\s*:/.test(o))return q(n);throw new Error("FBXFileLoader: unrecognized FBX format")}_buildScene(e,n,o,s){var r;const i=this._buildNameFilter(s);this._frameRate=e.frameRate>0?e.frameRate:30,this._inheritScaleHelpers=new Map;const a=new Map;for(const t of e.materials){const e=this._createMaterial(t,n,o);a.set(t.id,e)}const l=[],u=new Map,c=new Map,d=new Map,h=new Map,f=new Map;for(const t of e.skins)f.set(t.id,t);this._rigBoneModelIds=new Set;for(const t of e.rigs)for(const e of t.bones)this._rigBoneModelIds.add(e.modelId);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=f.get(n.skinId);t&&(c.set(n.geometryId,e),d.set(n.geometryId,t),h.set(n.geometryId,n))}}const p=new Map;this._parentModelById=new Map;const m=(e,t)=>{for(const n of e)p.set(n.id,n),t&&this._parentModelById.set(n.id,t),m(n.children,n)};m(e.rootModels,null);const _=To._collectCullingConflictMaterialIds(e.rootModels),g=new Map,v=new t.TransformNode("__fbx_root__",n);n.useRightHandedSystem||(v.rotation.y=Math.PI,v.scaling.z=-1);const y=this._options.unitScale,b="preserve"===y?0:"meters"===y?100:y;if(b>0&&e.unitScaleFactor>0){const t=e.unitScaleFactor/b;v.scaling.scaleInPlace(t)}v.metadata=Object.assign(Object.assign({},null!==(r=v.metadata)&&void 0!==r?r:{}),{fbxUnitScaleFactor:e.unitScaleFactor,fbxFrameRate:e.frameRate}),this._meshByGeometryKey=new Map,this._instanceSource=new Map,this._evaluatedCurveNodeIds=new Set;const x=[],T=[v];let A=v;const M=To._computeFBXAxisConversionMatrix(e);M.equals(t.Matrix.Identity())||(A=new t.TransformNode("__fbx_axis_conversion__",n),A.parent=v,To._applyMatrixToTransform(A,M),T.push(A));const w=new Map,S=t.Matrix.Identity();for(const t of e.rootModels)this._buildModel(t,n,A,A,S,a,i,x,T,c,d,h,w,_,g);this._linkSkeletonsToTransformNodes(e.rigs,u,w,T,n);for(const t of e.rigs){const e=u.get(t.id);if(!e)continue;x.find(t=>t.skeleton===e);const n=new Set;for(const t of e.bones){const e=t.getTransformNode();e&&n.add(e)}}if(e.blendShapes.length>0){this._applyBlendShapes(e.blendShapes,x,n);for(const[e,t]of Array.from(this._instanceSource))t.morphTargetManager&&!e.morphTargetManager&&(e.morphTargetManager=t.morphTargetManager)}const C=[],R=new Map;for(const t of e.cameras){const e=this._createCamera(t,w,n);e&&(C.push(e),R.set(t.attributeId,e))}const I=[],O=new Map;for(const t of e.lights){const e=this._createLight(t,w,n);e&&(I.push(e),O.set(t.attributeId,e))}this._applyConstraints(e,w,v,n);const F=[];for(const t of e.animations){const o=this._createAnimationGroup(t,e.rigs,u,n,w,p,x,{cameraByAttributeId:R,lightByAttributeId:O,materialCache:a});o&&F.push(o)}return this._reportDiagnostics(e,v,w),{meshes:x,particleSystems:[],skeletons:l,animationGroups:F,transformNodes:T,geometries:[],lights:I,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]],o=(e,t,o)=>{if(e<0||e>2)return;const s=[0,0,0];s[o]=t>=0?1:-1,n[e]=s};return o(e.coordAxis,e.coordAxisSign,0),o(e.upAxis,e.upAxisSign,1),o(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,o,s,r,i,a,l,u,c,d,h,f,p,m){var _,g,v;let y=o;const b=To._computeFBXModelLocalMatrix(e).multiply(r),x=this._parentModelById.get(e.id),T=x?f.get(x.id):void 0;if(y&&x&&T&&y===T&&1!==e.inheritType&&!this._isRigBone(e.id)&&!this._isRigBone(x.id)&&(!x.geometry||!d.has(x.geometry.id))){const o=new t.TransformNode(`${e.name}__fbx_inheritScale`,n);o.parent=T.parent,o.position.copyFrom(T.position),o.rotationQuaternion=T.rotationQuaternion?T.rotationQuaternion.clone():t.Quaternion.FromEulerVector(T.rotation),o.scaling.set(1,1,1),u.push(o),this._inheritScaleHelpers.set(e.id,o),y=o}if(e.geometry&&e.geometry.indices.length>0&&(!a||a(e.name))){const o=null!==e.geometry.controlPointIndices,r=o?c.get(e.geometry.id):void 0,x=o?d.get(e.geometry.id):void 0,T=o?h.get(e.geometry.id):void 0;r&&x&&(r.needInitialSkinMatrix=!0);const A=`${e.geometry.id}|${e.geometricTranslation.join(",")}|${e.geometricRotation.join(",")}|${e.geometricScaling.join(",")}`,M=!r&&this._options.shareGeometry?this._meshByGeometryKey.get(A):void 0;let w;if(M?(w=M.clone(e.name,null,!0),w.sideOrientation=M.sideOrientation,w.metadata=Object.assign(Object.assign({},null!==(_=M.metadata)&&void 0!==_?_:{}),{fbxInstanceOf:M.name}),this._instanceSource.set(w,M)):(w=this._createMesh(e,e.geometry,n,r,x,T),r||this._meshByGeometryKey.set(A,w)),r&&x){const e=x.meshBindPoseMatrix?t.Matrix.FromArray(x.meshBindPoseMatrix):b;w.parent=s,To._applyMatrixToTransform(w,e),w.computeWorldMatrix(!0),w.updatePoseMatrix(t.Matrix.Invert(e)),w.alwaysSelectAsActiveMesh=!0}else y&&(w.parent=y),this._applyRestTRS(w,e);if(e.materials.length>1&&(null===(g=e.geometry)||void 0===g?void 0:g.materialIndices))this._applyMultiMaterial(w,e,i,n,p,m);else if(e.materials.length>0){const t=i.get(e.materials[0].id);t&&(w.material=To._getModelMaterial(t,e,m,p.has(e.materials[0].id)))}(null===(v=e.geometry)||void 0===v?void 0:v.colors)&&this._useUnmodulatedVertexColorMaterials(w,n),this._applyMaterialUVSetCoordinates(w.material,e.geometry),l.push(w),f.set(e.id,w),To._applyModelMetadata(w,e);for(const t of e.children)this._buildModel(t,n,w,s,b,i,a,l,u,c,d,h,f,p,m)}else if(e.curve&&"skip"!==this._options.curves&&e.curve.polylines.length>0&&(!a||a(e.name))){const t=this._createLinesMesh(e,e.curve,n);y&&(t.parent=y),this._applyRestTRS(t,e),l.push(t),f.set(e.id,t),To._applyModelMetadata(t,e);for(const o of e.children)this._buildModel(o,n,t,s,b,i,a,l,u,c,d,h,f,p,m)}else{if((e.geometry||e.curve)&&a&&!To._modelSubtreeMatchesNameFilter(e,a))return;const o=new t.TransformNode(e.name,n);y&&(o.parent=y),this._applyRestTRS(o,e),u.push(o),f.set(e.id,o),To._applyModelMetadata(o,e);for(const t of e.children)this._buildModel(t,n,o,s,b,i,a,l,u,c,d,h,f,p,m);To._applyLodGroup(e,f)}}_linkSkeletonsToTransformNodes(e,n,o,s,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=o.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,To._applyMatrixToTransform(e,l.getLocalMatrix()),To._applyMatrixToTransform(a,i.getLocalMatrix()),l.linkTransformNode(e),s.push(e)}else To._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(To._modelSubtreeMatchesNameFilter(n,t))return!0}return!1}static _applyModelMetadata(e,t){var n;(t.customProperties||0!==t.diagnostics.length||t.displayLayer||t.lodGroup)&&(e.metadata=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},null!==(n=e.metadata)&&void 0!==n?n:{}),t.customProperties?{fbxCustomProperties:t.customProperties,fbxUserProperties:t.customProperties}:{}),t.diagnostics.length>0?{fbxDiagnostics:t.diagnostics}:{}),t.displayLayer?{fbxDisplayLayer:{name:t.displayLayer.name,show:t.displayLayer.show,freeze:t.displayLayer.freeze,color:t.displayLayer.color}}:{}),t.lodGroup?{fbxLodGroup:t.lodGroup}:{}),t.displayLayer&&!t.displayLayer.show&&e.setEnabled(!1))}static _applyLodGroup(e,n){var o,s,r,i,a,l;const u=e.lodGroup;if(!u)return;const c=[];for(let t=0;t<e.children.length;t++){const r=e.children[t],i=null!==(o=u.displayLevels[t])&&void 0!==o?o:0;2===i?null===(s=n.get(r.id))||void 0===s||s.setEnabled(!1):0===i&&c.push({child:r,level:t})}if(c.length<2)return;const d=e=>{const o=n.get(e.id);if(!o)return[];const s=o instanceof t.Mesh?[o]:[];for(const e of o.getChildMeshes(!1))e instanceof t.Mesh&&s.push(e);return s},h=d(c[0].child);for(let e=1;e<c.length;e++){const t=c[e].level,n=d(c[e].child),o=null!==(i=null!==(r=u.thresholds[t-1])&&void 0!==r?r:u.thresholds[u.thresholds.length-1])&&void 0!==i?i:0;for(let e=0;e<h.length;e++){const s=null!==(a=n[e])&&void 0!==a?a:null;u.relative?(h[e].useLODScreenCoverage=!0,h[e].addLODLevel(o/100,s)):h[e].addLODLevel(o,s),s&&(s.metadata=Object.assign(Object.assign({},null!==(l=s.metadata)&&void 0!==l?l:{}),{fbxLodLevel:t}))}}}_createLinesMesh(e,n,o){var s;const r=new t.LinesMesh(e.name,o),i=[],a=[];for(const e of n.polylines){const t=e.length/3;if(t<2)continue;const n=i.length/3;for(let t=0;t<e.length;t++)i.push(e[t]);for(let e=0;e<t-1;e++)a.push(n+e,n+e+1)}const l=To._computeFBXGeometricMatrix(e.geometricTranslation,e.geometricRotation,e.geometricScaling);if(!l.equals(t.Matrix.Identity()))for(let e=0;e<i.length;e+=3){const n=t.Vector3.TransformCoordinates(new t.Vector3(i[e],i[e+1],i[e+2]),l);i[e]=n.x,i[e+1]=n.y,i[e+2]=n.z}const u=new t.VertexData;return u.positions=i,u.indices=a,u.applyToMesh(r),n.color&&(r.color=new t.Color3(n.color[0],n.color[1],n.color[2])),r.metadata=Object.assign(Object.assign({},null!==(s=r.metadata)&&void 0!==s?s:{}),{fbxCurveType:n.kind,fbxCurveSegments:n.polylines.length}),r}_createMesh(e,n,o,s,r,i){var a;const l=new t.Mesh(e.name,o);l.sideOrientation=o.useRightHandedSystem?t.Material.CounterClockWiseSideOrientation:t.Material.ClockWiseSideOrientation;const u=new t.VertexData,c=Ao(n.positions),d=e.geometricTranslation,h=e.geometricRotation,f=e.geometricScaling,p=To._computeFBXGeometricMatrix(d,h,f),m=To._computeFBXGeometricDeltaMatrix(h,f),_=To._computeFBXGeometricNormalMatrix(h,f),g=!p.equals(t.Matrix.Identity()),v=!m.equals(t.Matrix.Identity()),y=!_.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]),p);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=Ao(n.normals),y)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=Ao(n.uvs)),n.uvSets.length>1&&(u.uvs2=Ao(n.uvSets[1].data)),n.uvSets.length>2&&(u.uvs3=Ao(n.uvSets[2].data)),n.uvSets.length>3&&(u.uvs4=Ao(n.uvSets[3].data)),n.uvSets.length>4&&(u.uvs5=Ao(n.uvSets[4].data)),n.uvSets.length>5&&(u.uvs6=Ao(n.uvSets[5].data)),n.tangents){const e=Ao(n.tangents);if(y)for(let n=0;n<e.length;n+=4){const o=t.Vector3.TransformNormal(new t.Vector3(e[n],e[n+1],e[n+2]),_);o.lengthSquared()>0&&o.normalize(),e[n]=o.x,e[n+1]=o.y,e[n+2]=o.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,o,s=1,r=null,i=null){var a,l,u,c,d,h;const f=e.length/3,p=new Map,m=new Array(f).fill(null);for(let s=0;s+2<o.length;s+=3){const a=i?i[s/3]:0,l=o[s],u=o[s+1],c=o[s+2],d=3*l,h=3*u,f=3*c,_=2*l,g=2*u,v=2*c,y=e[h]-e[d],b=e[f]-e[d],x=e[h+1]-e[d+1],T=e[f+1]-e[d+1],A=e[h+2]-e[d+2],M=e[f+2]-e[d+2],w=n[g]-n[_],S=n[v]-n[_],C=n[g+1]-n[_+1],R=n[v+1]-n[_+1],I=w*R-S*C;if(Math.abs(I)<1e-8)continue;const O=1/I,F=(R*y-C*b)*O,E=(R*x-C*T)*O,L=(R*A-C*M)*O,N=(w*b-S*y)*O,k=(w*T-S*x)*O,B=(w*M-S*A)*O;Mo(l,u,c,F,E,L,N,k,B,e,t,n,r,a,p,m),Mo(u,c,l,F,E,L,N,k,B,e,t,n,r,a,p,m),Mo(c,l,u,F,E,L,N,k,B,e,t,n,r,a,p,m)}const _=new Float32Array(4*f);for(let e=0;e<f;e++){const n=3*e,o=4*e,[r,i,f]=wo(t[n],t[n+1],t[n+2]),g=m[e]?p.get(m[e]):void 0,v=null!==(a=null==g?void 0:g.tx)&&void 0!==a?a:0,y=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*v+i*y+f*b;let T=v-r*x,A=y-i*x,M=b-f*x;const w=Math.hypot(T,A,M);w>1e-8?(T/=w,A/=w,M/=w):[T,A,M]=Co(r,i,f);const S=null!==(c=null==g?void 0:g.bx)&&void 0!==c?c:0,C=null!==(d=null==g?void 0:g.by)&&void 0!==d?d:0,R=null!==(h=null==g?void 0:g.bz)&&void 0!==h?h:0,I=i*M-f*A,O=f*T-r*M,F=r*A-i*T,E=Math.hypot(S,C,R)>1e-8&&I*S+O*C+F*R<0?-1:1;_[o]=T,_[o+1]=A,_[o+2]=M,_[o+3]=E*s}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(s&&r){const{matricesIndices:e,matricesWeights:t,matricesIndicesExtra:o,matricesWeightsExtra:s,numBoneInfluencers:a}=this._buildSkinningData(n,r,i);u.matricesIndices=e,u.matricesWeights=t,o&&s&&(u.matricesIndicesExtra=o,u.matricesWeightsExtra=s),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:v?m:null,fbxGeometryNormalMatrix:y?_:null,fbxPreRotMatrix:v?m:null}),s&&(l.skeleton=s),l}_applyMultiMaterial(e,n,o,s,r,i){var a,l;const u=n.geometry.materialIndices,c=null===(a=e.metadata)||void 0===a?void 0:a.fbxSubMeshMaterialIndices;if(c){const a=new t.MultiMaterial(n.name+"_multi",s);for(const e of c){const t=n.materials[e],s=t?o.get(t.id):void 0;a.subMaterials.push(s?To._getModelMaterial(s,n,i,r.has(t.id)):null)}return void(e.material=a)}const d=e.getIndices();if(!d)return;const h=d.length/3,f=new Map;for(let e=0;e<h;e++){const t=e<u.length?u[e]:0;let n=f.get(t);n||(n=[],f.set(t,n)),n.push(e)}const p=Array.from(f.keys()).sort((e,t)=>e-t),m=[],_=[];for(const e of p){const t=f.get(e),n=m.length;for(const e of t)m.push(d[3*e],d[3*e+1],d[3*e+2]);_.push({start:n,count:3*t.length,matIdx:e})}e.setIndices(m);const g=new t.MultiMaterial(n.name+"_multi",s);for(const e of _){const t=n.materials[e.matIdx];if(t){const e=o.get(t.id);e?g.subMaterials.push(To._getModelMaterial(e,n,i,r.has(t.id))):g.subMaterials.push(null)}else g.subMaterials.push(null)}e.material=g,e.subMeshes=[];const v=e.getTotalVertices();for(let n=0;n<_.length;n++){const o=_[n];new t.SubMesh(n,0,v,o.start,o.count,e)}e.metadata=Object.assign(Object.assign({},null!==(l=e.metadata)&&void 0!==l?l:{}),{fbxSubMeshMaterialIndices:p})}static _collectCullingConflictMaterialIds(e){const t=new Map,n=e=>{var o;for(const n of e.materials){const s=null!==(o=t.get(n.id))&&void 0!==o?o:{cullingOff:!1,cullingOn:!1};e.cullingOff?s.cullingOff=!0:s.cullingOn=!0,t.set(n.id,s)}for(const t of e.children)n(t)};for(const t of e)n(t);const o=new Set;for(const[e,n]of Array.from(t))n.cullingOff&&n.cullingOn&&o.add(e);return o}static _getModelMaterial(e,t,n,o=!0){var s;if(!t.cullingOff||!e.backFaceCulling)return e;if(!o)return e.backFaceCulling=!1,e;const r=null==n?void 0:n.get(e);if(r)return r;const i=null!==(s=e.clone(`${e.name}_CullingOff`))&&void 0!==s?s:e;return i.backFaceCulling=!1,null==n||n.set(e,i),i}_applyMaterialUVSetCoordinates(e,n){if(e)if(e instanceof t.MultiMaterial)for(const o of e.subMaterials)(o instanceof t.StandardMaterial||o instanceof t.PBRMaterial)&&this._applyStandardMaterialUVSetCoordinates(o,n);else(e instanceof t.StandardMaterial||e instanceof t.PBRMaterial)&&this._applyStandardMaterialUVSetCoordinates(e,n)}_applyStandardMaterialUVSetCoordinates(e,n){var o;for(const s of e instanceof t.PBRMaterial?[e.albedoTexture,e.bumpTexture,e.emissiveTexture,e.ambientTexture,e.metallicTexture,e.reflectivityTexture,e.microSurfaceTexture,e.opacityTexture,e.clearCoat.texture,e.clearCoat.bumpTexture,e.sheen.texture]:[e.diffuseTexture,e.bumpTexture,e.emissiveTexture,e.ambientTexture,e.specularTexture,e.opacityTexture,e.reflectionTexture]){if(!s)continue;const e=null===(o=s.metadata)||void 0===o?void 0:o.fbxUVSetName;if(!e)continue;const t=n.uvSets.findIndex(t=>t.name===e);t>=0&&(s.coordinatesIndex=t)}}_useUnmodulatedVertexColorMaterials(e,n){const o=e.material;if(!o)return;const s=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}if(e instanceof t.PBRMaterial&&!e.albedoTexture){const n=e.clone(`${e.name}_VertexColor`);return n.albedoColor=new t.Color3(1,1,1),n}return e};if(o instanceof t.MultiMaterial){const r=new t.MultiMaterial(`${o.name}_VertexColor`,n);return r.subMaterials=o.subMaterials.map(e=>e?s(e):e),void(e.material=r)}e.material=s(o)}_buildSkinningData(e,t,n){var o,s,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 s=e.controlPointIndices[n],r=null!==(o=t.boneIndices[s])&&void 0!==o?o:[];d=Math.max(d,Math.min(r.length,8))}d>4&&(u=new Float32Array(4*i),c=new Float32Array(4*i));for(let o=0;o<i;o++){const i=e.controlPointIndices[o],d=null!==(s=t.boneIndices[i])&&void 0!==s?s:[],h=null!==(r=t.boneWeights[i])&&void 0!==r?r:[];for(let e=0;e<8;e++){const t=e<4?a:u,s=e<4?l:c;if(!t||!s)continue;const r=4*o+e%4;if(e<d.length){const o=d[e],s=n?n.skinBoneIndexToRigBoneIndex[o]:o;if(void 0===s||s<0)throw new Error(`FBXFileLoader: missing rig bone mapping for skin bone index ${o}`);t[r]=s}else t[r]=0;s[r]=e<h.length?h[e]:0}}}return{matricesIndices:a,matricesWeights:l,matricesIndicesExtra:u,matricesWeightsExtra:c,numBoneInfluencers:Math.max(d,1)}}_createMaterial(e,t,n){var o;const s=this._options.materials,r="pbr"===s||"auto"===s&&Tt(e.model.shaderType)?this._createPbrMaterial(e,t,n):this._createStandardMaterial(e,t,n);return r.metadata=Object.assign(Object.assign(Object.assign({},null!==(o=r.metadata)&&void 0!==o?o:{}),e.userProperties?{fbxUserProperties:e.userProperties}:{}),{fbxShaderType:e.model.shaderType,fbxFeatures:Object.fromEntries(Object.entries(e.model.features).map(([e,t])=>{var n;return[e,null!==(n=null==t?void 0:t.enabled)&&void 0!==n&&n]}))}),r}_createPbrMaterial(e,n,o){var s,r,i,a,l,u,c,d,h,f,p,m,_,g,v,y,b,x,T,A,M,w,S,C;const R=new t.PBRMaterial(e.name,n),I=e.model.pbr,O=e.model.features,F=e=>{var t,n;return null!==(n=null===(t=O[e])||void 0===t?void 0:t.enabled)&&void 0!==n&&n},E="3dsMaxPbrSpecGloss"===e.model.shaderType,L=(e,n)=>e?new t.Color3(e[0]*(null!=n?n:1),e[1]*(null!=n?n:1),e[2]*(null!=n?n:1)):void 0,N=St(I.baseColor);if(R.albedoColor=null!==(r=L(N,(null===(s=I.baseColor)||void 0===s?void 0:s.texture)?1:Ct(I.baseFactor)))&&void 0!==r?r:t.Color3.White(),E)R.metallic=null,R.roughness=null,R.reflectivityColor=null!==(i=L(St(I.specularColor),1))&&void 0!==i?i:t.Color3.White(),R.microSurface=null!==(a=Ct(I.glossiness))&&void 0!==a?a:1-(null!==(l=Ct(I.roughness))&&void 0!==l?l:.5);else if(R.metallic=F("metalness")&&null!==(u=Ct(I.metalness))&&void 0!==u?u:0,R.roughness=null!==(c=Ct(I.roughness))&&void 0!==c?c:(null===(d=I.glossiness)||void 0===d?void 0:d.value)?1-I.glossiness.value[0]:.5,F("specular")&&(null===(h=I.specularFactor)||void 0===h?void 0:h.value)&&(R.metallicF0Factor=null!==(f=Ct(I.specularFactor))&&void 0!==f?f:1),F("specular")){const e=St(I.specularColor);e&&(R.metallicReflectanceColor=new t.Color3(e[0],e[1],e[2]))}const k=L(St(I.emissionColor),(null===(p=I.emissionColor)||void 0===p?void 0:p.texture)?1:Ct(I.emissionFactor));(k&&F("emission")||k&&(k.r>0||k.g>0||k.b>0))&&(R.emissiveColor=k);const B=St(I.opacity);B&&F("opacity")?R.alpha=(B[0]+B[1]+B[2])/3:Tt(e.model.shaderType)||(R.alpha=To._alphaFromClassicTransparency(e)),R.alpha<1&&(R.transparencyMode=t.Material.MATERIAL_ALPHABLEND);const P=null!==(m=Ct(I.transmissionFactor))&&void 0!==m?m:0;if(F("transmission")&&Tt(e.model.shaderType)&&P>0){R.subSurface.isRefractionEnabled=!0,R.subSurface.refractionIntensity=P;const e=St(I.transmissionColor);e&&(R.subSurface.tintColor=new t.Color3(e[0],e[1],e[2]));const n=Ct(I.specularIor);n&&F("ior")&&(R.subSurface.indexOfRefraction=n)}else{const e=Ct(I.specularIor);e&&F("ior")&&e>1&&(R.indexOfRefraction=e)}const D=null!==(_=Ct(I.coatFactor))&&void 0!==_?_:0;if(F("coat")&&D>0||(null===(g=I.coatFactor)||void 0===g?void 0:g.texture)){R.clearCoat.isEnabled=!0,R.clearCoat.intensity=D;const e=Ct(I.coatRoughness);void 0!==e&&(R.clearCoat.roughness=e);const n=Ct(I.coatIor);void 0!==n&&n>1&&(R.clearCoat.indexOfRefraction=n);const o=St(I.coatColor);!o||1===o[0]&&1===o[1]&&1===o[2]||(R.clearCoat.isTintEnabled=!0,R.clearCoat.tintColor=new t.Color3(o[0],o[1],o[2]))}const V=null!==(v=Ct(I.sheenFactor))&&void 0!==v?v:0;if(F("sheen")&&V>0||(null===(y=I.sheenColor)||void 0===y?void 0:y.texture)){R.sheen.isEnabled=!0,R.sheen.intensity=V;const e=St(I.sheenColor);e&&(R.sheen.color=new t.Color3(e[0],e[1],e[2]));const n=Ct(I.sheenRoughness);void 0!==n&&(R.sheen.roughness=n)}F("unlit")&&(R.unlit=!0),F("doubleSided")&&(R.backFaceCulling=!1);const G=(e,t=!1)=>{if(!(null==e?void 0:e.texture)||!e.textureEnabled)return null;const s=To._createTexture(e.texture,n,o,t);return s&&To._applyTextureSettings(s,e.texture),s},$=G(I.baseColor);$&&(R.albedoTexture=$);const U=G(I.normalMap,!0);U&&(R.bumpTexture=U,this._configureNormalTexture(U,R));const H=G(I.emissionColor);H&&(R.emissiveTexture=H,(!k||0===k.r&&0===k.g&&0===k.b)&&(R.emissiveColor=t.Color3.White()));const K=G(I.ambientOcclusion);if(K&&(R.ambientTexture=K,R.useAmbientInGrayScale=!0),E){const e=G(I.specularColor);e&&(R.reflectivityTexture=e);const t=null!==(b=G(I.glossiness))&&void 0!==b?b:G(I.roughness);t&&(R.microSurfaceTexture=t)}else{const e=(null===(x=I.metalness)||void 0===x?void 0:x.textureEnabled)?I.metalness.texture:void 0,t=(null===(T=I.roughness)||void 0===T?void 0:T.textureEnabled)&&I.roughness.texture?I.roughness:(null===(A=I.glossiness)||void 0===A?void 0:A.textureEnabled)&&I.glossiness.texture?I.glossiness:void 0,n=null==t?void 0:t.texture,o=!!e&&!!n&&e.id===n.id;let s=!1;if(!e||!o&&n){if(n){const n=G(t);n&&(R.metallicTexture=n,R.useMetallnessFromMetallicTextureBlue=!1,R.useRoughnessFromMetallicTextureGreen=!0,R.useRoughnessFromMetallicTextureAlpha=!1,e&&(R.metadata=Object.assign(Object.assign({},null!==(M=R.metadata)&&void 0!==M?M:{}),{fbxDroppedMetalnessTexture:e.relativeFileName})))}}else{const e=G(I.metalness);e&&(s=!0,R.metallicTexture=e,R.useMetallnessFromMetallicTextureBlue=!0,R.useRoughnessFromMetallicTextureGreen=o,R.useRoughnessFromMetallicTextureAlpha=!1)}s&&0===R.metallic&&(R.metallic=1)}if((null===(w=I.opacity)||void 0===w?void 0:w.texture)&&I.opacity.textureEnabled)if($&&I.opacity.texture.id===(null===(C=null===(S=I.baseColor)||void 0===S?void 0:S.texture)||void 0===C?void 0:C.id))R.useAlphaFromAlbedoTexture=!0,R.transparencyMode=t.Material.MATERIAL_ALPHATESTANDBLEND;else{const e=G(I.opacity);e&&(R.opacityTexture=e,R.transparencyMode=t.Material.MATERIAL_ALPHATESTANDBLEND)}if(R.clearCoat.isEnabled){const e=G(I.coatFactor);e&&(R.clearCoat.texture=e);const t=G(I.coatNormal,!0);t&&(R.clearCoat.bumpTexture=t)}if(R.sheen.isEnabled){const e=G(I.sheenColor);e&&(R.sheen.texture=e)}return R}static _alphaFromClassicTransparency(e){const t=e.properties;if(void 0!==t.opacity)return t.opacity;const n=Ct(e.model.fbx.transparencyFactor);if(void 0===n)return 1;const o=St(e.model.fbx.transparencyColor),s=o?(o[0]+o[1]+o[2])/3:1;return Math.min(1,Math.max(0,1-s*n))}static _applyTextureSettings(e,n){var o;n.uvTranslation&&(e.uOffset=n.uvTranslation[0],e.vOffset=n.uvTranslation[1]),n.uvScaling&&(e.uScale=n.uvScaling[0],e.vScale=n.uvScaling[1]),void 0!==n.uvRotation&&(e.wAng=n.uvRotation*(Math.PI/180)),void 0!==n.uvSetIndex&&(e.coordinatesIndex=n.uvSetIndex),void 0!==n.wrapU&&(e.wrapU=1===n.wrapU?t.Texture.CLAMP_ADDRESSMODE:t.Texture.WRAP_ADDRESSMODE),void 0!==n.wrapV&&(e.wrapV=1===n.wrapV?t.Texture.CLAMP_ADDRESSMODE:t.Texture.WRAP_ADDRESSMODE),(n.uvSetName||void 0!==n.layeredTextureId)&&(e.metadata=Object.assign(Object.assign(Object.assign({},null!==(o=e.metadata)&&void 0!==o?o:{}),n.uvSetName?{fbxUVSetName:n.uvSetName}:{}),void 0!==n.layeredTextureId?{fbxLayeredTextureId:n.layeredTextureId}:{}))}_createStandardMaterial(e,n,o){var s,r,i,a;const l=new t.StandardMaterial(e.name,n),u=e.properties,c=(...t)=>e.textures.some(e=>t.includes(e.propertyName));if("Lambert"===e.type&&(l.specularColor=t.Color3.Black()),u.diffuseColor){const e=c("DiffuseColor","Diffuse")?1:null!==(s=u.diffuseFactor)&&void 0!==s?s:1;l.diffuseColor=new t.Color3(u.diffuseColor[0]*e,u.diffuseColor[1]*e,u.diffuseColor[2]*e)}if(u.ambientColor){const e=c("AmbientColor","Ambient")?1:null!==(r=u.ambientFactor)&&void 0!==r?r:1;l.ambientColor=new t.Color3(u.ambientColor[0]*e,u.ambientColor[1]*e,u.ambientColor[2]*e)}if("Phong"===e.type&&u.specularColor){const e=c("SpecularColor","Specular","Shininess","ShininessExponent")?1:null!==(i=u.specularFactor)&&void 0!==i?i:1;l.specularColor=new t.Color3(u.specularColor[0]*e,u.specularColor[1]*e,u.specularColor[2]*e)}if(u.emissiveColor){const e=c("EmissiveColor","Emissive")?1:null!==(a=u.emissiveFactor)&&void 0!==a?a:1;l.emissiveColor=new t.Color3(u.emissiveColor[0]*e,u.emissiveColor[1]*e,u.emissiveColor[2]*e)}l.alpha=To._alphaFromClassicTransparency(e),l.alpha<1&&(l.transparencyMode=t.Material.MATERIAL_ALPHABLEND),void 0!==u.shininess&&(l.specularPower=u.shininess);for(const s of e.textures){if(!To._isSupportedMaterialTextureSlot(s.propertyName))continue;const e=To._createTexture(s,n,o,To._isNormalMapTextureSlot(s.propertyName));if(e){switch(s.propertyName){case"DiffuseColor":l.diffuseTexture=e,l.diffuseColor=new t.Color3(1,1,1);break;case"NormalMap":case"NormalMapTexture":case"normalCamera":case"Bump":case"BumpFactor":l.bumpTexture=e,this._configureNormalTexture(e,l);break;case"EmissiveColor":l.emissiveTexture=e;break;case"AmbientColor":l.ambientTexture=e;break;case"SpecularColor":l.specularTexture=e;break;case"TransparencyFactor":case"TransparentColor":l.opacityTexture=e,l.transparencyMode=t.Material.MATERIAL_ALPHATESTANDBLEND;break;case"ReflectionColor":case"ReflectionFactor":l.reflectionTexture=e}To._applyTextureSettings(e,s)}}return l}_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,o,s){const r=To._getTextureSourceName(e),i=To._getTextureCreationOptions(r,s,e.embeddedData);if(e.embeddedData){const o=new t.Texture(null,n,i),s=null!=r?r:`embeddedTexture_${e.id.toString()}`;return o.updateURL(`data:fbx-embedded-texture/${encodeURIComponent(s)}`,new Uint8Array(e.embeddedData),void 0,i.forcedExtension),o.name=s,o}const a=To._getExternalTextureUrls(e,o),l=a.shift();return l?To._createExternalTexture(l,a,n,i):null}static _createExternalTexture(e,n,o,s){n.push(...To._buildTextureFallbackUrls(e));let r=0;const i=new t.Texture(e,o,Object.assign(Object.assign({},s),{onError:()=>{const e=n[r++];e&&i.getScene()&&i.updateURL(e,null,void 0,To._getForcedExtension(e))}}));return i}static _buildTextureFallbackUrls(e){const t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\")),n=e.lastIndexOf(".");if(n<=t)return[];const o=e.slice(0,n),s=e.slice(n+1).toLowerCase();return["png","jpg","jpeg","webp","bmp","tga"].filter(e=>e!==s).map(e=>`${o}.${e}`)}static _getTextureCreationOptions(e,t,n){const o=n?e?To._getMimeType(e):"image/png":void 0;return{buffer:n?new Uint8Array(n):void 0,forcedExtension:e?To._getForcedExtension(e,o):n?".png":void 0,gammaSpace:!t,mimeType:o}}static _getExternalTextureUrls(e,t){const n=[e.relativeFileName,e.fileName].filter(e=>!!e),o=[];for(const e of n){const n=e.replace(/\\/g,"/");To._isSafeRelativeTexturePath(n)&&o.push(t+n);const s=To._getTextureSourceNameFromPath(n);s&&o.push(t+s)}return Array.from(new Set(o))}static _getTextureSourceName(e){const t=e.relativeFileName||e.fileName;if(!t)return null;const n=t.replace(/\\/g,"/");return To._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("\\")),o=e.lastIndexOf(".");if(o>n)return e.slice(o).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(To._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,o){var s,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 f=new t.MorphTargetManager(o);f.optimizeInfluencers=!1;const p=null!==(a=null!==(r=null===(s=e.metadata)||void 0===s?void 0:s.fbxGeometryDeltaMatrix)&&void 0!==r?r:null===(i=e.metadata)||void 0===i?void 0:i.fbxPreRotMatrix)&&void 0!==a?a:null,m=null!==(u=null===(l=e.metadata)||void 0===l?void 0:l.fbxGeometryNormalMatrix)&&void 0!==u?u:p;for(const n of h.channels){const s=null===(c=e.metadata)||void 0===c?void 0:c.fbxControlPointIndices;if(!s)continue;const r=e.getVerticesData("position"),i=e.getVerticesData("normal");if(!r)continue;const a=Io(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=Ro(u,s,r,i,p,m);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,o);_.setPositions(c.positions),c.normals&&_.setNormals(c.normals),l.push(f.numTargets),f.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}))}f.numTargets>0&&(f.numMaxInfluencers=f.numTargets,e.morphTargetManager=f)}}_createCamera(e,n,o){var s,r;const i=n.get(e.modelId),a=i?i.computeWorldMatrix(!0):t.Matrix.Identity(),l=t.Vector3.TransformCoordinates(t.Vector3.Zero(),a),u=new t.FreeCamera(e.name,l,o);if(u.fov=e.fieldOfView*(Math.PI/180),u.fovMode=t.Camera.FOVMODE_VERTICAL_FIXED,u.minZ=e.nearPlane,u.maxZ=e.farPlane,u.metadata=Object.assign(Object.assign({},null!==(s=u.metadata)&&void 0!==s?s:{}),{fbxCamera:{projectionType:e.projectionType,focalLength:e.focalLength,filmWidth:e.filmWidth,filmHeight:e.filmHeight,orthoZoom:e.orthoZoom,roll:e.roll,aspectRatio:e.aspectRatio,fieldOfViewX:e.fieldOfViewX,apertureMode:e.apertureMode,apertureSizeInch:e.apertureSizeInch,userProperties:e.userProperties,unknownProperties:e.unknownProperties,diagnostics:e.diagnostics}}),"orthographic"===e.projectionType&&(u.mode=t.Camera.ORTHOGRAPHIC_CAMERA,u.orthoTop=e.orthographicSize[1]/2,u.orthoBottom=-e.orthographicSize[1]/2,u.orthoRight=e.orthographicSize[0]/2,u.orthoLeft=-e.orthographicSize[0]/2),i&&this._options.attachCamerasAndLights){let n=i;if(a.determinant()<0){const s=new t.TransformNode(`${e.name}__fbx_cameraPivot`,o);s.parent=i,s.scaling.set(1,1,-1),n=s}u.parent=n,u.position.set(0,0,0);const s=(null!==(r=e.roll)&&void 0!==r?r:0)*Math.PI/180;u.rotationQuaternion=t.Quaternion.FromRotationMatrix(t.Matrix.RotationZ(s).multiply(t.Matrix.RotationY(Math.PI/2)))}else{const e=t.Vector3.TransformCoordinates(new t.Vector3(1,0,0),a);u.setTarget(e)}return u}_createLight(e,n,o){var s;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;const d=!!r&&this._options.attachCamerasAndLights,h=d?t.Vector3.Zero():a,f=d?new t.Vector3(0,0,-1):u;switch(e.lightType){case 1:c=new t.DirectionalLight(e.name,f,o),c.diffuse=l,c.intensity=e.intensity;break;case 2:{const n=e.coneAngle*(Math.PI/180);c=new t.SpotLight(e.name,h,f,n,2,o),c.diffuse=l,c.intensity=e.intensity,void 0!==e.innerAngle&&(c.innerAngle=Math.min(n,e.innerAngle*Math.PI/180));break}default:c=new t.PointLight(e.name,h,o),c.diffuse=l,c.intensity=e.intensity}return d&&r&&(c.parent=r,c.computeTransformedInformation()),c.specular=l,e.enableFarAttenuation&&void 0!==e.farAttenuationEnd&&e.farAttenuationEnd>0&&(c.range=e.farAttenuationEnd),c.metadata=Object.assign(Object.assign({},null!==(s=c.metadata)&&void 0!==s?s:{}),{fbxLight:{lightType:e.lightType,decayType:e.decayType,decayStart:e.decayStart,innerAngle:e.innerAngle,outerAngle:e.outerAngle,enableNearAttenuation:e.enableNearAttenuation,enableFarAttenuation:e.enableFarAttenuation,castShadows:e.castShadows,farAttenuationStart:e.farAttenuationStart,farAttenuationEnd:e.farAttenuationEnd,areaLightShape:e.areaLightShape,userProperties:e.userProperties,unknownProperties:e.unknownProperties,diagnostics:e.diagnostics}}),c}_createSkeleton(e,n,o){var s;const r=new t.Skeleton("Skeleton",`skeleton_${e}`,o),i=[],a=new Map,l=[],u=[],c=[],d=To._computeBoneInheritScales(n,n.map(e=>e.scale));for(let e=0;e<n.length;e++){const t=n[e],o=To._computeFBXLocalMatrix(t.translation,t.rotation,t.scale,t.preRotation,t.postRotation,t.rotationPivot,t.scalingPivot,t.rotationOffset,t.scalingOffset,t.rotationOrder);l[e]=o,c[e]=To._computeFBXRuntimeLocalMatrix(n,o,e,d)}u.push(...To._computeFBXAbsoluteMatrices(n,c));const h=n.map((e,n)=>e.transformLinkMatrix?t.Matrix.FromArray(e.transformLinkMatrix):e.modelBindPoseMatrix?t.Matrix.FromArray(e.modelBindPoseMatrix):u[n]),f=h.map((e,o)=>{const s=n[o].parentIndex;if(s<0)return e;const r=new t.Matrix;return h[s].invertToRef(r),e.multiply(r)}),p=To._shouldUseBindMatricesAsRest(n,l,f),m=To._computeBoneInheritScales(n,n.map(e=>e.scale));for(let e=0;e<n.length;e++){let o=p?f[e]:c[e],u=n[e].parentIndex>=0?i[n[e].parentIndex]:null;if(!p&&1!==n[e].inheritType&&n[e].parentIndex>=0&&u){const i=To._splitParentScaleCompensatedLocalMatrix(l[e],m[n[e].parentIndex],To._getBoneInheritedScale(n,e,m)),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!==(s=c.metadata)&&void 0!==s?s:{}),{fbxScaleCompensationForBoneIndex:e,fbxScaleCompensationForBoneName:n[e].name}),a.set(e,c),u=c,o=i.boneLocalMatrix}const d=new t.Bone(n[e].name,r,u,o,p?o.clone():null,p?o.clone():null,e);p&&n[e].isCluster&&To._getMaxScaleRatio(l[e],f[e])>=10&&this._bindRestBones.add(d),i.push(d)}if(this._sourceBonesBySkeleton.set(r,i),this._scaleCompensationHelpersBySkeleton.set(r,a),!p){for(let e=0;e<n.length;e++)i[e].updateMatrix(f[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}_isRigBone(e){return this._rigBoneModelIds.has(e)}_getSourceBone(e,t){var n,o;return null!==(o=null===(n=this._sourceBonesBySkeleton.get(e))||void 0===n?void 0:n[t])&&void 0!==o?o: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 o=0;o<e.length;o++){const s=e[o].parentIndex;n[o]=s<0?t[o].clone():t[o].multiply(n[s])}return n}static _computeBoneInheritScales(e,t){const n=[];for(let o=0;o<e.length;o++){const s=t[o],r=To._getBoneInheritScaleNode(e,o);if(r<0||r>=o)n[o]=[s[0],s[1],s[2]];else{const e=n[r];n[o]=[s[0]*e[0],s[1]*e[1],s[2]*e[2]]}}return n}static _getBoneInheritScaleNode(e,t){const n=e[t].parentIndex;return n<0?-1:0===e[t].inheritType?n:2===e[t].inheritType?To._getBoneInheritScaleNode(e,n):-1}static _getBoneInheritedScale(e,t,n){const o=To._getBoneInheritScaleNode(e,t);return o>=0?n[o]:[1,1,1]}static _computeFBXRuntimeLocalMatrix(e,t,n,o){const s=e[n].parentIndex;if(1===e[n].inheritType||s<0)return t;const r=null!=o?o:To._computeBoneInheritScales(e,e.map(e=>e.scale));return To._applyParentScaleCompensation(t,r[s],To._getBoneInheritedScale(e,n,r))}static _applyParentScaleCompensation(e,t,n){const o=To._splitParentScaleCompensatedLocalMatrix(e,t,n);return o.boneLocalMatrix.multiply(o.helperLocalMatrix)}static _splitParentScaleCompensatedLocalMatrix(e,n,o){const s=e.getTranslation();let r=e.clone();return r.setTranslation(t.Vector3.Zero()),!o||1===o[0]&&1===o[1]&&1===o[2]||(r=t.Matrix.Scaling(o[0],o[1],o[2]).multiply(r)),{boneLocalMatrix:r,helperLocalMatrix:t.Matrix.Compose(To._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(To._safeInverseScale(e[0]),To._safeInverseScale(e[1]),To._safeInverseScale(e[2]))}static _shouldUseBindMatricesAsRest(e,t,n){return e.some((e,o)=>!!e.isCluster&&To._getMaxScaleRatio(t[o],n[o])>=10)}static _getMaxScaleRatio(e,n){const o=new t.Vector3,s=new t.Quaternion,r=new t.Vector3,i=new t.Vector3,a=new t.Quaternion,l=new t.Vector3;return e.decompose(o,s,r),n.decompose(i,a,l),Math.max(To._getScaleRatio(o.x,i.x),To._getScaleRatio(o.y,i.y),To._getScaleRatio(o.z,i.z))}static _getScaleRatio(e,t){const n=Math.abs(e),o=Math.abs(t);return n<1e-6||o<1e-6?n<1e-6&&o<1e-6?1:Number.POSITIVE_INFINITY:Math.max(n/o,o/n)}static _computeFBXGeometricMatrix(e,n,o){return function(e,n,o){const s=t.Matrix.Translation(e[0],e[1],e[2]);return mo(n,o).multiply(s)}(e,n,o)}static _computeFBXGeometricDeltaMatrix(e,t){return mo(e,t)}static _computeFBXGeometricNormalMatrix(e,n){return function(e,n){const o=Math.PI/180,s=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=fo(e[0]*o,e[1]*o,e[2]*o);return s.multiply(r)}(e,n)}static _computeFBXLocalMatrix(e,n,o,s,r,i,a,l,u,c=0){return function(e){const{translation:n,rotation:o,scale:s,preRotation:r,postRotation:i,rotationPivot:a,scalingPivot:l,rotationOffset:u,scalingOffset:c,rotationOrder:d}=e,h=Math.PI/180,f=0!==a[0]||0!==a[1]||0!==a[2]||0!==l[0]||0!==l[1]||0!==l[2],p=0!==u[0]||0!==u[1]||0!==u[2]||0!==c[0]||0!==c[1]||0!==c[2],m=0!==i[0]||0!==i[1]||0!==i[2];if(!f&&!p&&!m){const e=fo(r[0]*h,r[1]*h,r[2]*h),i=po(o[0]*h,o[1]*h,o[2]*h,d),a=t.Matrix.Translation(n[0],n[1],n[2]),l=i.multiply(e);return t.Matrix.Scaling(s[0],s[1],s[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]),v=t.Matrix.Translation(a[0],a[1],a[2]),y=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=fo(r[0]*h,r[1]*h,r[2]*h),M=po(o[0]*h,o[1]*h,o[2]*h,d),w=t.Matrix.Scaling(s[0],s[1],s[2]);let S;if(m){const e=fo(i[0]*h,i[1]*h,i[2]*h);S=new t.Matrix,e.invertToRef(S)}else S=t.Matrix.Identity();let C=T;return C=C.multiply(w),C=C.multiply(x),C=C.multiply(b),C=C.multiply(y),C=C.multiply(S),C=C.multiply(M),C=C.multiply(A),C=C.multiply(v),C=C.multiply(g),C=C.multiply(_),C}({translation:e,rotation:n,scale:o,preRotation:s,postRotation:r,rotationPivot:i,scalingPivot:a,rotationOffset:l,scalingOffset:u,rotationOrder:c})}_applyRestTRS(e,t){const n=To._computeLocalTRS(t,t.translation,t.rotation,t.scale);this._adjustTRSForInheritMode(t,n,void 0),e.position=n.position,e.rotationQuaternion=n.rotationQuaternion,e.scaling=n.scaling}static _computeFBXModelLocalMatrix(e){return To._computeFBXLocalMatrix(e.translation,e.rotation,e.scale,e.preRotation,e.postRotation,e.rotationPivot,e.scalingPivot,e.rotationOffset,e.scalingOffset,e.rotationOrder)}static _applyMatrixToTransform(e,n){const o=new t.Vector3,s=new t.Quaternion,r=new t.Vector3;n.decompose(o,s,r),e.position=r,e.rotationQuaternion=s,e.scaling=o}_createAnimationGroup(e,n,o,s,r,i,a,l){var u,c;if(0===e.curveNodes.length&&!e.unsupportedCurveNodes.some(e=>null!==e.targetId&&e.curves.length>0))return null;this._activeLayers=e.layers,this._curveNodesByModelId=new Map;for(const t of e.curveNodes){if("DeformPercent"===t.type)continue;const e=this._curveNodesByModelId.get(t.targetModelId);e?e.push(t):this._curveNodesByModelId.set(t.targetModelId,[t])}const d=new t.AnimationGroup(e.name,s),h=new Map,f=(e,t)=>{var n;const o=null!==(n=t.getTransformNode())&&void 0!==n?n:t;let s=h.get(o);if(s){if(s.has(e.targetProperty))return}else s=new Set,h.set(o,s);s.add(e.targetProperty),d.addTargetedAnimation(e,o)},p=new Map;for(const e of n){const t=o.get(e.id);if(t)for(const n of e.bones){const e=this._getSourceBone(t,n.index);if(!e)continue;const o=p.get(n.modelId);o?o.push(e):p.set(n.modelId,[e])}}const m=new Map,_=new Map,g=[];for(const t of e.curveNodes)"DeformPercent"!==t.type?p.has(t.targetModelId)?(m.has(t.targetModelId)||m.set(t.targetModelId,[]),m.get(t.targetModelId).push(t)):(_.has(t.targetModelId)||_.set(t.targetModelId,[]),_.get(t.targetModelId).push(t)):g.push(t);const v=new Set;for(const t of n){const n=new Set(t.bones.filter(e=>1!==e.inheritType&&e.parentIndex>=0).map(e=>e.modelId));if(0===n.size)continue;const s=o.get(t.id);if(s&&!s.bones.some(e=>this._bindRestBones.has(e))){for(const e of Array.from(n))v.add(e);for(const{bone:o,animations:r}of this._buildInheritedRigBoneAnimations(t,s,m,i,n,e.startTime,e.stopTime))for(const e of r)f(e,o)}}for(const[t,n]of Array.from(m)){if(v.has(t))continue;const o=p.get(t),s=i.get(t);if(o&&0!==o.length&&s)for(const t of o){const o=this._buildBoneAnimations(n,t.name,s,e.startTime,e.stopTime,this._bindRestBones.has(t)?t.getBindMatrix():void 0);for(const e of o)f(e,t)}}for(const[t,n]of Array.from(_)){const o=r.get(t);if(!o)continue;const s=i.get(t);if(!s)continue;const a=this._buildNodeAnimations(n,o.name,s,e.startTime,e.stopTime);for(const e of a)d.addTargetedAnimation(e,o)}for(const[n,o]of Array.from(this._inheritScaleHelpers)){const s=i.get(n),a=s?this._parentModelById.get(n):void 0;if(!s||!a)continue;const l=this._frameRate,c=[...null!==(u=this._curveNodesByModelId.get(a.id))&&void 0!==u?u:[],...this._collectInheritScaleCurves(a).filter(e=>e.targetModelId!==a.id)];if(c.length>0){const n=No(c,l,e.startTime,e.stopTime),s=e=>{var t;return this._computeInheritAwareLocalMatrix(a,this._sampleModelLocalMatrix(a,null!==(t=this._curveNodesByModelId.get(a.id))&&void 0!==t?t:[],e),e)},r=To._refineSampleTimes(n,s),i=[],u=[];let h=null;for(const e of r){const n=new t.Vector3,o=new t.Quaternion,r=new t.Vector3;s(e).decompose(n,o,r),h&&t.Quaternion.Dot(h,o)<0&&o.scaleInPlace(-1),h=o,i.push({frame:e*l,value:r}),u.push({frame:e*l,value:o})}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),d.addTargetedAnimation(e,o)}if(!ko(u)){const e=new t.Animation(`${o.name}_rotation`,"rotationQuaternion",l,t.Animation.ANIMATIONTYPE_QUATERNION,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(u),d.addTargetedAnimation(e,o)}}const h=this._collectInheritScaleCurves(a),f=r.get(n);if(f&&h.length>0&&!_.has(n)&&!m.has(n))for(const t of this._buildNodeAnimations([],f.name,s,e.startTime,e.stopTime,h))d.addTargetedAnimation(t,f)}const y=new Map;for(const e of g){const t=y.get(e.targetModelId);t?t.push(e):y.set(e.targetModelId,[e])}for(const[n,o]of Array.from(y)){o.sort((e,t)=>e.layerIndex-t.layerIndex);const s=o.filter(e=>e.curves.length>0).map(e=>({layerIndex:e.layerIndex,curves:e.curves}));if(0===s.length)continue;let r=!1;for(const o of a){if(!o.morphTargetManager||r)continue;const i=o.metadata,a=null==i?void 0:i.fbxBlendShapeChannelTargets,l=null==a?void 0:a.get(n);if(l){const n=this._frameRate;for(let r=0;r<l.targetIndices.length;r++){const i=o.morphTargetManager.getTarget(l.targetIndices[r]);if(!i)continue;const a=new t.Animation(`${i.name}_influence`,"influence",n,t.Animation.ANIMATIONTYPE_FLOAT,t.Animation.ANIMATIONLOOPMODE_CYCLE),u=this._layeredScalarKeys(s,e,e=>{var t;return null!==(t=Io(e,l.fullWeights,l.targetIndices.length)[r])&&void 0!==t?t:0});a.setKeys(u),d.addTargetedAnimation(a,i)}r=!0;continue}const u=null==i?void 0:i.fbxBlendShapeChannelIds;if(!u)continue;const c=u.get(n);if(void 0===c)continue;const h=o.morphTargetManager.getTarget(c);if(h){const n=this._frameRate,o=new t.Animation(`${h.name}_influence`,"influence",n,t.Animation.ANIMATIONTYPE_FLOAT,t.Animation.ANIMATIONLOOPMODE_CYCLE);o.setKeys(this._layeredScalarKeys(s,e,e=>e/100)),d.addTargetedAnimation(o,h),r=!0}}}const b=new Map;for(const t of e.unsupportedCurveNodes){if(null===t.targetId||0===t.curves.length)continue;const e=`${t.targetId}|${null!==(c=t.propertyName)&&void 0!==c?c:t.type}`,n=b.get(e);n?n.push(t):b.set(e,[t])}for(const t of Array.from(b.values())){t.sort((e,t)=>e.layerIndex-t.layerIndex);const n=this._buildPropertyAnimations(t,e,r,l);if(n.length>0)for(const e of t)this._evaluatedCurveNodeIds.add(e.id);for(const{animation:e,target:t}of n)d.addTargetedAnimation(e,t)}return d.targetedAnimations.length>0?(d.normalize(e.startTime*this._frameRate,e.stopTime*this._frameRate),d):(d.dispose(),null)}_buildInheritedRigBoneAnimations(e,n,o,s,r,i,a){var l;const u=this._frameRate,c=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)c.add(e.bones[n].modelId);const d=e.bones.filter(e=>c.has(e.modelId)).flatMap(e=>{var t;return null!==(t=o.get(e.modelId))&&void 0!==t?t:[]});let h=No(d,u,i,a);if(0===h.length)return[];for(const t of e.bones){const e=s.get(t.modelId),n=null!==(l=o.get(t.modelId))&&void 0!==l?l:[];c.has(t.modelId)&&e&&0!==n.length&&(h=To._refineSampleTimes(h,t=>this._sampleModelLocalMatrix(e,n,t)))}const f=e.bones.map(()=>({posKeys:[],rotKeys:[],sclKeys:[],prevQuat:null})),p=e.bones.map(()=>({posKeys:[],rotKeys:[],sclKeys:[],prevQuat:null})),m=e.bones.map((e,o)=>{const r=this._getSourceBone(n,o),i=s.get(e.modelId);if(!r||!i||!this._bindRestBones.has(r))return null;const a=To._computeFBXModelLocalMatrix(i),l=new t.Matrix;return a.invertToRef(l),l});for(const i of h){const a=e.bones.map((e,r)=>{var a,l;const u=s.get(e.modelId),c=null!==(a=o.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}),l=e.bones.map(e=>{var t;const n=s.get(e.modelId),r=null!==(t=o.get(e.modelId))&&void 0!==t?t:[];return n?this._sampleModelScale(n,r,i):e.scale}),c=To._computeBoneInheritScales(e.bones,l),d=i*u;for(let t=0;t<a.length;t++){if(!r.has(e.bones[t].modelId))continue;const n=e.bones[t].parentIndex,o=n>=0?c[n]:e.bones[t].scale,s=To._splitParentScaleCompensatedLocalMatrix(a[t],o,To._getBoneInheritedScale(e.bones,t,c));To._pushMatrixKeys(f[t],d,s.boneLocalMatrix),To._pushMatrixKeys(p[t],d,s.helperLocalMatrix)}}const _=[];for(let o=0;o<e.bones.length;o++){if(!r.has(e.bones[o].modelId))continue;const s=this._getSourceBone(n,o);if(!s)continue;const{posKeys:i,rotKeys:a,sclKeys:l}=f[o],c=[];if(!this._isVector3KeysConstant(i)){const e=new t.Animation(`${s.name}_position`,"position",u,t.Animation.ANIMATIONTYPE_VECTOR3,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(i),c.push(e)}if(!ko(a)){const e=new t.Animation(`${s.name}_rotation`,"rotationQuaternion",u,t.Animation.ANIMATIONTYPE_QUATERNION,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(a),c.push(e)}if(!this._isVector3KeysConstant(l)){const e=new t.Animation(`${s.name}_scaling`,"scaling",u,t.Animation.ANIMATIONTYPE_VECTOR3,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(l),c.push(e)}c.length>0&&_.push({bone:s,animations:c});const d=this._getScaleCompensationHelper(n,o);if(!d)continue;const h=[],{posKeys:m,rotKeys:g,sclKeys:v}=p[o];if(!this._isVector3KeysConstant(m)){const e=new t.Animation(`${d.name}_position`,"position",u,t.Animation.ANIMATIONTYPE_VECTOR3,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(m),h.push(e)}if(!ko(g)){const e=new t.Animation(`${d.name}_rotation`,"rotationQuaternion",u,t.Animation.ANIMATIONTYPE_QUATERNION,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(g),h.push(e)}if(!this._isVector3KeysConstant(v)){const e=new t.Animation(`${d.name}_scaling`,"scaling",u,t.Animation.ANIMATIONTYPE_VECTOR3,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(v),h.push(e)}h.length>0&&_.push({bone:d,animations:h})}return _}static _pushMatrixKeys(e,n,o){const s=new t.Vector3,r=new t.Quaternion,i=new t.Vector3;o.decompose(s,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:s})}_buildNodeAnimations(e,n,o,s,r,i=[]){const a=this._frameRate,l=e.find(e=>"R"===e.type),u=No([...e,...i],a,s,r);if(0===u.length)return[];const c=t=>{const n=this._sampleModelTRS(o,e,t),s=To._computeLocalTRS(o,n.translation,n.rotation,n.scale);return this._adjustTRSForInheritMode(o,s,t),s},d=To._refineSampleTimes(u,e=>{const n=c(e);return t.Matrix.Compose(n.scaling,n.rotationQuaternion,n.position)}),h=[],f=[],p=[];let m=null;for(const n of d){const o=n*a,s=c(n),r=s.scaling,i=s.rotationQuaternion,l=s.position,u=Hn(e,"T",n),d=Hn(e,"R",n),_=Hn(e,"S",n);m&&t.Quaternion.Dot(m,i)<0&&i.scaleInPlace(-1),m=i,h.push(u?{frame:o,value:l,interpolation:1}:{frame:o,value:l}),f.push(d?{frame:o,value:i,interpolation:1}:{frame:o,value:i}),p.push(_?{frame:o,value:r,interpolation:1}:{frame:o,value:r})}const _=[];if(!this._isVector3KeysConstant(h)){const e=new t.Animation(`${n}_position`,"position",a,t.Animation.ANIMATIONTYPE_VECTOR3,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(h),_.push(e)}if(l){const e=new t.Animation(`${n}_rotation`,"rotationQuaternion",a,t.Animation.ANIMATIONTYPE_QUATERNION,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(f),_.push(e)}if(!this._isVector3KeysConstant(p)){const e=new t.Animation(`${n}_scaling`,"scaling",a,t.Animation.ANIMATIONTYPE_VECTOR3,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(p),_.push(e)}return _}static _refineSampleTimes(e,n,o=2){const s=e=>{const o=new t.Vector3,s=new t.Quaternion,r=new t.Vector3;return n(e).decompose(o,s,r),{s:o,r:s,t:r}},r=[],i=(e,n,a,l,u)=>{if(u>=o)return;const c=.5*(e+n);if(!(c>e&&c<n))return;const d=s(c),h=t.Vector3.Lerp(a.t,l.t,.5),f=t.Vector3.Lerp(a.s,l.s,.5),p=t.Quaternion.Slerp(a.r,l.r,.5),m=t.Vector3.Distance(h,d.t),_=t.Vector3.Distance(f,d.s),g=Math.min(1,Math.abs(t.Quaternion.Dot(p,d.r))),v=2*Math.acos(g),y=1e-4*(1+Math.max(Math.abs(d.t.x),Math.abs(d.t.y),Math.abs(d.t.z))),b=1e-4*(1+Math.max(Math.abs(d.s.x),Math.abs(d.s.y),Math.abs(d.s.z)));(m>y||_>b||v>5e-4)&&(i(e,c,a,d,u+1),r.push(c),i(c,n,d,l,u+1))};let a=e.length>0?s(e[0]):null;for(let t=0;t<e.length;t++)if(r.push(e[t]),t+1<e.length&&a){const n=s(e[t+1]);i(e[t],e[t+1],a,n,0),a=n}return r}_layeredScalarKeys(e,t,n){const o=this._frameRate;if(0===e.length)return[];if(1===e.length)return Bo(e[0].curves[0],o,t.startTime,t.stopTime,n);const s=e[0].curves[0].channel;return No(e.map(e=>({type:"other",targetModelId:0,curves:Array.from(e.curves),layerIndex:e.layerIndex})),o,t.startTime,t.stopTime).map(r=>({frame:r*o,value:n(Un(e,t.layers,[s],[0],r)[0])}))}_buildPropertyAnimations(e,n,o,s){var r,i,a,l,u,c,d,h,f,p,m,_;const g=this._frameRate,v=e[0],y=null!==(r=v.propertyName)&&void 0!==r?r:v.type,b=v.targetId,x=[],T=null!==(i=v.curves.find(e=>"d|X"===e.channel))&&void 0!==i?i:v.curves[0],A=v.defaultValues,M=e.length>1,w=e.map(e=>({layerIndex:e.layerIndex,curves:e.curves,defaultValues:e.defaultValues})),S=()=>No(e.map(e=>({type:"other",targetModelId:b,curves:e.curves,layerIndex:e.layerIndex})),g,n.startTime,n.stopTime),C=e=>{const t=v.curves.find(e=>"d|X"===e.channel),o=v.curves.find(e=>"d|Y"===e.channel),s=v.curves.find(e=>"d|Z"===e.channel);return S().map(r=>{var i,a,l;return{frame:r*g,values:M?Un(w,n.layers,["d|X","d|Y","d|Z"],e,r):[null!==(i=In(t,r))&&void 0!==i?i:e[0],null!==(a=In(o,r))&&void 0!==a?a:e[1],null!==(l=In(s,r))&&void 0!==l?l:e[2]]}})},R=(e,t=!1)=>{const o=M?S().map(t=>{var o;return{frame:t*g,value:e(Un(w,n.layers,[T.channel],[null!==(o=A[T.channel])&&void 0!==o?o:0],t)[0])}}):Bo(T,g,n.startTime,n.stopTime,e);if(t)for(const e of o)e.interpolation=1,delete e.inTangent,delete e.outTangent;return o},I=()=>{var e,n,o;return C([null!==(e=A["d|X"])&&void 0!==e?e:1,null!==(n=A["d|Y"])&&void 0!==n?n:1,null!==(o=A["d|Z"])&&void 0!==o?o:1]).map(({frame:e,values:n})=>({frame:e,value:new t.Color3(n[0],n[1],n[2])}))},O=(e,n,o,s,r)=>{if(0===s.length)return;const i=new t.Animation(`${r}_${n}`,n,g,o,t.Animation.ANIMATIONLOOPMODE_CYCLE);i.setKeys(s),x.push({animation:i,target:e})},F=o.get(b);if(F){if("Visibility"===y&&F instanceof t.Mesh)return O(F,"visibility",t.Animation.ANIMATIONTYPE_FLOAT,R(e=>Math.min(1,Math.max(0,e)),!0),F.name),x;const e=null===(a=F.metadata)||void 0===a?void 0:a.fbxUserProperties;if(e&&y in e)if(v.curves.some(e=>"d|Y"===e.channel||"d|Z"===e.channel)){const n=e[y],o=Array.isArray(n)?n:[0,0,0];e[y]=new t.Vector3(null!==(l=o[0])&&void 0!==l?l:0,null!==(u=o[1])&&void 0!==u?u:0,null!==(c=o[2])&&void 0!==c?c:0);const s=C([null!==(d=o[0])&&void 0!==d?d:0,null!==(h=o[1])&&void 0!==h?h:0,null!==(f=o[2])&&void 0!==f?f:0]).map(({frame:e,values:n})=>({frame:e,value:new t.Vector3(n[0],n[1],n[2])}));O(F,`metadata.fbxUserProperties.${y}`,t.Animation.ANIMATIONTYPE_VECTOR3,s,F.name)}else"boolean"==typeof e[y]&&(e[y]=e[y]?1:0),O(F,`metadata.fbxUserProperties.${y}`,t.Animation.ANIMATIONTYPE_FLOAT,R(e=>e),F.name);return x}const E=s.cameraByAttributeId.get(b);if(E){const e=null===(p=E.metadata)||void 0===p?void 0:p.fbxCamera,n=(null==e?void 0:e.aspectRatio)||1,o=null!==(m=null==e?void 0:e.apertureMode)&&void 0!==m?m:2;switch(y){case"FieldOfView":O(E,"fov",t.Animation.ANIMATIONTYPE_FLOAT,R(e=>1===o?2*Math.atan(Math.tan(e*Math.PI/360)/n):e*Math.PI/180),E.name);break;case"FieldOfViewY":O(E,"fov",t.Animation.ANIMATIONTYPE_FLOAT,R(e=>e*Math.PI/180),E.name);break;case"FieldOfViewX":0!==o&&O(E,"fov",t.Animation.ANIMATIONTYPE_FLOAT,R(e=>2*Math.atan(Math.tan(e*Math.PI/360)/n)),E.name);break;case"FocalLength":{const n=null===(_=null==e?void 0:e.apertureSizeInch)||void 0===_?void 0:_[1];n&&3===o&&O(E,"fov",t.Animation.ANIMATIONTYPE_FLOAT,R(e=>2*Math.atan(n/Math.max(e/25.4,1e-6)*.5)),E.name);break}case"NearPlane":O(E,"minZ",t.Animation.ANIMATIONTYPE_FLOAT,R(e=>e),E.name);break;case"FarPlane":O(E,"maxZ",t.Animation.ANIMATIONTYPE_FLOAT,R(e=>e),E.name)}return x}const L=s.lightByAttributeId.get(b);if(L){switch(y){case"Intensity":O(L,"intensity",t.Animation.ANIMATIONTYPE_FLOAT,R(e=>e/100),L.name);break;case"Color":O(L,"diffuse",t.Animation.ANIMATIONTYPE_COLOR3,I(),L.name);break;case"OuterAngle":case"ConeAngle":L instanceof t.SpotLight&&O(L,"angle",t.Animation.ANIMATIONTYPE_FLOAT,R(e=>e*Math.PI/180),L.name);break;case"InnerAngle":L instanceof t.SpotLight&&O(L,"innerAngle",t.Animation.ANIMATIONTYPE_FLOAT,R(e=>e*Math.PI/180),L.name)}return x}const N=s.materialCache.get(b);if(N){const e=N instanceof t.PBRMaterial,n=y.substring(y.lastIndexOf("|")+1);return"DiffuseColor"===y||"Diffuse"===y||"baseColor"===n||"base_color"===n||"color"===n?O(N,e?"albedoColor":"diffuseColor",t.Animation.ANIMATIONTYPE_COLOR3,I(),N.name):"EmissiveColor"===y||"Emissive"===y||"emissionColor"===n||"emission_color"===n||"emissive"===n||"emit_color"===n?O(N,"emissiveColor",t.Animation.ANIMATIONTYPE_COLOR3,I(),N.name):"Opacity"===y?O(N,"alpha",t.Animation.ANIMATIONTYPE_FLOAT,R(e=>e),N.name):"TransparencyFactor"===y||"TransparentFactor"===y?O(N,"alpha",t.Animation.ANIMATIONTYPE_FLOAT,R(e=>1-e),N.name):!e||"roughness"!==n&&"specular_roughness"!==n&&"specularRoughness"!==n?!e||"metalness"!==n&&"metallic"!==n&&"base_metalness"!==n?e||"SpecularColor"!==y||O(N,"specularColor",t.Animation.ANIMATIONTYPE_COLOR3,I(),N.name):O(N,"metallic",t.Animation.ANIMATIONTYPE_FLOAT,R(e=>e),N.name):O(N,"roughness",t.Animation.ANIMATIONTYPE_FLOAT,R(e=>e),N.name),x}return x}_applyConstraints(e,n,o,s){var r,i,a,l,u;const c=e=>{var t;return void 0===e||null===(t=n.get(e))||void 0===t?void 0:t.name},d=e.upAxisSign>=0?1:-1,h=new t.Vector3(0===e.upAxis?d:0,1===e.upAxis?d:0,2===e.upAxis?d:0),f=[];for(const s of e.constraints){const e=Object.assign({name:s.name,type:s.type,node:c(s.nodeId),targets:s.targets.map(e=>({node:c(e.modelId),weight:e.weight})),weight:s.weight,active:s.active},"singleChainIK"===s.type?{firstJoint:c(s.ikFirstJointId),endJoint:c(s.ikEndJointId),effector:c(s.ikEffectorId)}:{});f.push(e);const u=void 0!==s.nodeId?n.get(s.nodeId):void 0;if(!u)continue;const d=null!==(i=null===(r=u.metadata)||void 0===r?void 0:r.fbxConstraints)&&void 0!==i?i:[];if(u.metadata=Object.assign(Object.assign({},null!==(a=u.metadata)&&void 0!==a?a:{}),{fbxConstraints:[...d,e]}),"apply"!==this._options.constraints||"singleChainIK"===s.type||"unknown"===s.type)continue;const p=[];for(const e of s.targets){const o=n.get(e.modelId);if(!o)continue;const r=Math.PI/180,i="parent"===s.type?t.Matrix.Compose(new t.Vector3(...e.offsetScale),t.Quaternion.FromRotationMatrix(fo(e.offsetRotation[0]*r,e.offsetRotation[1]*r,e.offsetRotation[2]*r)),new t.Vector3(...e.offsetTranslation)):t.Matrix.Identity();p.push({node:o,weight:e.weight,offset:i})}if(0===p.length)continue;const m=void 0!==s.worldUpNodeId&&null!==(l=n.get(s.worldUpNodeId))&&void 0!==l?l:null;u.addBehavior(new bo(s,{root:o,targets:p,upNode:m,sceneUp:h}))}f.length>0&&(o.metadata=Object.assign(Object.assign({},null!==(u=o.metadata)&&void 0!==u?u:{}),{fbxConstraints:f}))}_reportDiagnostics(e,t,n){var o,s;const r=[],i=(e,t,n)=>{var o;const s="string"==typeof t?t:null!==(o=null==t?void 0:t.message)&&void 0!==o?o:JSON.stringify(t);r.push({source:e,message:s,objectName:n,details:"string"==typeof t?void 0:t})};for(const t of e.diagnostics)"duplicate-parent"!==t.subType&&i("scene",t,null!==(o=t.objectName)&&void 0!==o?o:t.nodeName);for(const t of e.geometries)for(const e of t.diagnostics)i("geometry",e,t.name);for(const t of e.curves)for(const e of t.diagnostics)i("geometry",e,t.name);for(const t of e.skins){for(const e of t.diagnostics)i("skin",e);for(const e of t.bones)for(const t of e.diagnostics)i("skin",t,e.name)}for(const t of e.rigs)for(const e of t.warnings)i("rig",e);for(const t of e.animations)for(const e of t.diagnostics)"unsupported-curve-node"===e.type&&void 0!==e.curveNodeId&&this._evaluatedCurveNodeIds.has(e.curveNodeId)||i("animation",e,t.name);for(const t of e.cameras)for(const e of t.diagnostics)i("camera",e,t.name);for(const t of e.lights)for(const e of t.diagnostics)i("light",e,t.name);const a=e=>{for(const t of e){for(const e of t.diagnostics)i("model",e,t.name);a(t.children)}};a(e.rootModels),t.metadata=Object.assign(Object.assign({},null!==(s=t.metadata)&&void 0!==s?s:{}),{fbxDiagnostics:r,fbxDisplayLayers:e.displayLayers.map(e=>({name:e.name,show:e.show,freeze:e.freeze,color:e.color})),fbxSelectionSets:e.selectionSets.map(e=>({name:e.name,members:e.members.map(e=>{var t,o;return Object.assign(Object.assign(Object.assign({node:null!==(o=null===(t=n.get(e.modelId))||void 0===t?void 0:t.name)&&void 0!==o?o:String(e.modelId),includeNode:e.includeNode},e.vertices?{vertices:e.vertices}:{}),e.edges?{edges:e.edges}:{}),e.faces?{faces:e.faces}:{})})}))});for(const e of r)this._options.onWarning(e)}_collectInheritScaleCurves(e){var t;const n=[];let o=e;const s=new Set;for(;o&&!s.has(o.id);){s.add(o.id);for(const e of null!==(t=this._curveNodesByModelId.get(o.id))&&void 0!==t?t:[])"S"===e.type&&n.push(e);o=this._getInheritScaleNode(o)}return n}_isVector3KeysConstant(e){if(e.length<2)return!0;const t=e[0].value;for(let n=1;n<e.length;n++){const o=e[n].value;if(Math.abs(o.x-t.x)>1e-4||Math.abs(o.y-t.y)>1e-4||Math.abs(o.z-t.z)>1e-4)return!1}return!0}_sampleModelTRS(e,t,n){const o=this._activeLayers;return{translation:$n(t,o,"T",e.translation,e.rotationOrder,n),rotation:$n(t,o,"R",e.rotation,e.rotationOrder,n),scale:$n(t,o,"S",e.scale,e.rotationOrder,n)}}static _computeLocalTRS(e,n,o,s){const r=e=>0!==e[0]||0!==e[1]||0!==e[2],i=Math.PI/180;let a=po(o[0]*i,o[1]*i,o[2]*i,e.rotationOrder);if(r(e.preRotation)&&(a=a.multiply(fo(e.preRotation[0]*i,e.preRotation[1]*i,e.preRotation[2]*i))),r(e.postRotation)){const n=fo(e.postRotation[0]*i,e.postRotation[1]*i,e.postRotation[2]*i),o=new t.Matrix;n.invertToRef(o),a=o.multiply(a)}let l=new t.Vector3(n[0],n[1],n[2]);return(r(e.rotationPivot)||r(e.scalingPivot)||r(e.rotationOffset)||r(e.scalingOffset))&&(l=To._computeFBXLocalMatrix(n,o,s,e.preRotation,e.postRotation,e.rotationPivot,e.scalingPivot,e.rotationOffset,e.scalingOffset,e.rotationOrder).getTranslation()),{position:l,rotationQuaternion:t.Quaternion.FromRotationMatrix(a),scaling:new t.Vector3(s[0],s[1],s[2])}}_adjustTRSForInheritMode(e,t,n){const o=this._parentModelById.get(e.id);if(1===e.inheritType||!o)return;const s=this._getInheritScale(o,n);t.position.x*=s[0],t.position.y*=s[1],t.position.z*=s[2];const r=this._getInheritScaleNode(e);if(r){const e=this._getInheritScale(r,n);t.scaling.x*=e[0],t.scaling.y*=e[1],t.scaling.z*=e[2]}}_sampleModelLocalMatrix(e,t,n,o){const s=this._sampleModelTRS(e,t,n);return To._computeFBXLocalMatrix(s.translation,s.rotation,null!=o?o:s.scale,e.preRotation,e.postRotation,e.rotationPivot,e.scalingPivot,e.rotationOffset,e.scalingOffset,e.rotationOrder)}_sampleModelScale(e,t,n){return $n(t,this._activeLayers,"S",e.scale,e.rotationOrder,n)}_getInheritScale(e,t){var n;if(!e)return[1,1,1];const o=void 0===t?e.scale:this._sampleModelScale(e,null!==(n=this._curveNodesByModelId.get(e.id))&&void 0!==n?n:[],t),s=this._getInheritScaleNode(e);if(!s)return[o[0],o[1],o[2]];const r=this._getInheritScale(s,t);return[o[0]*r[0],o[1]*r[1],o[2]*r[2]]}_getInheritScaleNode(e){const t=this._parentModelById.get(e.id);if(t)return 0===e.inheritType?t:2===e.inheritType?this._getInheritScaleNode(t):void 0}_computeInheritAwareLocalMatrix(e,n,o){const s=this._parentModelById.get(e.id);if(1===e.inheritType||!s)return n;const r=new t.Vector3,i=new t.Quaternion,a=new t.Vector3;n.decompose(r,i,a);const l=this._getInheritScale(s,o);a.x*=l[0],a.y*=l[1],a.z*=l[2];const u=this._getInheritScaleNode(e);if(u){const e=this._getInheritScale(u,o);r.x*=e[0],r.y*=e[1],r.z*=e[2]}return t.Matrix.Compose(r,i,a)}_buildBoneAnimations(e,n,o,s,r,i){const a=this._frameRate,l=e.find(e=>"R"===e.type),u=No(e,a,s,r);if(0===u.length)return[];const c=To._refineSampleTimes(u,t=>this._sampleModelLocalMatrix(o,e,t)),d=[],h=[],f=[];let p=null,m=null;if(i){const e=To._computeFBXLocalMatrix(o.translation,o.rotation,o.scale,o.preRotation,o.postRotation,o.rotationPivot,o.scalingPivot,o.rotationOffset,o.scalingOffset,o.rotationOrder);m=new t.Matrix,e.invertToRef(m)}for(const n of c){const s=n*a,r=this._sampleModelLocalMatrix(o,e,n),l=m&&i?i.multiply(m).multiply(r):r,u=new t.Vector3,c=new t.Quaternion,_=new t.Vector3;l.decompose(u,c,_),p&&t.Quaternion.Dot(p,c)<0&&c.scaleInPlace(-1),p=c,d.push({frame:s,value:_}),h.push({frame:s,value:c}),f.push({frame:s,value:u})}const _=[];if(!this._isVector3KeysConstant(d)){const e=new t.Animation(`${n}_position`,"position",a,t.Animation.ANIMATIONTYPE_VECTOR3,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(d),_.push(e)}if(l){const e=new t.Animation(`${n}_rotation`,"rotationQuaternion",a,t.Animation.ANIMATIONTYPE_QUATERNION,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(h),_.push(e)}if(!this._isVector3KeysConstant(f)){const e=new t.Animation(`${n}_scaling`,"scaling",a,t.Animation.ANIMATIONTYPE_VECTOR3,t.Animation.ANIMATIONLOOPMODE_CYCLE);e.setKeys(f),_.push(e)}return _}_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 Ao(e){const t=new Float32Array(e.length);for(let n=0;n<e.length;n++)t[n]=e[n];return t}function Mo(e,t,n,o,s,r,i,a,l,u,c,d,h,f,p,m){var _;const g=function(e,t,n,o){const s=3*t,r=3*n,i=3*o,a=e[r]-e[s],l=e[r+1]-e[s+1],u=e[r+2]-e[s+2],c=e[i]-e[s],d=e[i+1]-e[s+1],h=e[i+2]-e[s+2],f=Math.hypot(a,l,u),p=Math.hypot(c,d,h);if(f<=1e-8||p<=1e-8)return 0;const m=(a*c+l*d+u*h)/(f*p);return Math.acos(Math.max(-1,Math.min(1,m)))}(u,e,t,n);if(g<=1e-8)return;const v=function(e,t,n,o,s,r,i,a,l,u,c,d){const h=3*e,f=3*e,p=2*e,[m,_,g]=wo(l[f],l[f+1],l[f+2]),v=function(e,t,n,o,s,r,i,a,l){return(t*r-n*s)*i+(n*o-e*r)*a+(e*s-t*o)*l<0?-1:1}(m,_,g,t,n,o,s,r,i);return[c?`cp:${c[e]}`:`p:${So(a[h])},${So(a[h+1])},${So(a[h+2])}`,So(m),So(_),So(g),So(u[p]),So(u[p+1]),v,d].join("|")}(e,o,s,r,i,a,l,u,c,d,h,f);let y=p.get(v);y||(y={tx:0,ty:0,tz:0,bx:0,by:0,bz:0},p.set(v,y)),y.tx+=o*g,y.ty+=s*g,y.tz+=r*g,y.bx+=i*g,y.by+=a*g,y.bz+=l*g,null!==(_=m[e])&&void 0!==_||(m[e]=v)}function wo(e,t,n){const o=Math.hypot(e,t,n);return o>1e-8?[e/o,t/o,n/o]:[0,0,1]}function So(e){const t=Math.round(1e6*e);return Object.is(t,-0)?0:t}function Co(e,t,n){const o=Math.abs(e)<.9?1:0,s=1===o?0:1,r=e*o+t*s;let i=o-e*r,a=s-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 Ro(e,n,o,s,r,i){const a=o.length/3,l=new Float32Array(3*a),u=null!==e.normals&&null!==s?new Float32Array(3*a):null;for(let e=0;e<l.length;e++)l[e]=o[e];if(u&&s)for(let e=0;e<u.length;e++)u[e]=s[e];const c=new Map;for(let t=0;t<e.indices.length;t++)c.set(e.indices[t],t);for(let o=0;o<a;o++){const s=n[o],a=c.get(s);if(void 0===a)continue;let d=e.vertices[3*a],h=e.vertices[3*a+1],f=e.vertices[3*a+2];if(r){const e=t.Vector3.TransformNormal(new t.Vector3(d,h,f),r);d=e.x,h=e.y,f=e.z}if(l[3*o]+=d,l[3*o+1]+=h,l[3*o+2]+=f,u&&e.normals){let n=e.normals[3*a],s=e.normals[3*a+1],r=e.normals[3*a+2];if(i){const e=t.Vector3.TransformNormal(new t.Vector3(n,s,r),i);e.lengthSquared()>0&&e.normalize(),n=e.x,s=e.y,r=e.z}u[3*o]+=n,u[3*o+1]+=s,u[3*o+2]+=r}}return{positions:l,normals:u}}function Io(e,t,n){if(n<=0)return[];if(!t||t.length!==n||1===n)return[Oo(e/((null==t?void 0:t[0])&&0!==t[0]?t[0]:100))];const o=new Array(n).fill(0);if(e<=t[0])return o[0]=0===t[0]?e<=0?1:0:Oo(e/t[0]),o;for(let n=1;n<t.length;n++){const s=t[n-1],r=t[n];if(e>r)continue;const i=r-s;if(Math.abs(i)<1e-6)return o[n]=1,o;const a=Oo((e-s)/i);return o[n-1]=1-a,o[n]=a,o}return o[n-1]=1,o}function Oo(e){return Math.max(0,Math.min(1,e))}const Fo=512,Eo=32,Lo=1e5;function No(e,t,n,o){let s=Number.POSITIVE_INFINITY,r=Number.NEGATIVE_INFINITY;const i=new Set,a=[];for(const t of e)for(const e of t.curves){a.push(e);for(const t of e.keys)s=Math.min(s,t.time),r=Math.max(r,t.time),t.time>=n&&t.time<=o&&i.add(t.time)}if(!Number.isFinite(s)||!Number.isFinite(r))return[];const l=o>n?n:s,u=o>n?o:r;i.add(l),i.add(u);const c=Array.from(i).filter(e=>e>=l&&e<=u).sort((e,t)=>e-t),d=e=>{for(const t of a){const n=t.keys;if(0===n.length)continue;if(e<n[0].time){if(t.preExtrapolation&&"constant"!==t.preExtrapolation.mode)return!0;continue}if(e>=n[n.length-1].time){if(t.postExtrapolation&&"constant"!==t.postExtrapolation.mode)return!0;continue}let o=0,s=n.length-1;for(;s-o>1;){const t=o+s>>1;n[t].time<=e?o=t:s=t}if("cubic"===n[o].interpolation)return!0}return!1},h=[],f=Math.floor(u*t)-Math.ceil(l*t)+1,p=Math.max(1,Math.ceil(f/Lo));for(let e=0;e<c.length;e++){const n=c[e];if(h.push(n),e+1>=c.length)break;const o=c[e+1],s=Math.floor(n*t)+1,r=Math.ceil(o*t)-1,i=r-s+1;if(i<=0)continue;const a=d(n)?Fo:Eo,l=Math.max(p,Math.ceil(i/a));for(let e=s;e<=r;e+=l)h.push(e/t)}const m=h.sort((e,t)=>e-t),_=[];for(const e of m)e<l-1e-9||e>u+1e-9||(0===_.length||e-_[_.length-1]>1e-9)&&_.push(e);return _}function ko(e){if(e.length<2)return!0;const t=e[0].value;for(let n=1;n<e.length;n++){const o=e[n].value;if(Math.abs(o.x-t.x)>1e-4||Math.abs(o.y-t.y)>1e-4||Math.abs(o.z-t.z)>1e-4||Math.abs(o.w-t.w)>1e-4)return!1}return!0}function Bo(e,t,n,o,s){var r,i,a,l,u,c;const d=function(e,t,n){var o,s,r,i;return n>t?{start:t,stop:n}:{start:null!==(s=null===(o=e.keys[0])||void 0===o?void 0:o.time)&&void 0!==s?s: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,o),h=e.keys.filter(e=>e.time>=d.start&&e.time<=d.stop).map(e=>({source:e,frame:e.time*t,value:s(e.value)}));h.some(e=>Math.abs(e.source.time-d.start)<1e-6)||h.unshift({source:{time:d.start,value:null!==(r=In(e,d.start))&&void 0!==r?r:0,interpolation:"linear",leftDx:0,leftDy:0,rightDx:0,rightDy:0},frame:d.start*t,value:s(null!==(i=In(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=In(e,d.stop))&&void 0!==a?a:0,interpolation:"linear",leftDx:0,leftDy:0,rightDx:0,rightDy:0},frame:d.stop*t,value:s(null!==(l=In(e,d.stop))&&void 0!==l?l:0)});const f=h.map(e=>({frame:e.frame,value:e.value}));for(let e=0;e<h.length-1;e++){const n=h[e].source,o=f[e+1];if("constant"===n.interpolation){f[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;f[e].outTangent=Po(null!==(u=n.rightSlope)&&void 0!==u?u:a,s)/t,o.inTangent=Po(null!==(c=n.nextLeftSlope)&&void 0!==c?c:a,s)/t}return f}function Po(e,t){return t(e)-t(0)}let Do=!1;function Vo(){Do||(Do=!0,t.RegisterSceneLoaderPlugin(new To))}var Go={__proto__:null,FBXFileLoader:To,RegisterFBXFileLoader:Vo};function $o(e,t,n,o){const s={externalResourceFunction:o};return n&&(s.uri="file:"===t?n:t+n),ArrayBuffer.isView(e)?GLTFValidator.validateBytes(e,s):GLTFValidator.validateString(e,s)}function Uo(){const e=[];onmessage=t=>{const n=t.data;switch(n.id){case"init":importScripts(n.url);break;case"validate":$o(n.data,n.rootUrl,n.fileName,t=>new Promise((n,o)=>{const s=e.length;e.push({resolve:n,reject:o}),postMessage({id:"getExternalResource",index:s,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)}}}Vo();class Ho{static ValidateAsync(e,n,o,s){return"function"==typeof Worker?new Promise((r,i)=>{const a=`${$o}(${Uo})()`,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":s(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),Ho._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:o},[t.buffer])}else u.postMessage({id:"validate",data:e,rootUrl:n,fileName:o})}):(this._LoadScriptPromise||(this._LoadScriptPromise=t.Tools.LoadBabylonScriptAsync(this.Configuration.url)),this._LoadScriptPromise.then(()=>$o(e,n,o,s)))}}Ho.Configuration={url:`${t.Tools._DefaultCdnUrl}/gltf_validator.js`},Ho._LastResults=null;var Ko={__proto__:null,GLTFValidation:Ho};const Wo="Z2xURg",qo={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,"+Wo)||e.startsWith("data:;base64,"+Wo)||e.startsWith("data:application/octet-stream;base64,"+Wo)||e.startsWith("data:model/gltf-binary;base64,"+Wo)};function zo(e,t,n){try{return Promise.resolve(new Uint8Array(e,t,n))}catch(e){return Promise.reject(e)}}var jo,Xo,Yo;e.GLTFLoaderCoordinateSystemMode=void 0,(jo=e.GLTFLoaderCoordinateSystemMode||(e.GLTFLoaderCoordinateSystemMode={}))[jo.AUTO=0]="AUTO",jo[jo.FORCE_RIGHT_HANDED=1]="FORCE_RIGHT_HANDED",e.GLTFLoaderAnimationStartMode=void 0,(Xo=e.GLTFLoaderAnimationStartMode||(e.GLTFLoaderAnimationStartMode={}))[Xo.NONE=0]="NONE",Xo[Xo.FIRST=1]="FIRST",Xo[Xo.ALL=2]="ALL",e.GLTFLoaderState=void 0,(Yo=e.GLTFLoaderState||(e.GLTFLoaderState={}))[Yo.LOADING=0]="LOADING",Yo[Yo.READY=1]="READY",Yo[Yo.COMPLETE=2]="COMPLETE";const Qo=e=>Promise.resolve(e);class Zo{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 Jo=new Zo;class es extends Zo{constructor(){super(...arguments),this.extensionOptions={},this.preprocessUrlAsync=Qo}copyFrom(e){var t,n,o,s,r,i,a,l,u,c,d,h,f,p,m,_,g,v,y,b,x,T,A,M,w,S,C;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!==(o=e.animationStartMode)&&void 0!==o?o:this.animationStartMode,this.capturePerformanceCounters=null!==(s=e.capturePerformanceCounters)&&void 0!==s?s: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!==(f=e.loadOnlyMaterials)&&void 0!==f?f:this.loadOnlyMaterials,this.loadSkins=null!==(p=e.loadSkins)&&void 0!==p?p:this.loadSkins,this.loggingEnabled=null!==(m=e.loggingEnabled)&&void 0!==m?m: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!==(v=e.targetFps)&&void 0!==v?v:this.targetFps,this.transparencyAsCoverage=null!==(y=e.transparencyAsCoverage)&&void 0!==y?y: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!==(S=e.validate)&&void 0!==S?S:this.validate,this.dontUseTransmissionHelper=null!==(C=e.dontUseTransmissionHelper)&&void 0!==C?C:this.dontUseTransmissionHelper)}}class ts extends es{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=qo.name,this.extensions=qo.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({},Jo),e))}get _isPreprocessUrlAsyncSet(){return this.preprocessUrlAsync!==Qo}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=Qo,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,o,s,r,i,a,l){if(ArrayBuffer.isView(n))return this._loadBinary(e,n,o,s,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 o={abort:()=>{},onCompleteObservable:new t.Observable},r={readAsync:(t,o)=>new Promise((s,r)=>{this._loadFile(e,n,e=>{s(new Uint8Array(e))},!0,e=>{r(e)},e=>{e.setRequestHeader("Range",`bytes=${t}-${t+o-1}`)})}),byteLength:0};return this._unpackBinaryAsync(new t.DataReader(r)).then(e=>{o.onCompleteObservable.notifyObservers(o),s(e)},a?e=>a(void 0,e):void 0),o}return this._loadFile(e,n,n=>{this._validate(e,new Uint8Array(n,0,n.byteLength),o,u),this._unpackBinaryAsync(new t.DataReader({readAsync:(e,t)=>zo(n,e,t),byteLength:n.byteLength})).then(e=>{s(e)},a?e=>a(void 0,e):void 0)},!0,a)}return this._loadFile(e,n,t=>{try{this._validate(e,t,o,u),s({json:this._parseJson(t)})}catch(e){a&&a()}},!1,a)}_loadBinary(e,n,o,s,r,i){this._validate(e,new Uint8Array(n.buffer,n.byteOffset,n.byteLength),o,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=>{s(e)},r?e=>r(void 0,e):void 0)}importMeshAsync(e,t,n,o,s,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,o,s,r)))}loadAsync(e,t,n,o,s){return Promise.resolve().then(()=>(this.onParsedObservable.notifyObservers(t),this.onParsedObservable.clear(),this._log(`Loading ${s||""}`),this._loader=this._getLoader(t),this._loader.loadAsync(e,t,n,o,s)))}loadAssetContainerAsync(e,n,o,s,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,o,s,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 qo.canDirectLoad(e)}directLoad(e,n){if(n.startsWith("base64,"+Wo)||n.startsWith(";base64,"+Wo)||n.startsWith("application/octet-stream;base64,"+Wo)||n.startsWith("model/gltf-binary;base64,"+Wo)){const o=t.DecodeBase64UrlToBinary(n);return this._validate(e,new Uint8Array(o,0,o.byteLength)),this._unpackBinaryAsync(new t.DataReader({readAsync:(e,t)=>zo(o,e,t),byteLength:o.byteLength}))}return this._validate(e,n),Promise.resolve({json:this._parseJson(n)})}createPlugin(e){return new ts(e[qo.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,o,s,r){const i=e._loadFile(t,n,e=>{this._onProgress(e,i)},!0,o,s,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,o=0,s=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,o+=e._loaded,s+=e._total}this._progressCallback({lengthComputable:n,loaded:o,total:n?s:0})}_validate(e,n,o="",s=""){this.validate&&(this._startPerformanceCounter("Validate JSON"),Ho.ValidateAsync(n,o,s,t=>this.preprocessUrlAsync(o+t,o).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=ts._parseVersion(t.version);if(!n)throw new Error("Invalid version: "+t.version);if(void 0!==t.minVersion){const e=ts._parseVersion(t.minVersion);if(!e)throw new Error("Invalid minimum version: "+t.minVersion);if(ts._compareVersion(e,{major:2,minor:0})>0)throw new Error("Incompatible minimum version: "+t.minVersion)}const o={1:ts._CreateGLTF1Loader,2:ts._CreateGLTF2Loader}[n.major];if(!o)throw new Error("Unsupported version: "+t.version);return o(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 o=e.readUint32();this.loggingEnabled&&this._log(`Binary version: ${o}`);const s=e.readUint32();let r;switch(this.useRangeRequests||s===e.buffer.byteLength||t.Logger.Warn(`Length in header does not match actual data length: ${s} != ${e.buffer.byteLength}`),o){case 1:r=this._unpackBinaryV1Async(e,s);break;case 2:r=this._unpackBinaryV2Async(e,s);break;default:throw new Error("Unsupported version: "+o)}return this._endPerformanceCounter("Unpack Binary"),r})}_unpackBinaryV1Async(e,t){const n=e.readUint32(),o=e.readUint32();if(0!==o)throw new Error(`Unexpected content format: ${o}`);const s=t-e.byteOffset,r={json:this._parseJson(e.readString(n)),bin:null};if(0!==s){const t=e.byteOffset;r.bin={readAsync:(n,o)=>e.buffer.readAsync(t+n,o),byteLength:s}}return Promise.resolve(r)}_unpackBinaryV2Async(e,t){const n=1313821514,o=e.readUint32();if(e.readUint32()!==n)throw new Error("First chunk format is not JSON");return e.byteOffset+o===t?e.loadAsync(o).then(()=>({json:this._parseJson(e.readString(o)),bin:null})):e.loadAsync(o+8).then(()=>{const s={json:this._parseJson(e.readString(o)),bin:null},r=()=>{const o=e.readUint32();switch(e.readUint32()){case n:throw new Error("Unexpected JSON chunk");case 5130562:{const t=e.byteOffset;s.bin={readAsync:(n,o)=>e.buffer.readAsync(t+n,o),byteLength:o},e.skipBytes(o);break}default:e.skipBytes(o)}return e.byteOffset!==t?e.loadAsync(8).then(r):Promise.resolve(s)};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=ts._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){}}ts.IncrementalLoading=!0,ts.HomogeneousCoordinates=!1,ts._logSpaces=" ";let ns=!1;function os(){ns||(ns=!0,t.RegisterSceneLoaderPlugin(new ts))}os();var ss,rs,is,as,ls,us,cs,ds,hs,fs={__proto__:null,GLTFFileLoader:ts,get GLTFLoaderAnimationStartMode(){return e.GLTFLoaderAnimationStartMode},get GLTFLoaderCoordinateSystemMode(){return e.GLTFLoaderCoordinateSystemMode},GLTFLoaderDefaultOptions:Jo,get GLTFLoaderState(){return e.GLTFLoaderState},RegisterGLTFFileLoader:os};!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"}(ss||(ss={})),function(e){e[e.FRAGMENT=35632]="FRAGMENT",e[e.VERTEX=35633]="VERTEX"}(rs||(rs={})),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"}(is||(is={})),function(e){e[e.CLAMP_TO_EDGE=33071]="CLAMP_TO_EDGE",e[e.MIRRORED_REPEAT=33648]="MIRRORED_REPEAT",e[e.REPEAT=10497]="REPEAT"}(as||(as={})),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"}(ls||(ls={})),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"}(us||(us={})),function(e){e[e.FRONT=1028]="FRONT",e[e.BACK=1029]="BACK",e[e.FRONT_AND_BACK=1032]="FRONT_AND_BACK"}(cs||(cs={})),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"}(ds||(ds={}));class ps{static SetMatrix(e,n,o,s,r){let i=null;if("MODEL"===o.semantic?i=n.getWorldMatrix():"PROJECTION"===o.semantic?i=e.getProjectionMatrix():"VIEW"===o.semantic?i=e.getViewMatrix():"MODELVIEWINVERSETRANSPOSE"===o.semantic?i=t.Matrix.Transpose(n.getWorldMatrix().multiply(e.getViewMatrix()).invert()):"MODELVIEW"===o.semantic?i=n.getWorldMatrix().multiply(e.getViewMatrix()):"MODELVIEWPROJECTION"===o.semantic?i=n.getWorldMatrix().multiply(e.getTransformMatrix()):"MODELINVERSE"===o.semantic?i=n.getWorldMatrix().invert():"VIEWINVERSE"===o.semantic?i=e.getViewMatrix().invert():"PROJECTIONINVERSE"===o.semantic?i=e.getProjectionMatrix().invert():"MODELVIEWINVERSE"===o.semantic?i=n.getWorldMatrix().multiply(e.getViewMatrix()).invert():"MODELVIEWPROJECTIONINVERSE"===o.semantic?i=n.getWorldMatrix().multiply(e.getTransformMatrix()).invert():"MODELINVERSETRANSPOSE"===o.semantic&&(i=t.Matrix.Transpose(n.getWorldMatrix().invert())),i)switch(o.type){case is.FLOAT_MAT2:r.setMatrix2x2(s,t.Matrix.GetAsMatrix2x2(i));break;case is.FLOAT_MAT3:r.setMatrix3x3(s,t.Matrix.GetAsMatrix3x3(i));break;case is.FLOAT_MAT4:r.setMatrix(s,i)}}static SetUniform(e,n,o,s){switch(s){case is.FLOAT:return e.setFloat(n,o),!0;case is.FLOAT_VEC2:return e.setVector2(n,t.Vector2.FromArray(o)),!0;case is.FLOAT_VEC3:return e.setVector3(n,t.Vector3.FromArray(o)),!0;case is.FLOAT_VEC4:return e.setVector4(n,t.Vector4.FromArray(o)),!0;default:return!1}}static GetWrapMode(e){switch(e){case as.CLAMP_TO_EDGE:return t.Texture.CLAMP_ADDRESSMODE;case as.MIRRORED_REPEAT:return t.Texture.MIRROR_ADDRESSMODE;case as.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 ls.LINEAR:case ls.LINEAR_MIPMAP_NEAREST:case ls.LINEAR_MIPMAP_LINEAR:return t.Texture.TRILINEAR_SAMPLINGMODE;case ls.NEAREST:case ls.NEAREST_MIPMAP_NEAREST:return t.Texture.NEAREST_SAMPLINGMODE;default:return t.Texture.BILINEAR_SAMPLINGMODE}}static GetBufferFromBufferView(e,t,n,o,s){n=t.byteOffset+n;const r=e.loadedBufferViews[t.buffer];if(n+o>r.byteLength)throw new Error("Buffer access is out of range");const i=r.buffer;switch(n+=r.byteOffset,s){case ss.BYTE:return new Int8Array(i,n,o);case ss.UNSIGNED_BYTE:return new Uint8Array(i,n,o);case ss.SHORT:return new Int16Array(i,n,o);case ss.UNSIGNED_SHORT:return new Uint16Array(i,n,o);default:return new Float32Array(i,n,o)}}static GetBufferFromAccessor(e,t){const n=e.bufferViews[t.bufferView],o=t.count*ps.GetByteStrideFromType(t);return ps.GetBufferFromBufferView(e,n,t.byteOffset,o,t.componentType)}static DecodeBufferToText(e){let t="";const n=e.byteLength;for(let o=0;o<n;++o)t+=String.fromCharCode(e[o]);return t}static GetDefaultMaterial(e){if(!ps._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"},o={attributes:["position"],uniforms:["worldView","projection","u_emission"],samplers:new Array,needAlphaBlending:!1};ps._DefaultMaterial=new t.ShaderMaterial("GLTFDefaultMaterial",e,n,o),ps._DefaultMaterial.setColor4("u_emission",new t.Color4(.5,.5,.5,1))}return ps._DefaultMaterial}}ps._DefaultMaterial=null,function(e){e[e.IDENTIFIER=1]="IDENTIFIER",e[e.UNKNOWN=2]="UNKNOWN",e[e.END_OF_INPUT=3]="END_OF_INPUT"}(hs||(hs={}));class ms{constructor(e){this._pos=0,this.currentToken=hs.UNKNOWN,this.currentIdentifier="",this.currentString="",this.isLetterOrDigitPattern=/^[a-zA-Z0-9]+$/,this._toParse=e,this._maxPos=e.length}getNextToken(){if(this.isEnd())return hs.END_OF_INPUT;if(this.currentString=this.read(),this.currentToken=hs.UNKNOWN,"_"===this.currentString||this.isLetterOrDigitPattern.test(this.currentString))for(this.currentToken=hs.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 _s=["MODEL","VIEW","PROJECTION","MODELVIEW","MODELVIEWPROJECTION","JOINTMATRIX"],gs=["world","view","projection","worldView","worldViewProjection","mBones"],vs=["translation","rotation","scale"],ys=["position","rotationQuaternion","scaling"],bs=(e,t,n)=>{for(const o in e){const s=e[o];n[t][o]=s}},xs=e=>{if(e)for(let t=0;t<e.length/2;t++)e[2*t+1]=1-e[2*t+1]},Ts=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},As=e=>{let n;if(e.translation||e.rotation||e.scale){const o=t.Vector3.FromArray(e.scale||[1,1,1]),s=t.Quaternion.FromArray(e.rotation||[0,0,0,1]),r=t.Vector3.FromArray(e.translation||[0,0,0]);n=t.Matrix.Compose(o,s,r)}else n=t.Matrix.FromArray(e.matrix);return n},Ms=(e,n,o,s)=>{for(let e=0;e<s.bones.length;e++)if(s.bones[e].name===o)return s.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===o){const o=As(a),r=new t.Bone(a.name||"",s,Ms(e,n,a.jointName,s),o);return r.id=i,r}}}return null},ws=(e,t)=>{for(let n=0;n<e.length;n++){const o=e[n];for(let e=0;e<o.node.children.length;e++)if(o.node.children[e]===t)return o.bone}return null},Ss=(e,t)=>{const n=e.nodes;let o=n[t];if(o)return{node:o,id:t};for(const e in n)if(o=n[e],o.jointName===t)return{node:o,id:e};return null},Cs=(e,t)=>{for(let n=0;n<e.jointNames.length;n++)if(e.jointNames[n]===t)return!0;return!1},Rs=(e,n,o,s,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=s),!n.babylonNode)return r;const i=[];let a=null;const l=[],u=[],c=[],d=[];for(let n=0;n<o.length;n++){const s=o[n],r=e.meshes[s];if(r)for(let n=0;n<r.primitives.length;n++){const o=new t.VertexData,s=r.primitives[n];s.mode;const h=s.attributes;let f,p;for(const n in h)if(f=e.accessors[h[n]],p=ps.GetBufferFromAccessor(e,f),"NORMAL"===n)o.normals=new Float32Array(p.length),o.normals.set(p);else if("POSITION"===n){if(ts.HomogeneousCoordinates){o.positions=new Float32Array(p.length-p.length/4);for(let e=0;e<p.length;e+=4)o.positions[e]=p[e],o.positions[e+1]=p[e+1],o.positions[e+2]=p[e+2]}else o.positions=new Float32Array(p.length),o.positions.set(p);u.push(o.positions.length)}else if(-1!==n.indexOf("TEXCOORD_")){const e=Number(n.split("_")[1]),s=t.VertexBuffer.UVKind+(0===e?"":e+1),r=new Float32Array(p.length);r.set(p),xs(r),o.set(r,s)}else"JOINT"===n?(o.matricesIndices=new Float32Array(p.length),o.matricesIndices.set(p)):"WEIGHT"===n?(o.matricesWeights=new Float32Array(p.length),o.matricesWeights.set(p)):"COLOR"===n&&(o.colors=new Float32Array(p.length),o.colors.set(p));if(f=e.accessors[s.indices],f)p=ps.GetBufferFromAccessor(e,f),o.indices=new Int32Array(p.length),o.indices.set(p),d.push(o.indices.length);else{const e=[];for(let t=0;t<o.positions.length/3;t++)e.push(t);o.indices=new Int32Array(e),d.push(o.indices.length)}a?a.merge(o):a=o;const m=e.scene.getMaterialById(s.material);i.push(null===m?ps.GetDefaultMaterial(e.scene):m),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"+s,e.scene),h.subMaterials=i):h=new t.StandardMaterial("multimat"+s,e.scene),1===i.length&&(h=i[0]),h._parentContainer=e.assetContainer,r.material||(r.material=h),new t.Geometry(s,e.scene,a,!1,r),r.computeWorldMatrix(!0),e.scene._blockEntityCollection=!1,r.subMeshes=[];let f=0;for(let n=0;n<o.length;n++){const s=o[n],i=e.meshes[s];if(i)for(let e=0;e<i.primitives.length;e++)i.primitives[e].mode,t.SubMesh.AddToMesh(f,l[f],u[f],c[f],d[f],r,r,!0),f++}return r},Is=(e,t,n,o)=>{e.position&&(e.position=t),(e.rotationQuaternion||e.rotation)&&(e.rotationQuaternion=n),e.scaling&&(e.scaling=o)},Os=(e,n,o)=>{let s=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=Rs(e,n,n.meshes,o,n.babylonNode);i.skeleton=e.scene.getLastSkeletonById(n.skin),null===i.skeleton&&(i.skeleton=((e,n,o,s)=>{if(s||(s=new t.Skeleton(n.name||"","",e.scene)),!n.babylonSkeleton)return s;const r=[],i=[];((e,n,o,s)=>{for(const r in e.nodes){const i=e.nodes[r],a=r;if(!i.jointName||Cs(o,i.jointName))continue;const l=As(i),u=new t.Bone(i.name||"",n,null,l);u.id=a,s.push({bone:u,node:i,id:a})}for(let e=0;e<s.length;e++){const t=s[e],n=t.node.children;for(let e=0;e<n.length;e++){let o=null;for(let t=0;t<s.length;t++)if(s[t].id===n[e]){o=s[t];break}o&&(o.bone._parent=t.bone,t.bone.children.push(o.bone))}}})(e,s,n,r),s.bones=[];for(let o=0;o<n.jointNames.length;o++){const a=Ss(e,n.jointNames[o]);if(!a)continue;const l=a.node;if(!l){t.Tools.Warn("Joint named "+n.jointNames[o]+" does not exist");continue}const u=a.id,c=e.scene.getBoneById(u);if(c){s.bones.push(c);continue}let d,h=null;for(let r=0;r<o;r++){const o=Ss(e,n.jointNames[r]);if(!o)continue;const i=o.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=Ms(e,n,n.jointNames[r],s),d=!0;break}if(d)break}}const f=As(l);!h&&r.length>0&&(h=ws(r,u),h&&-1===i.indexOf(h)&&i.push(h)),new t.Bone(l.jointName||"",s,h,f).id=u}const a=s.bones;s.bones=[];for(let t=0;t<n.jointNames.length;t++){const o=Ss(e,n.jointNames[t]);if(o)for(let e=0;e<a.length;e++)if(a[e].id===o.id){s.bones.push(a[e]);break}}s.prepare();for(let e=0;e<i.length;e++)s.bones.push(i[e]);return s})(e,r,0,r.babylonSkeleton),r.babylonSkeleton||(r.babylonSkeleton=i.skeleton)),s=i}}else if(n.meshes)s=Rs(e,n,n.mesh?[n.mesh]:n.meshes,o,n.babylonNode);else if(!n.light||n.babylonNode||e.importOnlyMeshes){if(n.camera&&!n.babylonNode&&!e.importOnlyMeshes){const o=e.cameras[n.camera];if(o){if(e.scene._blockEntityCollection=!!e.assetContainer,"orthographic"===o.type){const o=new t.FreeCamera(n.camera,t.Vector3.Zero(),e.scene,!1);o.name=n.name||"",o.mode=t.Camera.ORTHOGRAPHIC_CAMERA,o.attachControl(),s=o,o._parentContainer=e.assetContainer}else if("perspective"===o.type){const r=o[o.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),s=i,i._parentContainer=e.assetContainer}e.scene._blockEntityCollection=!1}}}else{const o=e.lights[n.light];if(o)if("ambient"===o.type){const r=o[o.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)),s=i}else if("directional"===o.type){const r=o[o.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)),s=i}else if("point"===o.type){const r=o[o.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)),s=i}else if("spot"===o.type){const r=o[o.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),s=i}}if(!n.jointName){if(n.babylonNode)return n.babylonNode;if(null===s){e.scene._blockEntityCollection=!!e.assetContainer;const o=new t.Mesh(n.name||"",e.scene);o._parentContainer=e.assetContainer,e.scene._blockEntityCollection=!1,n.babylonNode=o,s=o}}if(null!==s){if(n.matrix&&s instanceof t.Mesh)((e,n)=>{if(n.matrix){const o=new t.Vector3(0,0,0),s=new t.Quaternion,r=new t.Vector3(0,0,0);t.Matrix.FromArray(n.matrix).decompose(r,s,o),Is(e,o,s,r)}else n.translation&&n.rotation&&n.scale&&Is(e,t.Vector3.FromArray(n.translation),t.Quaternion.FromArray(n.rotation),t.Vector3.FromArray(n.scale));e.computeWorldMatrix(!0)})(s,n);else{const e=n.translation||[0,0,0],o=n.rotation||[0,0,0,1],r=n.scale||[1,1,1];Is(s,t.Vector3.FromArray(e),t.Quaternion.FromArray(o),t.Vector3.FromArray(r))}s.updateCache(!0),n.babylonNode=s}return s},Fs=(e,t,n,o=!1)=>{const s=e.nodes[t];let r=null;if(o=!(e.importOnlyMeshes&&!o&&e.importMeshesNames)||-1!==e.importMeshesNames.indexOf(s.name||"")||0===e.importMeshesNames.length,!s.jointName&&o&&(r=Os(e,s,t),null!==r&&(r.id=t,r.parent=n)),s.children)for(let t=0;t<s.children.length;t++)Fs(e,s.children[t],r,o)},Es=e=>{let n=e.currentScene;if(n)for(let t=0;t<n.nodes.length;t++)Fs(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++)Fs(e,n.nodes[t],null)}(e=>{for(const n in e.animations){const o=e.animations[n];if(!o.channels||!o.samplers)continue;let s=null;for(let r=0;r<o.channels.length;r++){const i=o.channels[r],a=o.samplers[i.sampler];if(!a)continue;let l,u;o.parameters?(l=o.parameters[a.input],u=o.parameters[a.output]):(l=a.input,u=a.output);const c=ps.GetBufferFromAccessor(e,e.accessors[l]),d=ps.GetBufferFromAccessor(e,e.accessors[u]),h=i.target.id;let f=e.scene.getNodeById(h);if(null===f&&(f=e.scene.getNodeByName(h)),null===f){t.Tools.Warn("Creating animation named "+n+". But cannot find node named "+h+" to attach to");continue}const p=f instanceof t.Bone;let m=i.target.path;const _=vs.indexOf(m);-1!==_&&(m=ys[_]);let g=t.Animation.ANIMATIONTYPE_MATRIX;p||("rotationQuaternion"===m?(g=t.Animation.ANIMATIONTYPE_QUATERNION,f.rotationQuaternion=new t.Quaternion):g=t.Animation.ANIMATIONTYPE_VECTOR3);let v=null;const y=[];let b=0,x=!1;p&&s&&s.getKeys().length===c.length&&(v=s,x=!0),x||(e.scene._blockEntityCollection=!!e.assetContainer,v=new t.Animation(n,p?"_matrix":m,1,g,t.Animation.ANIMATIONLOOPMODE_CYCLE),e.scene._blockEntityCollection=!1);for(let e=0;e<c.length;e++){let n;if("rotationQuaternion"===m?(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),p){const o=f;let r=t.Vector3.Zero(),i=new t.Quaternion,a=t.Vector3.Zero(),l=o.getBaseMatrix();x&&s&&(l=s.getKeys()[e].value),l.decompose(a,i,r),"position"===m?r=n:"rotationQuaternion"===m?i=n:a=n,n=t.Matrix.Compose(a,i,r)}x?s&&(s.getKeys()[e].value=n):y.push({frame:c[e],value:n})}!x&&v&&(v.setKeys(y),f.animations.push(v)),s=v,e.scene.stopAnimation(f),e.scene.beginAnimation(f,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)}},Ls=(e,t,n)=>{for(const o in t.uniforms){const s=t.uniforms[o],r=t.parameters[s];if(e.currentIdentifier===o&&r.semantic&&!r.source&&!r.node){const e=_s.indexOf(r.semantic);if(-1!==e)return delete n[o],gs[e]}}return e.currentIdentifier},Ns=e=>{for(const t in e.materials)Ps.LoadMaterialAsync(e,t,()=>{},()=>{})};class ks{static CreateRuntime(e,t,n){const o={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&&bs(e.extensions,"extensions",o),e.extensionsUsed&&bs(e.extensionsUsed,"extensionsUsed",o),e.buffers&&((e,t)=>{for(const n in e){const o=e[n];t.buffers[n]=o,t.buffersCount++}})(e.buffers,o),e.bufferViews&&bs(e.bufferViews,"bufferViews",o),e.accessors&&bs(e.accessors,"accessors",o),e.meshes&&bs(e.meshes,"meshes",o),e.lights&&bs(e.lights,"lights",o),e.cameras&&bs(e.cameras,"cameras",o),e.nodes&&bs(e.nodes,"nodes",o),e.images&&bs(e.images,"images",o),e.textures&&bs(e.textures,"textures",o),e.shaders&&((e,t)=>{for(const n in e){const o=e[n];t.shaders[n]=o,t.shaderscount++}})(e.shaders,o),e.programs&&bs(e.programs,"programs",o),e.samplers&&bs(e.samplers,"samplers",o),e.techniques&&bs(e.techniques,"techniques",o),e.materials&&bs(e.materials,"materials",o),e.animations&&bs(e.animations,"animations",o),e.skins&&bs(e.skins,"skins",o),e.scenes&&(o.scenes=e.scenes),e.scene&&e.scenes&&(o.currentScene=e.scenes[e.scene]),o}static LoadBufferAsync(e,n,o,s,r){const i=e.buffers[n];t.Tools.IsBase64(i.uri)?setTimeout(()=>o(new Uint8Array(t.Tools.DecodeBase64(i.uri)))):t.Tools.LoadFile(e.rootUrl+i.uri,e=>o(new Uint8Array(e)),r,void 0,!0,e=>{e&&s(e.status+" "+e.statusText)})}static LoadTextureBufferAsync(e,n,o,s){const r=e.textures[n];if(!r||!r.source)return void s("");if(r.babylonTexture)return void o(null);const i=e.images[r.source];t.Tools.IsBase64(i.uri)?setTimeout(()=>o(new Uint8Array(t.Tools.DecodeBase64(i.uri)))):t.Tools.LoadFile(e.rootUrl+i.uri,e=>o(new Uint8Array(e)),void 0,void 0,!0,e=>{e&&s(e.status+" "+e.statusText)})}static CreateTextureAsync(e,n,o,s){const r=e.textures[n];if(r.babylonTexture)return void s(r.babylonTexture);const i=e.samplers[r.sampler],a=i.minFilter===ls.NEAREST_MIPMAP_NEAREST||i.minFilter===ls.NEAREST_MIPMAP_LINEAR||i.minFilter===ls.LINEAR_MIPMAP_NEAREST||i.minFilter===ls.LINEAR_MIPMAP_LINEAR,l=t.Texture.BILINEAR_SAMPLINGMODE,u=null==o?new Blob:new Blob([t.GetBlobBufferSource(o)]),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=ps.GetWrapMode(i.wrapS)),void 0!==i.wrapT&&(h.wrapV=ps.GetWrapMode(i.wrapT)),h.name=n,r.babylonTexture=h,s(h)}static LoadShaderStringAsync(e,n,o,s){const r=e.shaders[n];if(t.Tools.IsBase64(r.uri)){const e=atob(r.uri.split(",")[1]);o&&o(e)}else t.Tools.LoadFile(e.rootUrl+r.uri,o,void 0,void 0,!1,e=>{e&&s&&s(e.status+" "+e.statusText)})}static LoadMaterialAsync(e,n,o,s){const r=e.materials[n];if(!r.technique)return void(s&&s("No technique found."));const i=e.techniques[r.technique];if(!i){e.scene._blockEntityCollection=!!e.assetContainer;const s=new t.StandardMaterial(n,e.scene);return s._parentContainer=e.assetContainer,e.scene._blockEntityCollection=!1,s.diffuseColor=new t.Color3(.5,.5,.5),s.sideOrientation=t.Material.CounterClockWiseSideOrientation,void o(s)}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 f=new ms(u),p=new ms(c),m={},_=[],g=[],v=[];for(const e in i.uniforms){const t=i.uniforms[e],n=i.parameters[t];if(m[e]=n,!n.semantic||n.node||n.source)n.type===is.SAMPLER_2D?v.push(e):_.push(e);else{const t=_s.indexOf(n.semantic);-1!==t?(_.push(gs[t]),delete m[e]):_.push(e)}}for(const e in i.attributes){const t=i.attributes[e],n=i.parameters[t];if(n.semantic){const e=Ts(n);e&&g.push(e)}}for(;!f.isEnd()&&f.getNextToken();){if(f.currentToken!==hs.IDENTIFIER){d+=f.currentString;continue}let e=!1;for(const t in i.attributes){const n=i.attributes[t],o=i.parameters[n];if(f.currentIdentifier===t&&o.semantic){d+=Ts(o),e=!0;break}}e||(d+=Ls(f,i,m))}for(;!p.isEnd()&&p.getNextToken();)p.currentToken===hs.IDENTIFIER?h+=Ls(p,i,m):h+=p.currentString;const y={vertex:a.vertexShader+n,fragment:a.fragmentShader+n},b={attributes:g,uniforms:_,samplers:v,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,y,b);if(x.onError=((e,t,n)=>(o,s)=>{t.dispose(!0),n("Cannot compile program named "+e.name+". Error: "+s+". Default material will be applied")})(a,x,s),x.onCompiled=((e,t,n,o,s,r)=>i=>{((e,t,n,o,s)=>{const r=o.values||n.parameters,i=n.uniforms;for(const n in s){const a=s[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 s[e])};l===is.SAMPLER_2D?Ps.LoadTextureAsync(e,o.values?u:a.value,c(n),()=>c(null)):a.value&&ps.SetUniform(t,n,o.values?u:a.value,l)&&delete s[n]}})(e,t,n,o,s),t.onBind=i=>{((e,t,n,o,s,r,i)=>{const a=r.values||s.parameters;for(const i in n){const l=n[i],u=l.type;if(u===is.FLOAT_MAT2||u===is.FLOAT_MAT3||u===is.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;ps.SetMatrix(t.scene,e,l,i,o.getEffect())}}else ps.SetMatrix(t.scene,e,l,i,o.getEffect());else{const e=a[s.uniforms[i]];if(!e)continue;if(u===is.SAMPLER_2D){const n=t.textures[r.values?e:l.value].babylonTexture;if(null==n)continue;o.getEffect().setTexture(i,n)}else ps.SetUniform(o.getEffect(),i,e,u)}}i(o)})(i,e,s,t,n,o,r)}})(e,x,i,r,m,o),x.sideOrientation=t.Material.CounterClockWiseSideOrientation,l&&l.functions){const e=l.functions;e.cullFace&&e.cullFace[0]!==cs.BACK&&(x.backFaceCulling=!1);const n=e.blendFuncSeparate;n&&(n[0]===ds.SRC_ALPHA&&n[1]===ds.ONE_MINUS_SRC_ALPHA&&n[2]===ds.ONE&&n[3]===ds.ONE?x.alphaMode=t.Constants.ALPHA_COMBINE:n[0]===ds.ONE&&n[1]===ds.ONE&&n[2]===ds.ZERO&&n[3]===ds.ONE?x.alphaMode=t.Constants.ALPHA_ONEONE:n[0]===ds.SRC_ALPHA&&n[1]===ds.ONE&&n[2]===ds.ZERO&&n[3]===ds.ONE?x.alphaMode=t.Constants.ALPHA_ADD:n[0]===ds.ZERO&&n[1]===ds.ONE_MINUS_SRC_COLOR&&n[2]===ds.ONE&&n[3]===ds.ONE?x.alphaMode=t.Constants.ALPHA_SUBTRACT:n[0]===ds.DST_COLOR&&n[1]===ds.ZERO&&n[2]===ds.ONE&&n[3]===ds.ONE?x.alphaMode=t.Constants.ALPHA_MULTIPLY:n[0]===ds.SRC_ALPHA&&n[1]===ds.ONE_MINUS_SRC_COLOR&&n[2]===ds.ONE&&n[3]===ds.ONE&&(x.alphaMode=t.Constants.ALPHA_MAXIMIZED))}}}let Bs=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,o,s,r,i,a,l){return n.useRightHandedSystem=!0,Ps.LoadRuntimeAsync(n,o,s,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 o=[],s=[];for(const e in n.nodes){const s=n.nodes[e];s.babylonNode instanceof t.AbstractMesh&&o.push(s.babylonNode)}for(const e in n.skins){const o=n.skins[e];o.babylonSkeleton instanceof t.Skeleton&&s.push(o.babylonSkeleton)}this._loadBuffersAsync(n,()=>{this._loadShadersAsync(n,()=>{Ns(n),Es(n),!ts.IncrementalLoading&&i&&i(o,s)})}),ts.IncrementalLoading&&i&&i(o,s)},l),!0}importMeshAsync(e,t,n,o,s,r){return new Promise((i,a)=>{this._importMeshAsync(e,t,o,s,n,(e,t)=>{i({meshes:e,particleSystems:[],skeletons:t,animationGroups:[],lights:[],transformNodes:[],geometries:[],spriteManagers:[]})},r,e=>{a(new Error(e))})})}_loadAsync(e,t,n,o,s,r){e.useRightHandedSystem=!0,Ps.LoadRuntimeAsync(e,t,n,e=>{Ps.LoadRuntimeExtensionsAsync(e,()=>{this._createNodes(e),this._loadBuffersAsync(e,()=>{this._loadShadersAsync(e,()=>{Ns(e),Es(e),ts.IncrementalLoading||o()})}),ts.IncrementalLoading&&o()},r)},r)}loadAsync(e,t,n,o){return b(this,void 0,void 0,function*(){return yield new Promise((s,r)=>{this._loadAsync(e,t,n,()=>{s()},o,e=>{r(new Error(e))})})})}_loadShadersAsync(e,n){let o=!1;const s=(o,s)=>{Ps.LoadShaderStringAsync(e,o,r=>{r instanceof ArrayBuffer||(e.loadedShaderCount++,r&&(t.Effect.ShadersStore[o+(s.type===rs.VERTEX?"VertexShader":"PixelShader")]=r),e.loadedShaderCount===e.shaderscount&&n())},()=>{t.Tools.Error("Error when loading shader program named "+o+" located at "+s.uri)})};for(const n in e.shaders){o=!0;const r=e.shaders[n];r?s.bind(this,n,r)():t.Tools.Error("No shader named: "+n)}o||n()}_loadBuffersAsync(e,n){let o=!1;const s=(o,s)=>{Ps.LoadBufferAsync(e,o,r=>{e.loadedBufferCount++,r&&(r.byteLength!=e.buffers[o].byteLength&&t.Tools.Error("Buffer named "+o+" is length "+r.byteLength+". Expected: "+s.byteLength),e.loadedBufferViews[o]=r),e.loadedBufferCount===e.buffersCount&&n()},()=>{t.Tools.Error("Error when loading buffer named "+o+" located at "+s.uri)})};for(const n in e.buffers){o=!0;const r=e.buffers[n];r?s.bind(this,n,r)():t.Tools.Error("No buffer named: "+n)}o||n()}_createNodes(e){let t=e.currentScene;if(t)for(let n=0;n<t.nodes.length;n++)Fs(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++)Fs(e,t.nodes[n],null)}}};Bs.Extensions={};class Ps{constructor(e){this._name=e}get name(){return this._name}loadRuntimeAsync(e,t,n,o,s){return!1}loadRuntimeExtensionsAsync(e,t,n){return!1}loadBufferAsync(e,t,n,o,s){return!1}loadTextureBufferAsync(e,t,n,o){return!1}createTextureAsync(e,t,n,o,s){return!1}loadShaderStringAsync(e,t,n,o){return!1}loadMaterialAsync(e,t,n,o){return!1}static LoadRuntimeAsync(e,t,n,o,s){Ps._ApplyExtensions(r=>r.loadRuntimeAsync(e,t,n,o,s),()=>{setTimeout(()=>{o&&o(ks.CreateRuntime(t.json,e,n))})})}static LoadRuntimeExtensionsAsync(e,t,n){Ps._ApplyExtensions(o=>o.loadRuntimeExtensionsAsync(e,t,n),()=>{setTimeout(()=>{t()})})}static LoadBufferAsync(e,t,n,o,s){Ps._ApplyExtensions(r=>r.loadBufferAsync(e,t,n,o,s),()=>{ks.LoadBufferAsync(e,t,n,o,s)})}static LoadTextureAsync(e,t,n,o){Ps._LoadTextureBufferAsync(e,t,s=>{s&&Ps._CreateTextureAsync(e,t,s,n,o)},o)}static LoadShaderStringAsync(e,t,n,o){Ps._ApplyExtensions(s=>s.loadShaderStringAsync(e,t,n,o),()=>{ks.LoadShaderStringAsync(e,t,n,o)})}static LoadMaterialAsync(e,t,n,o){Ps._ApplyExtensions(s=>s.loadMaterialAsync(e,t,n,o),()=>{ks.LoadMaterialAsync(e,t,n,o)})}static _LoadTextureBufferAsync(e,t,n,o){Ps._ApplyExtensions(s=>s.loadTextureBufferAsync(e,t,n,o),()=>{ks.LoadTextureBufferAsync(e,t,n,o)})}static _CreateTextureAsync(e,t,n,o,s){Ps._ApplyExtensions(r=>r.createTextureAsync(e,t,n,o,s),()=>{ks.CreateTextureAsync(e,t,n,o)})}static _ApplyExtensions(e,t){for(const t in Bs.Extensions)if(e(Bs.Extensions[t]))return;t()}}let Ds=!1;function Vs(){Ds||(Ds=!0,ts._CreateGLTF1Loader=()=>new Bs)}class Gs extends Ps{constructor(){super("KHR_binary_glTF")}loadRuntimeAsync(e,t,n,o){const s=t.json.extensionsUsed;return!(!s||-1===s.indexOf(this.name)||!t.bin||(this._bin=t.bin,o(ks.CreateRuntime(t.json,e,n)),0))}loadBufferAsync(e,t,n,o){return-1!==e.extensionsUsed.indexOf(this.name)&&"binary_glTF"===t&&(this._bin.readAsync(0,this._bin.byteLength).then(n,e=>o(e.message)),!0)}loadTextureBufferAsync(e,t,n){const o=e.textures[t],s=e.images[o.source];if(!s.extensions||!(this.name in s.extensions))return!1;const r=s.extensions[this.name],i=e.bufferViews[r.bufferView];return n(ps.GetBufferFromBufferView(e,i,0,i.byteLength,ss.UNSIGNED_BYTE)),!0}loadShaderStringAsync(e,t,n){const o=e.shaders[t];if(!o.extensions||!(this.name in o.extensions))return!1;const s=o.extensions[this.name],r=e.bufferViews[s.bufferView],i=ps.GetBufferFromBufferView(e,r,0,r.byteLength,ss.UNSIGNED_BYTE);return setTimeout(()=>{const e=ps.DecodeBufferToText(i);n(e)}),!0}}let $s=!1;function Us(){$s||($s=!0,Bs.RegisterExtension(new Gs))}Vs(),os(),Us();class Hs extends Ps{constructor(){super("KHR_materials_common")}loadRuntimeExtensionsAsync(e){if(!e.extensions)return!1;const n=e.extensions[this.name];if(!n)return!1;const o=n.lights;if(o)for(const n in o){const s=o[n];switch(s.type){case"ambient":{const n=new t.HemisphericLight(s.name,new t.Vector3(0,1,0),e.scene),o=s.ambient;o&&(n.diffuse=t.Color3.FromArray(o.color||[1,1,1]));break}case"point":{const n=new t.PointLight(s.name,new t.Vector3(10,10,10),e.scene),o=s.point;o&&(n.diffuse=t.Color3.FromArray(o.color||[1,1,1]));break}case"directional":{const n=new t.DirectionalLight(s.name,new t.Vector3(0,-1,0),e.scene),o=s.directional;o&&(n.diffuse=t.Color3.FromArray(o.color||[1,1,1]));break}case"spot":{const n=s.spot;n&&(new t.SpotLight(s.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 "'+s.type+"” not supported")}}return!1}loadMaterialAsync(e,n,o,s){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",s):a.ambientColor=t.Color3.FromArray(i.values.ambient||[0,0,0]),"string"==typeof i.values.diffuse?this._loadTexture(e,i.values.diffuse,a,"diffuseTexture",s):a.diffuseColor=t.Color3.FromArray(i.values.diffuse||[0,0,0]),"string"==typeof i.values.emission?this._loadTexture(e,i.values.emission,a,"emissiveTexture",s):a.emissiveColor=t.Color3.FromArray(i.values.emission||[0,0,0]),"string"==typeof i.values.specular?this._loadTexture(e,i.values.specular,a,"specularTexture",s):a.specularColor=t.Color3.FromArray(i.values.specular||[0,0,0]),!0}_loadTexture(e,t,n,o,s){ks.LoadTextureBufferAsync(e,t,s=>{ks.CreateTextureAsync(e,t,s,e=>n[o]=e)},s)}}let Ks=!1;function Ws(){Ks||(Ks=!0,Bs.RegisterExtension(new Hs))}Ws();var qs={__proto__:null,get EBlendingFunction(){return ds},get EComponentType(){return ss},get ECullingType(){return cs},get EParameterType(){return is},get EShaderType(){return rs},get ETextureFilterType(){return ls},get ETextureFormat(){return us},get ETextureWrapMode(){return as},GLTFBinaryExtension:Gs,GLTFLoader:Bs,GLTFLoaderBase:ks,GLTFLoaderExtension:Ps,GLTFMaterialsCommonExtension:Hs,GLTFUtils:ps,RegisterGLTF1Loader:Vs,RegisterGLTFBinaryExtension:Us,RegisterGLTFMaterialsCommonExtension:Ws};const zs=new Map,js=zs;function Xs(e,n,o){Ys(e)&&t.Logger.Warn(`Extension with the name '${e}' already exists`),zs.set(e,{isGLTFExtension:n,factory:o})}function Ys(e){return zs.delete(e)}const Qs=[{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 Zs{constructor(e,t){this._gltf=e,this._infoTree=t}convert(e){let t,n=this._gltf,o=this._infoTree;if(!e.startsWith("/"))throw new Error("Path must start with a /");const s=e.split("/");if(s.shift(),s[s.length-1].includes(".length")){const e=s[s.length-1].split(".");s.pop(),s.push(...e)}let r=!1;for(const i of s)if("length"===i){if(!o.length)throw o.__array__?new Error(`Path ${e} is invalid - no length accessor`):new Error(`Path ${e} is invalid`);o=o.length,void 0!==n&&(t=n)}else{if(o.__ignoreObjectTree__&&(r=!0),o.__array__)o=o.__array__;else if(o=o[i],!o)throw new Error(`Path ${e} is invalid`);if(o.__passThroughTarget__)r=!0;else if(r){const e=/^\d+$/.test(i)?parseInt(i,10):NaN;if(!isNaN(e)&&"function"==typeof o.get){const t=o;o=Object.assign({},t),o.get=(n,o,...s)=>t.get(n,e,...s),"function"==typeof t.set&&(o.set=(n,o,s,...r)=>t.set(n,o,e,...r)),"function"==typeof t.getTarget&&(o.getTarget=(n,o,...s)=>t.getTarget(n,e,...s))}}else if(void 0===n){if(!Qs.find(t=>t.regex.test(e)))throw new Error(`Path ${e} is invalid`)}else n=null==n?void 0:n[i];o.__target__&&void 0!==n&&(t=n)}return{object:t,info:o}}}function Js(e,n){return{type:"FlowGraphInteger",get:n=>{const o=e(n);return void 0===o?void 0:t.FlowGraphInteger.FromValue(o)},getTarget:n,getPropertyName:[()=>"length"]}}const er={length:Js(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,o;return null===(o=null===(n=t._babylonTransformNode)||void 0===n?void 0:n.rotationQuaternion)||void 0===o?void 0:o.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:Js(e=>{const t=rr(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=rr(e);if(n&&void 0!==t&&t>=0&&t<n.mtm.numTargets)return ir(n.mtm.getTarget(t).influence)},set:(e,t,n)=>{var o;const s="number"==typeof e?e:"number"==typeof(null==e?void 0:e.value)?e.value:e,r=rr(t);if(!(!r||void 0===n||n<0||n>=r.mtm.numTargets))for(const e of r.meshes){const t=null===(o=e.morphTargetManager)||void 0===o?void 0:o.getTarget(n);t&&(t.influence=s)}},getTarget:(e,t)=>{const n=rr(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=rr(e);if(!t)return[];const n=[];for(let e=0;e<t.mtm.numTargets;e++)n.push(ir(t.mtm.getTarget(e).influence));return n},getTarget:e=>null==e?void 0:e._babylonTransformNode,getPropertyName:[()=>"influence"]},matrix:{type:"Matrix",get:e=>{var n,o,s;return t.Matrix.Compose(null===(n=e._babylonTransformNode)||void 0===n?void 0:n.scaling,null===(o=e._babylonTransformNode)||void 0===o?void 0:o.rotationQuaternion,null===(s=e._babylonTransformNode)||void 0===s?void 0:s.position)},getTarget:e=>e._babylonTransformNode,isReadOnly:!0},globalMatrix:{type:"Matrix",get:e=>{var n,o,s,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===(s=null===(o=e._babylonTransformNode)||void 0===o?void 0:o.rotationQuaternion)||void 0===s?void 0:s._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:Js(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,o;return null===(o=null===(n=e._babylonTransformNode)||void 0===n?void 0:n.getChildren(e=>e instanceof t.SpotLight,!0)[0])||void 0===o?void 0:o.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 o=n._babylonTransformNode.getChildren(e=>e instanceof t.SpotLight,!0)[0];o&&(o.intensity=e)}}},color:{type:"Color3",get:e=>{var n,o;return null===(o=null===(n=e._babylonTransformNode)||void 0===n?void 0:n.getChildren(e=>e instanceof t.SpotLight,!0)[0])||void 0===o?void 0:o.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 o=n._babylonTransformNode.getChildren(e=>e instanceof t.SpotLight,!0)[0];o&&(o.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)}}}}}},tr={length:Js(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}},nr={length:Js(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:Js(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:Js(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 or(e,t,n,o){const s=sr(e);return o?s[n][o]:s[n]}function sr(e,n,o){var s,r,i;return null===(i=null===(s=e._data)||void 0===s?void 0:s[null!==(r=null==o?void 0:o.fillMode)&&void 0!==r?r:t.Constants.MATERIAL_TriangleFillMode])||void 0===i?void 0:i.babylonMaterial}function rr(e){var t,n,o,s;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 o=e._primitiveBabylonMeshes;if(o)for(const e of o){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!==(o=e.morphTargetManager)&&void 0!==o?o:null===(s=e.sourceMesh)||void 0===s?void 0:s.morphTargetManager)===i&&a.push(e);return 0===a.length&&a.push(r),{mtm:i,meshes:a}}}function ir(e){return Number.isFinite(e)?parseFloat(e.toPrecision(7)):e}function ar(e,t,n){if(!e)return;let o=e.extensions;if(!o){if(!n)return;o={},e.extensions=o}let s=o[t.extensionKey];if(!s){if(!n)return;s={},o[t.extensionKey]=s}for(const e of t.texturePath){let t=s[e];if(!t){if(!n)return;t={},s[e]=t}s=t}if(!s.extensions){if(!n)return;s.extensions={}}let r=s.extensions.KHR_texture_transform;if(!r){if(!n)return;r={},s.extensions.KHR_texture_transform=r}return r}function lr(e,n,o){return{offset:{componentsCount:2,type:"Vector2",get:(s,r,i)=>{var a,l;const u=or(s,0,e,n);if(u)return new t.Vector2(u.uOffset,u.vOffset);if(o){const e=ar(s,o,!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:sr,set:(t,s,r,i)=>{const a=or(s,0,e,n);if(a&&(a.uOffset=t.x,a.vOffset=t.y),o){const e=ar(s,o,!0);e&&(e.offset=[t.x,t.y])}},getPropertyName:[()=>`${e}${n?"."+n:""}.uOffset`,()=>`${e}${n?"."+n:""}.vOffset`]},rotation:{type:"number",get:(t,s,r)=>{var i;const a=or(t,0,e,n);if(a)return a.wAng;if(o){const e=ar(t,o,!1);return null!==(i=null==e?void 0:e.rotation)&&void 0!==i?i:0}return 0},getTarget:sr,set:(t,s,r,i)=>{const a=or(s,0,e,n);if(a&&(a.wAng=t),o){const e=ar(s,o,!0);e&&(e.rotation=t)}},getPropertyName:[()=>`${e}${n?"."+n:""}.wAng`]},scale:{componentsCount:2,type:"Vector2",get:(s,r,i)=>{var a,l;const u=or(s,0,e,n);if(u)return new t.Vector2(u.uScale,u.vScale);if(o){const e=ar(s,o,!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:sr,set:(t,s,r,i)=>{const a=or(s,0,e,n);if(a&&(a.uScale=t.x,a.vScale=t.y),o){const e=ar(s,o,!0);e&&(e.scale=[t.x,t.y])}},getPropertyName:[()=>`${e}${n?"."+n:""}.uScale`,()=>`${e}${n?"."+n:""}.vScale`]}}}const ur={scene:{__target__:!0,type:"number",get:e=>null!=e?e:0,getTarget:()=>({__gltfRoot:!0}),isReadOnly:!0,getPropertyName:[()=>"scene"]},cameras:{length:Js(e=>e.length,e=>e.map(e=>e._babylonCamera)),__array__:{__target__:!0,orthographic:{xmag:{componentsCount:2,type:"Vector2",get:e=>{var n,o,s,r;return new t.Vector2(null!==(o=null===(n=e._babylonCamera)||void 0===n?void 0:n.orthoLeft)&&void 0!==o?o:0,null!==(r=null===(s=e._babylonCamera)||void 0===s?void 0:s.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,o,s,r;return new t.Vector2(null!==(o=null===(n=e._babylonCamera)||void 0===n?void 0:n.orthoBottom)&&void 0!==o?o:0,null!==(r=null===(s=e._babylonCamera)||void 0===s?void 0:s.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:er,materials:{length:Js(e=>e.length,e=>e.map(e=>{var n,o;return null===(o=null===(n=e._data)||void 0===n?void 0:n[t.Constants.MATERIAL_TriangleFillMode])||void 0===o?void 0:o.babylonMaterial})),__array__:{__target__:!0,doubleSided:{type:"boolean",get:(e,t,n)=>{var o;return!(null===(o=sr(e,0,n))||void 0===o?void 0:o.backFaceCulling)},set:(e,t,n,o)=>{const s=sr(t,0,o);s&&(s.backFaceCulling=!e)},getTarget:(e,t,n)=>sr(e,0,n),getPropertyName:[()=>"backFaceCulling"]},alphaCutoff:{type:"number",get:(e,t,n)=>{var o;return null===(o=sr(e,0,n))||void 0===o?void 0:o.alphaCutOff},set:(e,t,n,o)=>{const s=sr(t,0,o);s&&(s.alphaCutOff=e)},getTarget:(e,t,n)=>sr(e,0,n),getPropertyName:[()=>"alphaCutOff"]},emissiveFactor:{type:"Color3",get:(e,t,n)=>sr(e,0,n).emissiveColor,set:(e,t,n,o)=>sr(t,0,o).emissiveColor.copyFrom(e),getTarget:(e,t,n)=>sr(e,0,n),getPropertyName:[()=>"emissiveColor"]},emissiveTexture:{extensions:{KHR_texture_transform:lr("emissiveTexture")}},normalTexture:{scale:{type:"number",get:(e,t,n)=>{var o;return null===(o=or(e,0,"bumpTexture"))||void 0===o?void 0:o.level},set:(e,t,n,o)=>{const s=or(t,0,"bumpTexture");s&&(s.level=e)},getTarget:(e,t,n)=>sr(e,0,n),getPropertyName:[()=>"level"]},extensions:{KHR_texture_transform:lr("bumpTexture")}},occlusionTexture:{strength:{type:"number",get:(e,t,n)=>sr(e,0,n).ambientTextureStrength,set:(e,t,n,o)=>{const s=sr(t,0,o);s&&(s.ambientTextureStrength=e)},getTarget:(e,t,n)=>sr(e,0,n),getPropertyName:[()=>"ambientTextureStrength"]},extensions:{KHR_texture_transform:lr("ambientTexture")}},pbrMetallicRoughness:{baseColorFactor:{type:"Color4",get:(e,n,o)=>{const s=sr(e,0,o);return t.Color4.FromColor3(s.albedoColor,s.alpha)},set:(e,t,n,o)=>{const s=sr(t,0,o);s.albedoColor.set(e.r,e.g,e.b),s.alpha=e.a},getTarget:(e,t,n)=>sr(e,0,n),getPropertyName:[()=>"albedoColor",()=>"alpha"]},baseColorTexture:{extensions:{KHR_texture_transform:lr("albedoTexture")}},metallicFactor:{type:"number",get:(e,t,n)=>sr(e,0,n).metallic,set:(e,t,n,o)=>{const s=sr(t,0,o);s&&(s.metallic=e)},getTarget:(e,t,n)=>sr(e,0,n),getPropertyName:[()=>"metallic"]},roughnessFactor:{type:"number",get:(e,t,n)=>sr(e,0,n).roughness,set:(e,t,n,o)=>{const s=sr(t,0,o);s&&(s.roughness=e)},getTarget:(e,t,n)=>sr(e,0,n),getPropertyName:[()=>"roughness"]},metallicRoughnessTexture:{extensions:{KHR_texture_transform:lr("metallicTexture")}}},extensions:{KHR_materials_anisotropy:{anisotropyStrength:{type:"number",get:(e,t,n)=>{var o,s;return null===(s=null===(o=sr(e,0,n))||void 0===o?void 0:o.anisotropy)||void 0===s?void 0:s.intensity},set:(e,t,n,o)=>{const s=sr(t,0,o);s&&(s.anisotropy.intensity=e)},getTarget:(e,t,n)=>sr(e,0,n),getPropertyName:[()=>"anisotropy.intensity"]},anisotropyRotation:{type:"number",get:(e,t,n)=>{var o,s;return null===(s=null===(o=sr(e,0,n))||void 0===o?void 0:o.anisotropy)||void 0===s?void 0:s.angle},set:(e,t,n,o)=>{const s=sr(t,0,o);s&&(s.anisotropy.angle=e)},getTarget:(e,t,n)=>sr(e,0,n),getPropertyName:[()=>"anisotropy.angle"]},anisotropyTexture:{extensions:{KHR_texture_transform:lr("anisotropy","texture")}}},KHR_materials_clearcoat:{clearcoatFactor:{type:"number",get:(e,t,n)=>sr(e,0,n).clearCoat.intensity,set:(e,t,n,o)=>{sr(t,0,o).clearCoat.intensity=e},getTarget:(e,t,n)=>sr(e,0,n),getPropertyName:[()=>"clearCoat.intensity"]},clearcoatRoughnessFactor:{type:"number",get:(e,t,n)=>sr(e,0,n).clearCoat.roughness,set:(e,t,n,o)=>{sr(t,0,o).clearCoat.roughness=e},getTarget:(e,t,n)=>sr(e,0,n),getPropertyName:[()=>"clearCoat.roughness"]},clearcoatTexture:{extensions:{KHR_texture_transform:lr("clearCoat","texture")}},clearcoatNormalTexture:{scale:{type:"number",get:(e,t,n)=>{var o;return null===(o=sr(e,0,n).clearCoat.bumpTexture)||void 0===o?void 0:o.level},getTarget:sr,set:(e,t,n,o)=>sr(t,0,o).clearCoat.bumpTexture.level=e},extensions:{KHR_texture_transform:lr("clearCoat","bumpTexture")}},clearcoatRoughnessTexture:{extensions:{KHR_texture_transform:lr("clearCoat","textureRoughness")}}},KHR_materials_dispersion:{dispersion:{type:"number",get:(e,t,n)=>sr(e,0,n).subSurface.dispersion,getTarget:sr,set:(e,t,n,o)=>sr(t,0,o).subSurface.dispersion=e}},KHR_materials_emissive_strength:{emissiveStrength:{type:"number",get:(e,t,n)=>sr(e,0,n).emissiveIntensity,getTarget:sr,set:(e,t,n,o)=>sr(t,0,o).emissiveIntensity=e}},KHR_materials_ior:{ior:{type:"number",get:(e,t,n)=>sr(e,0,n).indexOfRefraction,getTarget:sr,set:(e,t,n,o)=>sr(t,0,o).indexOfRefraction=e}},KHR_materials_iridescence:{iridescenceFactor:{type:"number",get:(e,t,n)=>sr(e,0,n).iridescence.intensity,getTarget:sr,set:(e,t,n,o)=>sr(t,0,o).iridescence.intensity=e},iridescenceIor:{type:"number",get:(e,t,n)=>sr(e,0,n).iridescence.indexOfRefraction,getTarget:sr,set:(e,t,n,o)=>sr(t,0,o).iridescence.indexOfRefraction=e},iridescenceTexture:{extensions:{KHR_texture_transform:lr("iridescence","texture")}},iridescenceThicknessMaximum:{type:"number",get:(e,t,n)=>sr(e,0,n).iridescence.maximumThickness,getTarget:sr,set:(e,t,n,o)=>sr(t,0,o).iridescence.maximumThickness=e},iridescenceThicknessMinimum:{type:"number",get:(e,t,n)=>sr(e,0,n).iridescence.minimumThickness,getTarget:sr,set:(e,t,n,o)=>sr(t,0,o).iridescence.minimumThickness=e},iridescenceThicknessTexture:{extensions:{KHR_texture_transform:lr("iridescence","thicknessTexture")}}},KHR_materials_sheen:{sheenColorFactor:{type:"Color3",get:(e,t,n)=>sr(e,0,n).sheen.color,getTarget:sr,set:(e,t,n,o)=>sr(t,0,o).sheen.color.copyFrom(e)},sheenColorTexture:{extensions:{KHR_texture_transform:lr("sheen","texture")}},sheenRoughnessFactor:{type:"number",get:(e,t,n)=>sr(e,0,n).sheen.intensity,getTarget:sr,set:(e,t,n,o)=>sr(t,0,o).sheen.intensity=e},sheenRoughnessTexture:{extensions:{KHR_texture_transform:lr("sheen","textureRoughness")}}},KHR_materials_specular:{specularFactor:{type:"number",get:(e,t,n)=>sr(e,0,n).metallicF0Factor,getTarget:sr,set:(e,t,n,o)=>sr(t,0,o).metallicF0Factor=e,getPropertyName:[()=>"metallicF0Factor"]},specularColorFactor:{type:"Color3",get:(e,t,n)=>sr(e,0,n).metallicReflectanceColor,getTarget:sr,set:(e,t,n,o)=>sr(t,0,o).metallicReflectanceColor.copyFrom(e),getPropertyName:[()=>"metallicReflectanceColor"]},specularTexture:{extensions:{KHR_texture_transform:lr("metallicReflectanceTexture")}},specularColorTexture:{extensions:{KHR_texture_transform:lr("reflectanceTexture")}}},KHR_materials_transmission:{transmissionFactor:{type:"number",get:(e,t,n)=>sr(e,0,n).subSurface.refractionIntensity,getTarget:sr,set:(e,t,n,o)=>sr(t,0,o).subSurface.refractionIntensity=e,getPropertyName:[()=>"subSurface.refractionIntensity"]},transmissionTexture:{extensions:{KHR_texture_transform:lr("subSurface","refractionIntensityTexture",{extensionKey:"KHR_materials_transmission",texturePath:["transmissionTexture"]})}}},KHR_materials_diffuse_transmission:{diffuseTransmissionFactor:{type:"number",get:(e,t,n)=>sr(e,0,n).subSurface.translucencyIntensity,getTarget:sr,set:(e,t,n,o)=>sr(t,0,o).subSurface.translucencyIntensity=e},diffuseTransmissionTexture:{extensions:{KHR_texture_transform:lr("subSurface","translucencyIntensityTexture",{extensionKey:"KHR_materials_diffuse_transmission",texturePath:["diffuseTransmissionTexture"]})}},diffuseTransmissionColorFactor:{type:"Color3",get:(e,t,n)=>sr(e,0,n).subSurface.translucencyColor,getTarget:sr,set:(e,t,n,o)=>{var s;return e&&(null===(s=sr(t,0,o).subSurface.translucencyColor)||void 0===s?void 0:s.copyFrom(e))}},diffuseTransmissionColorTexture:{extensions:{KHR_texture_transform:lr("subSurface","translucencyColorTexture",{extensionKey:"KHR_materials_diffuse_transmission",texturePath:["diffuseTransmissionColorTexture"]})}}},KHR_materials_volume:{attenuationColor:{type:"Color3",get:(e,t,n)=>sr(e,0,n).subSurface.tintColor,getTarget:sr,set:(e,t,n,o)=>sr(t,0,o).subSurface.tintColor.copyFrom(e)},attenuationDistance:{type:"number",get:(e,t,n)=>sr(e,0,n).subSurface.tintColorAtDistance,getTarget:sr,set:(e,t,n,o)=>sr(t,0,o).subSurface.tintColorAtDistance=e},thicknessFactor:{type:"number",get:(e,t,n)=>sr(e,0,n).subSurface.maximumThickness,getTarget:sr,set:(e,t,n,o)=>sr(t,0,o).subSurface.maximumThickness=e},thicknessTexture:{extensions:{KHR_texture_transform:lr("subSurface","thicknessTexture",{extensionKey:"KHR_materials_volume",texturePath:["thicknessTexture"]})}}}}}},extensions:{KHR_lights_punctual:{lights:{length:Js(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:Js(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:Js(e=>e.length,e=>e.map(e=>e._babylonLight))}},EXT_lights_image_based:{lights:{length:Js(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 o;n._babylonTexture&&((null===(o=n._babylonTexture.getScene())||void 0===o?void 0:o.useRightHandedSystem)||(e=t.Quaternion.Inverse(e)),t.Matrix.FromQuaternionToRef(e,n._babylonTexture.getReflectionTextureMatrix()))},getTarget:e=>e._babylonTexture}}}}},animations:tr,meshes:nr,scenes:{length:Js(e=>e.length,e=>e),__array__:{__target__:!0,nodes:{length:Js(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:Js(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:Js(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 cr(e){if(Array.isArray(e))return e.map(e=>cr(e));if(null!==e&&"object"==typeof e){const t=Object.getPrototypeOf(e);if(t!==Object.prototype&&null!==t)return e;const n={};for(const[t,o]of Object.entries(e))n[t]=cr(o);return n}return e}function dr(e,t){if(!t)return new Zs(e,ur);const n=cr(ur);return t(n),new Zs(e,n)}function hr(e){const t=e.split("/").map(e=>e.replace(/{}/g,"__array__"));let n=ur;for(const e of t)e&&(n=n[e]);if(n&&n.type&&n.get)return n}function fr(e,t){const n=e.split("/").map(e=>e.replace(/{}/g,"__array__"));let o=ur;for(const e of n)e&&(o=o[e]);o&&o.type&&o.get&&(o.interpolation=t)}function pr(e,t,n=ur){const o=e.split("/").map(e=>e.replace(/{}/g,"__array__"));let s=n;for(const e of o)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 mr=new t.Lazy(()=>Promise.resolve(BABYLON)),_r=new t.Lazy(()=>Promise.resolve().then(function(){return Fr}));class gr{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 vr(e){if(e.min&&e.max){const n=e.min,o=e.max,s=t.TmpVectors.Vector3[0].copyFromFloats(n[0],n[1],n[2]),r=t.TmpVectors.Vector3[1].copyFromFloats(o[0],o[1],o[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;s.scaleInPlace(n),r.scaleInPlace(n)}return new t.BoundingInfo(s,r)}return null}class yr{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){Xs(e,!1,t)}static UnregisterExtension(e){return Ys(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 o of n)if(e instanceof o.materialClass){t=new o.adapterClass(e);break}if(!t)throw new Error("Appropriate material adapter class not found");const o=t;this._materialAdapterCache.set(e,o),this._materialAdapters.add(o)}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,o,s,r){return b(this,arguments,void 0,function*(e,t,n,o,s,r,i=""){return yield Promise.resolve().then(()=>b(this,void 0,void 0,function*(){this._babylonScene=t,this._assetContainer=n,this._loadData(o);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(s,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,o){return b(this,arguments,void 0,function*(e,t,n,o,s=""){return this._babylonScene=e,this._loadData(t),yield this._loadAsync(n,s,null,()=>{})})}_loadAsync(n,o,s,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:")&&o?n:`${n}${t.RandomGUID()}/`,this._fileName=o,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 Lr})]).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 kr})]).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(s)u.push(this.loadSceneAsync("/nodes",{nodes:s,index:-1}));else if(null!=this._gltf.scene||this._gltf.scenes&&this._gltf.scenes[0]){const e=gr.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],o="/materials/"+e,s=t.Material.TriangleFillMode;u.push(this._loadMaterialAsync(o,n,null,s,()=>{}))}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(()=>b(this,void 0,void 0,function*(){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 yield this._extensionsOnReadyAsync(),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 o=n[0];(o.byteLength<e.bin.byteLength-3||o.byteLength>e.bin.byteLength)&&t.Logger.Warn(`Binary buffer length (${o.byteLength}) from JSON does not match chunk length (${e.bin.byteLength})`),this._bin=e.bin}else t.Logger.Warn("Unexpected BIN chunk")}}_setupData(){if(gr.Assign(this._gltf.accessors),gr.Assign(this._gltf.animations),gr.Assign(this._gltf.buffers),gr.Assign(this._gltf.bufferViews),gr.Assign(this._gltf.cameras),gr.Assign(this._gltf.images),gr.Assign(this._gltf.materials),gr.Assign(this._gltf.meshes),gr.Assign(this._gltf.nodes),gr.Assign(this._gltf.samplers),gr.Assign(this._gltf.scenes),gr.Assign(this._gltf.skins),gr.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 o=e[n.index];n.parent=void 0===o?t:this._gltf.nodes[o]}}}_loadExtensionsAsync(){return b(this,void 0,void 0,function*(){var e;const n=[];if(js.forEach((e,o)=>{var s;!1===(null===(s=this.parent.extensionOptions[o])||void 0===s?void 0:s.enabled)?e.isGLTFExtension&&this.isExtensionUsed(o)&&t.Logger.Warn(`Extension ${o} is used but has been explicitly disabled.`):e.isGLTFExtension&&!this.isExtensionUsed(o)||n.push((()=>b(this,void 0,void 0,function*(){const n=yield e.factory(this);return n.name!==o&&t.Logger.Warn(`The name of the glTF loader extension instance does not match the registered name: ${n.name} !== ${o}`),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 o={_babylonTransformNode:this._rootBabylonMesh,index:-1};switch(this._parent.coordinateSystemMode){case e.GLTFLoaderCoordinateSystemMode.AUTO:this._babylonScene.useRightHandedSystem||(o.rotation=[0,1,0,0],o.scale=[1,1,-1],yr._LoadTransform(o,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),o}loadSceneAsync(e,t){const n=this._extensionsLoadSceneAsync(e,t);if(n)return n;const o=new Array;if(this.logOpen(`${e} ${t.name||""}`),t.nodes)for(const n of t.nodes){const t=gr.Get(`${e}/nodes/${n}`,this._gltf.nodes,n);o.push(this.loadNodeAsync(`/nodes/${t.index}`,t,e=>{e.parent=this._rootBabylonMesh}))}for(const e of this._postSceneLoadActions)e();return o.push(this._loadAnimationsAsync()),this.logClose(),Promise.all(o).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,o=()=>{}){const s=this._extensionsLoadNodeAsync(e,n,o);if(s)return s;if(n._babylonTransformNode)throw new Error(`${e}: Invalid recursive node hierarchy`);const r=new Array;this.logOpen(`${e} ${n.name||""}`);const i=t=>{if(yr.AddPointerMetadata(t,e),yr._LoadTransform(n,t),null!=n.camera){const o=gr.Get(`${e}/camera`,this._gltf.cameras,n.camera);r.push(this.loadCameraAsync(`/cameras/${o.index}`,o,e=>{e.parent=t,this._babylonScene.useRightHandedSystem||(t.scaling.x=-1)}))}if(n.children)for(const o of n.children){const n=gr.Get(`${e}/children/${o}`,this._gltf.nodes,o);r.push(this.loadNodeAsync(`/nodes/${n.index}`,n,e=>{e.parent=t}))}o(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 o=new t.TransformNode(e,this._babylonScene);o._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,null==n.mesh?n._babylonTransformNode=o:n._babylonTransformNodeForSkin=o,i(o)}if(a)if(l){const o=gr.Get(`${e}/mesh`,this._gltf.meshes,n.mesh);r.push(this._loadMeshAsync(`/meshes/${o.index}`,n,o,o=>{const s=n._babylonTransformNodeForSkin;o.metadata=t.deepMerge(s.metadata,o.metadata||{});const i=gr.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=gr.Get(`/skins/${i.index}/skeleton`,this._gltf.nodes,i.skeleton).parent;n.index===e.index?o.parent=s.parent:o.parent=e._babylonTransformNode}else o.parent=this._rootBabylonMesh;this._parent.onSkinLoadedObservable.notifyObservers({node:s,skinnedNode:o})})}))}))}else{const t=gr.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,o,s){const r=o.primitives;if(!r||!r.length)throw new Error(`${e}: Primitives are missing`);null==r[0].index&&gr.Assign(r);const i=new Array;this.logOpen(`${e} ${o.name||""}`);const a=n.name||`node${n.index}`;if(1===r.length){const t=o.primitives[0];i.push(this._loadMeshPrimitiveAsync(`${e}/primitives/${t.index}`,a,n,o,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,o,t,e=>{e.parent=n._babylonTransformNode,n._primitiveBabylonMeshes.push(e)}))}return s(n._babylonTransformNode),this.logClose(),Promise.all(i).then(()=>n._babylonTransformNode)}_loadMeshPrimitiveAsync(e,n,o,s,r,i){const a=this._extensionsLoadMeshPrimitiveAsync(e,n,o,s,r,i);if(a)return a;this.logOpen(`${e}`);const l=0===this._disableInstancedMesh&&this._parent.createInstances&&null==o.skin&&!s.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,o,s,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=yr._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=gr.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 yr.AddPointerMetadata(u,e),this._parent.onMeshLoadedObservable.notifyObservers(u),i(u),this.logClose(),c.then(()=>u)}_loadVertexDataAsync(e,n,o){const s=this._extensionsLoadVertexDataAsync(e,n,o);if(s)return s;const r=n.attributes;if(!r)throw new Error(`${e}: Attributes are missing`);const i=new Array,a=new t.Geometry(o.name,this._babylonScene);if(null==n.indices)o.isUnIndexed=!0;else{const t=gr.Get(`${e}/indices`,this._gltf.accessors,n.indices);i.push(this._loadIndicesAccessorAsync(`/accessors/${t.index}`,t).then(e=>{a.setIndices(e)}))}const l=(n,s,l)=>{if(null==r[n])return;o._delayInfo=o._delayInfo||[],-1===o._delayInfo.indexOf(s)&&o._delayInfo.push(s);const u=gr.Get(`${e}/attributes/${n}`,this._gltf.accessors,r[n]);i.push(this._loadVertexAccessorAsync(`/accessors/${u.index}`,u,s).then(e=>{if(e.getKind()===t.VertexBuffer.PositionKind&&!this.parent.alwaysComputeBoundingBox&&!o.skeleton){const e=vr(u);e&&(a._boundingInfo=e,a.useBoundingInfoFromGeometry=!0)}a.setVerticesBuffer(e,u.count)})),s==t.VertexBuffer.MatricesIndicesExtraKind&&(o.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&&(o.hasVertexAlpha=!0)}),Promise.all(i).then(()=>a)}_createMorphTargets(e,n,o,s,r){if(!s.targets||!this._parent.loadMorphTargets)return;if(null==n._numMorphTargets)n._numMorphTargets=s.targets.length;else if(s.targets.length!==n._numMorphTargets)throw new Error(`${e}: Primitives do not have the same number of targets`);const i=o.extras?o.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<s.targets.length;e++){const s=n.weights?n.weights[e]:o.weights?o.weights[e]:0,a=i?i[e]:`morphTarget${e}`;r.morphTargetManager.addTarget(new t.MorphTarget(a,s,r.getScene()))}}_loadMorphTargetsAsync(e,n,o,s){if(!n.targets||!this._parent.loadMorphTargets)return Promise.resolve();const r=new Array,i=o.morphTargetManager;for(let t=0;t<i.numTargets;t++){const o=i.getTarget(t);r.push(this._loadMorphTargetVertexDataAsync(`${e}/targets/${t}`,s,n.targets[t],o))}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,o,s){return b(this,void 0,void 0,function*(){const r=new Array,i=(t,s,i)=>{if(null==o[t])return;const a=n.getVertexBuffer(s);if(!a)return;const l=gr.Get(`${e}/${t}`,this._gltf.accessors,o[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,o)=>{n[o]=t[o]+e}),s.setPositions(n)}),i("NORMAL",t.VertexBuffer.NormalKind,(e,t)=>{const n=new Float32Array(t.length);e.forEach(n.length,(e,o)=>{n[o]=t[o]+e}),s.setNormals(n)}),i("TANGENT",t.VertexBuffer.TangentKind,(e,t)=>{const n=new Float32Array(t.length/3*4);let o=0;e.forEach(t.length/3*4,(e,s)=>{(s+1)%4!=0&&(n[o]=t[o]+e,o++)}),s.setTangents(n)}),i("TEXCOORD_0",t.VertexBuffer.UVKind,(e,t)=>{const n=new Float32Array(t.length);e.forEach(t.length,(e,o)=>{n[o]=t[o]+e}),s.setUVs(n)}),i("TEXCOORD_1",t.VertexBuffer.UV2Kind,(e,t)=>{const n=new Float32Array(t.length);e.forEach(t.length,(e,o)=>{n[o]=t[o]+e}),s.setUV2s(n)}),i("COLOR_0",t.VertexBuffer.ColorKind,(t,n)=>{let o=null;const r=t.getSize();if(3===r){o=new Float32Array(n.length/3*4),t.forEach(n.length,(e,t)=>{const s=Math.floor(t/3),r=t%3;o[4*s+r]=n[3*s+r]+e});for(let e=0;e<n.length/3;++e)o[4*e+3]=1}else{if(4!==r)throw new Error(`${e}: Invalid number of components (${r}) for COLOR_0 attribute`);o=new Float32Array(n.length),t.forEach(n.length,(e,t)=>{o[t]=n[t]+e})}s.setColors(o)}),yield Promise.all(r).then(()=>{})})}static _LoadTransform(e,n){if(null!=e.skin)return;let o=t.Vector3.Zero(),s=t.Quaternion.Identity(),r=t.Vector3.One();e.matrix?t.Matrix.FromArray(e.matrix).decompose(r,s,o):(e.translation&&(o=t.Vector3.FromArray(e.translation)),e.rotation&&(s=t.Quaternion.FromArray(e.rotation)),e.scale&&(r=t.Vector3.FromArray(e.scale))),n.position=o,n.rotationQuaternion=s,n.scaling=r}_loadSkinAsync(e,n,o,s){if(!this._parent.loadSkins)return Promise.resolve();const r=this._extensionsLoadSkinAsync(e,n,o);if(r)return r;if(o._data)return s(o._data.babylonSkeleton),o._data.promise;const i=`skeleton${o.index}`;this._babylonScene._blockEntityCollection=!!this._assetContainer;const a=new t.Skeleton(o.name||i,i,this._babylonScene);a._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,this._loadBones(e,o,a);const l=this._loadSkinInverseBindMatricesDataAsync(e,o).then(e=>{this._updateBoneMatrices(a,e)});return o._data={babylonSkeleton:a,promise:l},s(a),l}_loadBones(e,n,o){if(null==n.skeleton||this._parent.alwaysComputeSkeletonRootNode){const o=this._findSkeletonRootNode(`${e}/joints`,n.joints);if(o)if(void 0===n.skeleton)n.skeleton=o.index;else{const s=(e,t)=>{for(;t.parent;t=t.parent)if(t.parent===e)return!0;return!1},r=gr.Get(`${e}/skeleton`,this._gltf.nodes,n.skeleton);r===o||s(r,o)||(t.Logger.Warn(`${e}/skeleton: Overriding with nearest common ancestor as skeleton node is not a common root`),n.skeleton=o.index)}else t.Logger.Warn(`${e}: Failed to find common root`)}const s={};for(const t of n.joints){const r=gr.Get(`${e}/joints/${t}`,this._gltf.nodes,t);this._loadBone(r,n,o,s)}}_findSkeletonRootNode(e,t){if(0===t.length)return null;const n={};for(const o of t){const t=[];let s=gr.Get(`${e}/${o}`,this._gltf.nodes,o);for(;-1!==s.index;)t.unshift(s),s=s.parent;n[o]=t}let o=null;for(let e=0;;++e){let s=n[t[0]];if(e>=s.length)return o;const r=s[e];for(let i=1;i<t.length;++i)if(s=n[t[i]],e>=s.length||r!==s[e])return o;o=r}}_loadBone(e,n,o,s){e._isJoint=!0;let r=s[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,o,s):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}`,o,i,this._getNodeMatrix(e),null,null,a),s[e.index]=r,this._postSceneLoadActions.push(()=>{r.linkTransformNode(e._babylonTransformNode)}),r}_loadSkinInverseBindMatricesDataAsync(e,t){if(null==t.inverseBindMatrices)return Promise.resolve(null);const n=gr.Get(`${e}/inverseBindMatrices`,this._gltf.accessors,t.inverseBindMatrices);return this._loadFloatAccessorAsync(`/accessors/${n.index}`,n)}_updateBoneMatrices(e,n){for(const o of e.bones){const e=t.Matrix.Identity(),s=o._index;n&&-1!==s&&(t.Matrix.FromArrayToRef(n,16*s,e),e.invertToRef(e));const r=o.getParent();r&&e.multiplyToRef(r.getAbsoluteInverseBindMatrix(),e),o.updateMatrix(e,!1,!1),o._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,o=()=>{}){const s=this._extensionsLoadCameraAsync(e,n,o);if(s)return s;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 yr.AddPointerMetadata(i,e),this._parent.onCameraLoadedObservable.notifyObservers(i),o(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 o=e[n];t.push(this.loadAnimationAsync(`/animations/${o.index}`,o).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)||mr.value.then(({AnimationGroup:n})=>{this._babylonScene._blockEntityCollection=!!this._assetContainer;const o=new n(t.name||`animation${t.index}`,this._babylonScene);o._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,t._babylonAnimationGroup=o;const s=new Array;gr.Assign(t.channels),gr.Assign(t.samplers);for(const n of t.channels)s.push(this._loadAnimationChannelAsync(`${e}/channels/${n.index}`,e,t,n,(e,t)=>{e.animations=e.animations||[],e.animations.push(t),o.addTargetedAnimation(t,e)}));return this._parent._endPerformanceCounter("Load animation"),Promise.all(s).then(()=>(o.normalize(0),o))})}_loadAnimationChannelAsync(e,t,n,o,s){const r=this._extensionsLoadAnimationChannelAsync(e,t,n,o,s);if(r)return r;if(null==o.target.node)return Promise.resolve();const i=gr.Get(`${e}/target/node`,this._gltf.nodes,o.target.node),a=o.target.path,l="weights"===a;return l&&!i._numMorphTargets||!l&&!i._babylonTransformNode?Promise.resolve():this._parent.loadNodeAnimations||l||i._isJoint?_r.value.then(({RegisterGLTFLoaderAnimation:r})=>{var l,u,c,d;let h;switch(r(),a){case"translation":h=null===(l=hr("/nodes/{}/translation"))||void 0===l?void 0:l.interpolation;break;case"rotation":h=null===(u=hr("/nodes/{}/rotation"))||void 0===u?void 0:u.interpolation;break;case"scale":h=null===(c=hr("/nodes/{}/scale"))||void 0===c?void 0:c.interpolation;break;case"weights":h=null===(d=hr("/nodes/{}/weights"))||void 0===d?void 0:d.interpolation;break;default:throw new Error(`${e}/target/path: Invalid value (${o.target.path})`)}if(!h)throw new Error(`${e}/target/path: Could not find interpolation properties for target path (${o.target.path})`);const f={object:i,info:h};return this._loadAnimationChannelFromTargetInfoAsync(e,t,n,o,f,s)}):Promise.resolve()}_loadAnimationChannelFromTargetInfoAsync(e,t,n,o,s,r){const i=this.parent.targetFps,a=1/i,l=gr.Get(`${e}/sampler`,n.samplers,o.sampler);return this._loadAnimationSamplerAsync(`${t}/samplers/${o.sampler}`,l).then(e=>{let t=0;const l=s.object,u=s.info;for(const s of u){const u=s.getStride(l),c=e.input,d=e.output,h=new Array(c.length);let f=0;switch(e.interpolation){case"STEP":for(let e=0;e<c.length;e++){const t=s.getValue(l,d,f,1);f+=u,h[e]={frame:c[e]*i,value:t,interpolation:1}}break;case"CUBICSPLINE":for(let e=0;e<c.length;e++){const t=s.getValue(l,d,f,a);f+=u;const n=s.getValue(l,d,f,1);f+=u;const o=s.getValue(l,d,f,a);f+=u,h[e]={frame:c[e]*i,inTangent:t,value:n,outTangent:o}}break;case"LINEAR":for(let e=0;e<c.length;e++){const t=s.getValue(l,d,f,1);f+=u,h[e]={frame:c[e]*i,value:t}}}if(f>0){const e=`${n.name||`animation${n.index}`}_channel${o.index}_${t}`,a=s.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 o=gr.Get(`${e}/input`,this._gltf.accessors,t.input),s=gr.Get(`${e}/output`,this._gltf.accessors,t.output);return t._data=Promise.all([this._loadFloatAccessorAsync(`/accessors/${o.index}`,o),this._loadFloatAccessorAsync(`/accessors/${s.index}`,s)]).then(([e,t])=>({input:e,interpolation:n,output:t})),t._data}loadBufferAsync(e,t,n,o){const s=this._extensionsLoadBufferAsync(e,t,n,o);if(s)return s;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,o)}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 o=gr.Get(`${e}/buffer`,this._gltf.buffers,t.buffer);return t._data=this.loadBufferAsync(`/buffers/${o.index}`,o,t.byteOffset||0,t.byteLength),t._data}_loadAccessorAsync(e,n,o){if(n._data)return n._data;const s=yr._GetNumComponents(e,n.type),r=s*t.VertexBufferGetTypeByteLength(n.componentType),i=s*n.count;if(null==n.bufferView)n._data=Promise.resolve(new o(i));else{const a=gr.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 o(i);return t.VertexBufferForEach(l,n.byteOffset||0,a.byteStride||r,s,n.componentType,e.length,n.normalized||!1,(t,n)=>{e[n]=t}),e}return yr._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=gr.Get(`${e}/sparse/indices/bufferView`,this._gltf.bufferViews,i.indices.bufferView),c=gr.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=yr._GetTypedArray(`${e}/sparse/indices`,i.indices.componentType,a,i.indices.byteOffset,i.count),d=s*i.count;let h;if(5126!==n.componentType||n.normalized){const a=yr._GetTypedArray(`${e}/sparse/values`,n.componentType,u,i.values.byteOffset,d);h=new o(d),t.VertexBufferForEach(a,0,r,s,n.componentType,h.length,n.normalized||!1,(e,t)=>{h[t]=e})}else h=yr._GetTypedArray(`${e}/sparse/values`,n.componentType,u,i.values.byteOffset,d);let f=0;for(let e=0;e<c.length;e++){let t=c[e]*s;for(let e=0;e<s;e++)l[t++]=h[f++]}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=yr._GetTypedArrayConstructor(`${e}/componentType`,t.componentType);t._data=this._loadAccessorAsync(e,t,n)}else{const n=gr.Get(`${e}/bufferView`,this._gltf.bufferViews,t.bufferView);t._data=this.loadBufferViewAsync(`/bufferViews/${n.index}`,n).then(n=>yr._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,o){var s;if(null===(s=n._babylonVertexBuffer)||void 0===s?void 0:s[o])return n._babylonVertexBuffer[o];n._babylonVertexBuffer||(n._babylonVertexBuffer={});const r=this._babylonScene.getEngine();if(n.sparse||null==n.bufferView)n._babylonVertexBuffer[o]=this._loadFloatAccessorAsync(e,n).then(e=>new t.VertexBuffer(r,e,o,!1));else{const s=gr.Get(`${e}/bufferView`,this._gltf.bufferViews,n.bufferView);n._babylonVertexBuffer[o]=this._loadVertexBufferViewAsync(s).then(i=>{const a=yr._GetNumComponents(e,n.type);return new t.VertexBuffer(r,i,o,!1,void 0,s.byteStride,void 0,n.byteOffset,a,n.componentType,n.normalized,!0,void 0,!0)})}return n._babylonVertexBuffer[o]}_loadMaterialMetallicRoughnessPropertiesAsync(e,n,o){const s=new Array,r=this._getOrCreateMaterialAdapter(o);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&&s.push(this.loadTextureInfoAsync(`${e}/baseColorTexture`,n.baseColorTexture,e=>{e.name=`${o.name} (Base Color)`,r.baseColorTexture=e})),n.metallicRoughnessTexture&&(n.metallicRoughnessTexture.nonColorData=!0,s.push(this.loadTextureInfoAsync(`${e}/metallicRoughnessTexture`,n.metallicRoughnessTexture,e=>{e.name=`${o.name} (Metallic Roughness)`,r.baseMetalnessTexture=e,r.specularRoughnessTexture=e})),r.useRoughnessFromMetallicTextureGreen=!0,r.useMetallicFromMetallicTextureBlue=!0)),Promise.all(s).then(()=>{})}_loadMaterialAsync(e,t,n,o,s=()=>{}){const r=this._extensionsLoadMaterialAsync(e,t,n,o,s);if(r)return r;t._data=t._data||{};let i=t._data[o];if(!i){this.logOpen(`${e} ${t.name||""}`);const n=this.createMaterial(e,t,o);i={babylonMaterial:n,babylonMeshes:[],promise:this.loadMaterialPropertiesAsync(e,t,n)},t._data[o]=i,yr.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)})),s(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 o=new n.materialClass(e,this._babylonScene);o._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,o.fillMode=t,o.transparencyMode=n.materialClass.MATERIAL_OPAQUE;const s=this._getOrCreateMaterialAdapter(o);return s.transparencyAsAlphaCoverage=this._parent.transparencyAsCoverage,s.baseMetalness=1,s.specularRoughness=1,o}createMaterial(e,t,n){const o=this._extensionsCreateMaterial(e,t,n);if(o)return o;const s=t.name||`material${t.index}`;return this._createDefaultMaterial(s,n,this._selectImplForGltfMaterial(t))}loadMaterialPropertiesAsync(e,t,n){const o=this._extensionsLoadMaterialPropertiesAsync(e,t,n);if(o)return o;const s=new Array;return s.push(this.loadMaterialBasePropertiesAsync(e,t,n)),t.pbrMetallicRoughness&&s.push(this._loadMaterialMetallicRoughnessPropertiesAsync(`${e}/pbrMetallicRoughness`,t.pbrMetallicRoughness,n)),this.loadMaterialAlphaProperties(e,t,n),Promise.all(s).then(()=>{})}loadMaterialBasePropertiesAsync(e,n,o){const s=new Array,r=this._getOrCreateMaterialAdapter(o);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,s.push(this.loadTextureInfoAsync(`${e}/normalTexture`,n.normalTexture,e=>{var t;e.name=`${o.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,s.push(this.loadTextureInfoAsync(`${e}/occlusionTexture`,n.occlusionTexture,e=>{e.name=`${o.name} (Occlusion)`,i=e})),null!=n.occlusionTexture.strength&&(l=n.occlusionTexture.strength)),n.emissiveTexture&&s.push(this.loadTextureInfoAsync(`${e}/emissiveTexture`,n.emissiveTexture,e=>{e.name=`${o.name} (Emissive)`,a=e})),Promise.all(s).then(()=>{i&&(r.ambientOcclusionTexture=i,r.ambientOcclusionTextureStrength=l),a&&(r.emissionColorTexture=a)})}loadMaterialAlphaProperties(e,n,o){if(0===this._pbrMaterialImpls.size)throw new Error(`${e}: Material type not supported`);const s=this._getOrCreateMaterialAdapter(o),r=s.baseColorTexture;switch(n.alphaMode||"OPAQUE"){case"OPAQUE":o.transparencyMode=t.Material.MATERIAL_OPAQUE,o.alpha=1;break;case"MASK":o.transparencyMode=t.Material.MATERIAL_ALPHATEST,s.alphaCutOff=null==n.alphaCutoff?.5:n.alphaCutoff,r&&(r.hasAlpha=!0,s.useAlphaFromBaseColorTexture=!0);break;case"BLEND":o.transparencyMode=t.Material.MATERIAL_ALPHABLEND,r&&(r.hasAlpha=!0,s.useAlphaFromBaseColorTexture=!0);break;default:throw new Error(`${e}/alphaMode: Invalid value (${n.alphaMode})`)}}loadTextureInfoAsync(e,t,n=()=>{}){const o=this._extensionsLoadTextureInfoAsync(e,t,n);if(o)return o;if(this.logOpen(`${e}`),t.texCoord>=6)throw new Error(`${e}/texCoord: Invalid value (${t.texCoord})`);const s=gr.Get(`${e}/index`,this._gltf.textures,t.index);s._textureInfo=t;const r=this._loadTextureAsync(`/textures/${t.index}`,s,o=>{o.coordinatesIndex=t.texCoord||0,yr.AddPointerMetadata(o,e),this._parent.onTextureLoadedObservable.notifyObservers(o),n(o)});return this.logClose(),r}_loadTextureAsync(e,t,n=()=>{}){const o=this._extensionsLoadTextureAsync(e,t,n);if(o)return o;this.logOpen(`${e} ${t.name||""}`);const s=null==t.sampler?yr.DefaultSampler:gr.Get(`${e}/sampler`,this._gltf.samplers,t.sampler),r=gr.Get(`${e}/source`,this._gltf.images,t.source),i=this._createTextureAsync(e,s,r,n,void 0,!t._textureInfo.nonColorData);return this.logClose(),i}_createTextureAsync(e,n,o,s=()=>{},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=o.mimeType)&&void 0!==a?a:t.GetMimeType(null!==(l=o.uri)&&void 0!==l?l:""),loaderOptions:r,useSRGBBuffer:!!i&&this._parent.useSRGBBuffers},f=new t.Texture(null,this._babylonScene,h);f._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,c.push(d.promise);const p=o.uri&&!t.IsBase64DataUrl(o.uri)?o.uri:void 0,m=null!=p?p:`${this._fileName}#image${o.index}`;if(c.push(this.loadImageAsync(`/images/${o.index}`,o).then(e=>{const t=`data:${this._uniqueRootUrl}${m}`;f.updateURL(t,e);const n=f.getInternalTexture();n&&(n.label=o.name)})),f.wrapU=u.wrapU,f.wrapV=u.wrapV,s(f),this._parent.useGltfTextureNames){const e=o.name||p||`image${o.index}`;f.name=e}return Promise.all(c).then(()=>f)}_loadSampler(e,t){return t._data||(t._data={noMipMaps:9728===t.minFilter||9729===t.minFilter,samplingMode:yr._GetTextureSamplingMode(e,t),wrapU:yr._GetTextureWrapMode(`${e}/wrapS`,t.wrapS),wrapV:yr._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=gr.Get(`${e}/bufferView`,this._gltf.bufferViews,t.bufferView);t._data=this.loadBufferViewAsync(`/bufferViews/${n.index}`,n)}this.logClose()}return t._data}loadUriAsync(e,n,o){var s;const r=this._extensionsLoadUriAsync(e,n,o);if(r)return r;if(!this._parent._isPreprocessUrlAsyncSet&&!yr._ValidateUri(o))throw new Error(`${e}: '${o}' is invalid`);if(t.IsBase64DataUrl(o)){const n=new Uint8Array(t.DecodeBase64UrlToBinary(o));return this.log(`${e}: Decoded ${o.substring(0,64)}... (${n.length} bytes)`),Promise.resolve(n)}return this.log(`${e}: Loading ${o}`),this._parent.preprocessUrlAsync(this._rootUrl+o,null!==(s=this._rootUrl)&&void 0!==s?s:void 0).then(n=>new Promise((s,r)=>{this._parent._loadFile(this._babylonScene,n,t=>{this._disposed||(this.log(`${e}: Loaded ${o} (${t.byteLength} bytes)`),s(new Uint8Array(t)))},!0,n=>{r(new t.LoadFileError(`${e}: Failed to load '${o}'${n?": "+n.status+" "+n.statusText:""}`,n))})}))}static AddPointerMetadata(e,t){e.metadata=e.metadata||{};const n=e._internalMetadata=e._internalMetadata||{},o=n.gltf=n.gltf||{};(o.pointers=o.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 o=null==n.magFilter?9729:n.magFilter,s=null==n.minFilter?9987:n.minFilter;if(9729===o)switch(s){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 (${s})`),t.Texture.LINEAR_LINEAR_MIPLINEAR}else switch(9728!==o&&t.Logger.Warn(`${e}/magFilter: Invalid value (${o})`),s){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 (${s})`),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,o,s,r){const i=o.buffer;s=o.byteOffset+(s||0);const a=yr._GetTypedArrayConstructor(`${e}/componentType`,n),l=t.VertexBufferGetTypeByteLength(n);return s%l!==0?(t.Logger.Warn(`${e}: Copying buffer as byte offset (${s}) is not a multiple of component type byte length (${l})`),new a(i.slice(s,s+r*l),0)):new a(i,s,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 o=t._data[n];for(const t of o.babylonMeshes){t.computeWorldMatrix(!0);const n=o.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 o of this._extensions)if(o.enabled){const s=`${o.name}.${t}`,r=e;r._activeLoaderExtensionFunctions=r._activeLoaderExtensionFunctions||{};const i=r._activeLoaderExtensionFunctions;if(!i[s]){i[s]=!0;try{const e=n(o);if(e)return e}finally{delete i[s]}}}return null}_extensionsOnLoading(){this._forEachExtensions(e=>e.onLoading&&e.onLoading())}_extensionsOnReadyAsync(){return b(this,void 0,void 0,function*(){for(const e of this._extensions)e.enabled&&e.onReady&&(yield 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",o=>o.loadNodeAsync&&o.loadNodeAsync(e,t,n))}_extensionsLoadCameraAsync(e,t,n){return this._applyExtensions(t,"loadCamera",o=>o.loadCameraAsync&&o.loadCameraAsync(e,t,n))}_extensionsLoadVertexDataAsync(e,t,n){return this._applyExtensions(t,"loadVertexData",o=>o._loadVertexDataAsync&&o._loadVertexDataAsync(e,t,n))}_extensionsLoadMeshPrimitiveAsync(e,t,n,o,s,r){return this._applyExtensions(s,"loadMeshPrimitive",i=>i._loadMeshPrimitiveAsync&&i._loadMeshPrimitiveAsync(e,t,n,o,s,r))}_extensionsLoadMaterialAsync(e,t,n,o,s){return this._applyExtensions(t,"loadMaterial",r=>r._loadMaterialAsync&&r._loadMaterialAsync(e,t,n,o,s))}_extensionsCreateMaterial(e,t,n){return this._applyExtensions(t,"createMaterial",o=>o.createMaterial&&o.createMaterial(e,t,n))}_extensionsLoadMaterialPropertiesAsync(e,t,n){return this._applyExtensions(t,"loadMaterialProperties",o=>o.loadMaterialPropertiesAsync&&o.loadMaterialPropertiesAsync(e,t,n))}_extensionsLoadTextureInfoAsync(e,t,n){return this._applyExtensions(t,"loadTextureInfo",o=>o.loadTextureInfoAsync&&o.loadTextureInfoAsync(e,t,n))}_extensionsLoadTextureAsync(e,t,n){return this._applyExtensions(t,"loadTexture",o=>o._loadTextureAsync&&o._loadTextureAsync(e,t,n))}_extensionsLoadAnimationAsync(e,t){return this._applyExtensions(t,"loadAnimation",n=>n.loadAnimationAsync&&n.loadAnimationAsync(e,t))}_extensionsLoadAnimationChannelAsync(e,t,n,o,s){return this._applyExtensions(n,"loadAnimationChannel",r=>r._loadAnimationChannelAsync&&r._loadAnimationChannelAsync(e,t,n,o,s))}_extensionsLoadSkinAsync(e,t,n){return this._applyExtensions(n,"loadSkin",o=>o._loadSkinAsync&&o._loadSkinAsync(e,t,n))}_extensionsLoadUriAsync(e,t,n){return this._applyExtensions(t,"loadUri",o=>o._loadUriAsync&&o._loadUriAsync(e,t,n))}_extensionsLoadBufferViewAsync(e,t){return this._applyExtensions(t,"loadBufferView",n=>n.loadBufferViewAsync&&n.loadBufferViewAsync(e,t))}_extensionsLoadBufferAsync(e,t,n,o){return this._applyExtensions(t,"loadBuffer",s=>s.loadBufferAsync&&s.loadBufferAsync(e,t,n,o))}static LoadExtensionAsync(e,t,n,o){if(!t.extensions)return null;const s=t.extensions[n];return s?o(`${e}/extensions/${n}`,s):null}static LoadExtraAsync(e,t,n,o){if(!t.extras)return null;const s=t.extras[n];return s?o(`${e}/extras/${n}`,s):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)}}yr.DefaultSampler={index:-1};let br=!1;function xr(){br||(br=!0,ts._CreateGLTF2Loader=e=>new yr(e))}var Tr={__proto__:null,ArrayItem:gr,GLTFFileLoader:ts,GLTFLoader:yr,LoadBoundingInfoFromPositionAccessor:vr,RegisterGLTF2Loader:xr};function Ar(e,n,o,s){return t.Vector3.FromArray(n,o).scaleInPlace(s)}function Mr(e,n,o,s){return t.Quaternion.FromArray(n,o).scaleInPlace(s)}function wr(e,t,n,o){const s=new Array(e._numMorphTargets);for(let e=0;e<s.length;e++)s[e]=t[n++]*o;return s}xr(),os();class Sr{constructor(e,t,n,o){this.type=e,this.name=t,this.getValue=n,this.getStride=o}_buildAnimation(e,n,o){const s=new t.Animation(e,this.name,n,this.type);return s.setKeys(o,!0),s}}class Cr extends Sr{buildAnimations(e,t,n,o){const s=[];return s.push({babylonAnimatable:e._babylonTransformNode,babylonAnimation:this._buildAnimation(t,n,o)}),s}}class Rr extends Sr{buildAnimations(e,n,o,s){const r=[];if(e._numMorphTargets)for(let i=0;i<e._numMorphTargets;i++){const a=new t.Animation(`${n}_${i}`,this.name,o,this.type);if(a.setKeys(s.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}}let Ir=!1;function Or(){Ir||(Ir=!0,fr("/nodes/{}/translation",[new Cr(t.Animation.ANIMATIONTYPE_VECTOR3,"position",Ar,()=>3)]),fr("/nodes/{}/rotation",[new Cr(t.Animation.ANIMATIONTYPE_QUATERNION,"rotationQuaternion",Mr,()=>4)]),fr("/nodes/{}/scale",[new Cr(t.Animation.ANIMATIONTYPE_VECTOR3,"scaling",Ar,()=>3)]),fr("/nodes/{}/weights",[new Rr(t.Animation.ANIMATIONTYPE_FLOAT,"influence",wr,e=>e._numMorphTargets)]))}var Fr={__proto__:null,AnimationPropertyInfo:Sr,RegisterGLTFLoaderAnimation:Or,TransformNodeAnimationPropertyInfo:Cr,WeightAnimationPropertyInfo:Rr,getQuaternion:Mr,getVector3:Ar,getWeights:wr};Or();class Er{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,o,s;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===(o=i.texture)||void 0===o||o.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===(s=a.texture)||void 0===s||s.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,o,s,r,i){return b(this,arguments,void 0,function*(e,n,o,s,r,i,a=!1){var l,u,c,d,h,f,p,m,_;const g=this._material.coatWeight,v=this._material.coatWeightTexture,y=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,y.toColor4(),t.TextureChannel.RGBA,t.TextureColorSpace.SRGB),t.CreateTextureWithFactorOperand(v,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(o,A,s),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[S,C]=M.map(e=>e.value);if(e._disposed)return null===(u=S.texture)||void 0===u||u.dispose(),void(null===(c=C.texture)||void 0===c||c.dispose());const R=yield t.MultiplyTexturesAsync("newCoatColor ("+this._material.name+")",S,C,this._material.getScene(),t.TextureColorSpace.SRGB);if(e._disposed)return void(null===(d=R.texture)||void 0===d||d.dispose());R.texture?(this.coatColorTexture=R.texture,this.coatColor=t.Color3.White()):R.factor&&(this.coatColorTexture=null,this.coatColor.fromArray([R.factor.r,R.factor.g,R.factor.b]));const I=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(v,T,t.TextureChannel.R),this._material.getScene());if(e._disposed)return void(null===(h=I.texture)||void 0===h||h.dispose());this.coatIor=I.factor?I.factor.r:this.coatIor;const O=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(v,T,t.TextureChannel.R),this._material.getScene());if(e._disposed)return void(null===(f=O.texture)||void 0===f||f.dispose());this.coatRoughness=O.factor?O.factor.r:1,this.coatRoughnessTexture=O.texture;const F=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(v,T,t.TextureChannel.R),this._material.getScene());if(e._disposed)null===(p=F.texture)||void 0===p||p.dispose();else{if(this.coatDarkening=F.factor?F.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(o,A,s),this._material.getScene());if(e._disposed)return void(null===(m=n.texture)||void 0===m||m.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(v,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 Lr={__proto__:null,OpenPBRMaterialLoadingAdapter:Er};class Nr{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 o=n,s=Math.max(o.x,Math.max(o.y,o.z)),r=s>0?1/s:1;this._material.subSurface.diffusionDistance=new t.Color3(Math.exp(-o.x*r),Math.exp(-o.y*r),Math.exp(-o.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 kr={__proto__:null,PBRMaterialLoadingAdapter:Nr};const Br="EXT_lights_image_based";class Pr{constructor(e){this.name=Br,this._loader=e,this.enabled=this._loader.isExtensionUsed(Br)}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 yr.LoadExtensionAsync(e,t,this.name,(n,o)=>b(this,void 0,void 0,function*(){this._loader._allMaterialsDirtyRequired=!0;const s=new Array;s.push(this._loader.loadSceneAsync(e,t)),this._loader.logOpen(`${n}`);const r=gr.Get(`${n}/light`,this._lights,o.light);return s.push(this._loadLightAsync(`/extensions/${this.name}/lights/${o.light}`,r).then(e=>{this._loader.babylonScene.environmentTexture=e})),this._loader.logClose(),yield Promise.all(s).then(()=>{})}))}_loadLightAsync(e,n){if(!n._loaded){const o=new Array;this._loader.logOpen(`${e}`);const s=new Array(n.specularImages.length);for(let t=0;t<n.specularImages.length;t++){const r=n.specularImages[t];s[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=gr.Get(i,this._loader.gltf.images,a);o.push(this._loader.loadImageAsync(`/images/${a}`,l).then(e=>{s[t][n]=e})),this._loader.logClose()}}this._loader.logClose(),n._loaded=Promise.all(o).then(()=>b(this,void 0,void 0,function*(){const o=new t.RawCubeTexture(this._loader.babylonScene,null,n.specularImageSize);if(o.name=n.name||"environment",n._babylonTexture=o,null!=n.intensity&&(o.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,o.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=(s.length-1)/Math.log2(n.specularImageSize);return yield o.updateRGBDAsync(s,i,a)}))}return n._loaded.then(()=>n._babylonTexture)}}let Dr=!1;function Vr(){Dr||(Dr=!0,Ys(Br),Xs(Br,!0,e=>new Pr(e)))}var Gr={__proto__:null,EXT_lights_image_based:Pr,RegisterEXT_lights_image_based:Vr};Vr();const $r="EXT_mesh_gpu_instancing";class Ur{constructor(e){this.name=$r,this._loader=e,this.enabled=this._loader.isExtensionUsed($r)}dispose(){this._loader=null}loadNodeAsync(e,n,o){return yr.LoadExtensionAsync(e,n,this.name,(e,s)=>b(this,void 0,void 0,function*(){this._loader._disableInstancedMesh++;const r=this._loader.loadNodeAsync(`/nodes/${n.index}`,n,o);if(this._loader._disableInstancedMesh--,!n._primitiveBabylonMeshes)return yield r;const i=new Array;let a=0;const l=t=>{if(null==s.attributes[t])return void i.push(Promise.resolve(null));const n=gr.Get(`${e}/attributes/${t}`,this._loader.gltf.accessors,s.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[o,s,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)o&&t.Vector3.FromArrayToRef(o,3*e,t.TmpVectors.Vector3[0]),s&&t.Quaternion.FromArrayToRef(s,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}))}))}}let Hr=!1;function Kr(){Hr||(Hr=!0,Ys($r),Xs($r,!0,e=>new Ur(e)))}var Wr={__proto__:null,EXT_mesh_gpu_instancing:Ur,RegisterEXT_mesh_gpu_instancing:Kr};Kr();const qr="EXT_meshopt_compression";class zr{constructor(e){this.name=qr,this.enabled=e.isExtensionUsed(qr),this._loader=e}dispose(){this._loader=null}loadBufferViewAsync(e,n){return yr.LoadExtensionAsync(e,n,this.name,(o,s)=>b(this,void 0,void 0,function*(){const o=n;if(o._meshOptData)return yield o._meshOptData;const r=gr.Get(`${e}/buffer`,this._loader.gltf.buffers,s.buffer);return o._meshOptData=this._loader.loadBufferAsync(`/buffers/${r.index}`,r,s.byteOffset||0,s.byteLength).then(e=>b(this,void 0,void 0,function*(){return yield t.MeshoptCompression.Default.decodeGltfBufferAsync(e,s.count,s.byteStride,s.mode,s.filter)})),yield o._meshOptData}))}}let jr=!1;function Xr(){jr||(jr=!0,Ys(qr),Xs(qr,!0,e=>new zr(e)))}var Yr={__proto__:null,EXT_meshopt_compression:zr,RegisterEXT_meshopt_compression:Xr};Xr();const Qr="EXT_texture_webp";class Zr{constructor(e){this.name=Qr,this._loader=e,this.enabled=e.isExtensionUsed(Qr)}dispose(){this._loader=null}_loadTextureAsync(e,t,n){return yr.LoadExtensionAsync(e,t,this.name,(o,s)=>b(this,void 0,void 0,function*(){const r=null==t.sampler?yr.DefaultSampler:gr.Get(`${e}/sampler`,this._loader.gltf.samplers,t.sampler),i=gr.Get(`${o}/source`,this._loader.gltf.images,s.source);return yield this._loader._createTextureAsync(e,r,i,e=>{n(e)},void 0,!t._textureInfo.nonColorData)}))}}let Jr=!1;function ei(){Jr||(Jr=!0,Ys(Qr),Xs(Qr,!0,e=>new Zr(e)))}var ti={__proto__:null,EXT_texture_webp:Zr,RegisterEXT_texture_webp:ei};ei();const ni="EXT_texture_avif";class oi{constructor(e){this.name=ni,this._loader=e,this.enabled=e.isExtensionUsed(ni)}dispose(){this._loader=null}_loadTextureAsync(e,t,n){return yr.LoadExtensionAsync(e,t,this.name,(o,s)=>b(this,void 0,void 0,function*(){const r=null==t.sampler?yr.DefaultSampler:gr.Get(`${e}/sampler`,this._loader.gltf.samplers,t.sampler),i=gr.Get(`${o}/source`,this._loader.gltf.images,s.source);return yield this._loader._createTextureAsync(e,r,i,e=>{n(e)},void 0,!t._textureInfo.nonColorData)}))}}let si=!1;function ri(){si||(si=!0,Ys(ni),Xs(ni,!0,e=>new oi(e)))}var ii={__proto__:null,EXT_texture_avif:oi,RegisterEXT_texture_avif:ri};ri();const ai="EXT_lights_ies";class li{constructor(e){this.name=ai,this._loader=e,this.enabled=this._loader.isExtensionUsed(ai)}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,gr.Assign(this._lights)}}loadNodeAsync(e,n,o){return yr.LoadExtensionAsync(e,n,this.name,(s,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=gr.Get(s,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),yr.AddPointerMetadata(i,s),o(e)});let u;if(a.uri)u=yield this._loader.loadUriAsync(e,a,a.uri);else{const t=gr.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}))}}let ui=!1;function ci(){ui||(ui=!0,Ys(ai),Xs(ai,!0,e=>new li(e)))}var di={__proto__:null,EXT_lights_ies:li,RegisterEXT_lights_ies:ci};ci();const hi="KHR_draco_mesh_compression";class fi{constructor(e){this.name=hi,this.useNormalizedFlagFromAccessor=!0,this._loader=e,this.enabled=t.DracoDecoder.DefaultAvailable&&this._loader.isExtensionUsed(hi)}dispose(){delete this.dracoDecoder,this._loader=null}_loadVertexDataAsync(e,n,o){return yr.LoadExtensionAsync(e,n,this.name,(s,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 s=r.attributes[e];if(null!=s&&(o._delayInfo=o._delayInfo||[],-1===o._delayInfo.indexOf(t)&&o._delayInfo.push(t),i[t]=s,this.useNormalizedFlagFromAccessor)){const o=gr.TryGet(this._loader.gltf.accessors,n.attributes[e]);o&&(a[t]=o.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=gr.Get(s,this._loader.gltf.bufferViews,r.bufferView);return u._dracoBabylonGeometry||(u._dracoBabylonGeometry=this._loader.loadBufferViewAsync(`/bufferViews/${u.index}`,u).then(s=>b(this,void 0,void 0,function*(){const r=this.dracoDecoder||t.DracoDecoder.Default,l=gr.TryGet(this._loader.gltf.accessors,n.attributes.POSITION),u=this._loader.parent.alwaysComputeBoundingBox||o.skeleton||!l?null:vr(l);return yield r._decodeMeshToGeometryForGltfAsync(o.name,this._loader.babylonScene,s,i,a,u).catch(t=>{throw new Error(`${e}: ${t.message}`)})}))),yield u._dracoBabylonGeometry}))}}let pi=!1;function mi(){pi||(pi=!0,Ys(hi),Xs(hi,!0,e=>new fi(e)))}var _i={__proto__:null,KHR_draco_mesh_compression:fi,RegisterKHR_draco_mesh_compression:mi};mi();const gi="KHR_gaussian_splatting",vi=.28209479177387814,yi=[0,3,5,7];function bi(e){return e<=0?0:e>=255?255:e+.5|0}class xi{constructor(e){this.name=gi,this._loader=e,this.enabled=this._loader.isExtensionUsed(gi)}dispose(){this._loader=null}_loadMeshPrimitiveAsync(e,n,o,s,r,i){return yr.LoadExtensionAsync(e,r,this.name,o=>b(this,void 0,void 0,function*(){if(null!=r.mode&&0!==r.mode)throw new Error(`${o}: Gaussian splatting primitives must use POINTS mode`);const s=this._loader,a=t=>{const n=r.attributes[t];if(null==n)return null;const o=gr.Get(`${e}/attributes/${t}`,s.gltf.accessors,n);return s._loadFloatAccessorAsync(`/accessors/${o.index}`,o)},l=a("POSITION");if(!l)throw new Error(`${o}: 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<yi[e];t++)c.push(`KHR_gaussian_splatting:SH_DEGREE_${e}_COEF_${t}`)}const d=s.babylonScene;d._blockEntityCollection=!!s._assetContainer;const h=new t.GaussianSplattingMesh(n,null,d);h._parentContainer=s._assetContainer,d._blockEntityCollection=!1,yr.AddPointerMetadata(h,e),s.parent.onMeshLoadedObservable.notifyObservers(h),i(h);const f=d.getEngine().getCaps(),[p,m,_,g,v,y,...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=p.length/3,T=y?y.length/x:0,A=new ArrayBuffer(32*x),M=new Float32Array(A),w=new Uint8Array(A);let S=null;if(u>0){const e=3*((u+1)*(u+1)-1),n=Math.ceil(e/16),o=f.maxTextureSize,s=Math.ceil(x/o);S=t.AllocateShBuffers(n,s*o*4*4)}for(let e=0;e<x;e++){const t=8*e,n=32*e,o=3*e;if(M[t+0]=p[o+0],M[t+1]=p[o+1],M[t+2]=p[o+2],M[t+3]=_?_[o+0]:1,M[t+4]=_?_[o+1]:1,M[t+5]=_?_[o+2]:1,v)w[n+24]=bi(255*(.5+vi*v[o+0])),w[n+25]=bi(255*(.5+vi*v[o+1])),w[n+26]=bi(255*(.5+vi*v[o+2]));else if(y){const t=e*T;w[n+24]=bi(255*y[t+0]),w[n+25]=bi(255*y[t+1]),w[n+26]=bi(255*y[t+2])}else w[n+24]=255,w[n+25]=255,w[n+26]=255;w[n+27]=g?bi(255*g[e]):y&&T>=4?bi(255*y[e*T+3]):255;const s=4*e,r=m?m[s+0]:0,i=m?m[s+1]:0,a=m?m[s+2]:0,l=m?m[s+3]:1;if(w[n+28]=bi(127.5*l+127.5),w[n+29]=bi(127.5*r+127.5),w[n+30]=bi(127.5*i+127.5),w[n+31]=bi(127.5*a+127.5),S){const t=16*e;for(let e=0;e<b.length;e++){const n=b[e];if(n)for(let s=0;s<3;s++){const r=3*e+s,i=15&r;S[r>>4][t+i]=bi(128*n[o+s]+128)}}}}return yield h.updateDataAsync(A,null!=S?S:void 0,void 0,u||void 0),h}))}}let Ti=!1;function Ai(){Ti||(Ti=!0,Ys(gi),Xs(gi,!0,e=>new xi(e)))}var Mi={__proto__:null,KHR_gaussian_splatting:xi,RegisterKHR_gaussian_splatting:Ai};Ai();const wi="KHR_lights_punctual";class Si{constructor(e){this.name=wi,this._loader=e,this.enabled=this._loader.isExtensionUsed(wi)}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,gr.Assign(this._lights)}}loadNodeAsync(e,n,o){return yr.LoadExtensionAsync(e,n,this.name,(s,r)=>b(this,void 0,void 0,function*(){return this._loader._allMaterialsDirtyRequired=!0,yield this._loader.loadNodeAsync(e,n,e=>{let n;const i=gr.Get(s,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(`${s}: 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),yr.AddPointerMetadata(n,s),o(e)})}))}}let Ci=!1;function Ri(){Ci||(Ci=!0,Ys(wi),Xs(wi,!0,e=>new Si(e)))}var Ii={__proto__:null,KHR_lights:Si,RegisterKHR_lights:Ri};Ri();const Oi="EXT_lights_area";class Fi{constructor(e){this.name=Oi,this._loader=e,this.enabled=this._loader.isExtensionUsed(Oi)}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,gr.Assign(this._lights)}}loadNodeAsync(e,n,o){return yr.LoadExtensionAsync(e,n,this.name,(s,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=gr.Get(s,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,o=u;i=new t.RectAreaLight(l,t.Vector3.Zero(),e,o,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(`${s}: 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),yr.AddPointerMetadata(i,s),o(e)})}))}}let Ei=!1;function Li(){Ei||(Ei=!0,Ys(Oi),Xs(Oi,!0,e=>new Fi(e)))}var Ni={__proto__:null,EXT_lights_area:Fi,RegisterEXT_lights_area:Li};Li();const ki="KHR_materials_pbrSpecularGlossiness";class Bi{constructor(e){this.name=ki,this.order=200,this._loader=e,this.enabled=this._loader.isExtensionUsed(ki)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yr.LoadExtensionAsync(e,t,this.name,(o,s)=>b(this,void 0,void 0,function*(){const r=new Array;return r.push(this._loader.loadMaterialBasePropertiesAsync(e,t,n)),r.push(this._loadSpecularGlossinessPropertiesAsync(o,s,n)),this._loader.loadMaterialAlphaProperties(e,t,n),yield Promise.all(r).then(()=>{})}))}_loadSpecularGlossinessPropertiesAsync(e,n,o){const s=this._loader._getOrCreateMaterialAdapter(o),r=new Array;return s.configureSpecularGlossiness(),n.diffuseFactor?(s.baseColor=t.Color3.FromArray(n.diffuseFactor),o.alpha=n.diffuseFactor[3]):s.baseColor=t.Color3.White(),s.specularColor=n.specularFactor?t.Color3.FromArray(n.specularFactor):t.Color3.White(),s.glossiness=null==n.glossinessFactor?1:n.glossinessFactor,n.diffuseTexture&&r.push(this._loader.loadTextureInfoAsync(`${e}/diffuseTexture`,n.diffuseTexture,e=>{e.name=`${o.name} (Diffuse)`,s.baseColorTexture=e})),n.specularGlossinessTexture&&r.push(this._loader.loadTextureInfoAsync(`${e}/specularGlossinessTexture`,n.specularGlossinessTexture,e=>{e.name=`${o.name} (Specular Glossiness)`,s.specularColorTexture=e})),Promise.all(r).then(()=>{})}}let Pi=!1;function Di(){Pi||(Pi=!0,Ys(ki),Xs(ki,!0,e=>new Bi(e)))}var Vi={__proto__:null,KHR_materials_pbrSpecularGlossiness:Bi,RegisterKHR_materials_pbrSpecularGlossiness:Di};Di();const Gi="KHR_materials_unlit";class $i{constructor(e){this.name=Gi,this.order=210,this._loader=e,this.enabled=this._loader.isExtensionUsed(Gi)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yr.LoadExtensionAsync(e,t,this.name,()=>b(this,void 0,void 0,function*(){return yield this._loadUnlitPropertiesAsync(e,t,n)}))}_loadUnlitPropertiesAsync(e,n,o){const s=this._loader._getOrCreateMaterialAdapter(o),r=new Array,i=n.pbrMetallicRoughness;return i&&(i.baseColorFactor&&(s.baseColor=t.Color3.FromArray(i.baseColorFactor),s.geometryOpacity=i.baseColorFactor[3]),i.baseColorTexture&&r.push(this._loader.loadTextureInfoAsync(`${e}/baseColorTexture`,i.baseColorTexture,e=>{e.name=`${o.name} (Base Color)`,s.baseColorTexture=e}))),s.isUnlit=!0,n.doubleSided&&(s.backFaceCulling=!1,s.twoSidedLighting=!0),this._loader.loadMaterialAlphaProperties(e,n,o),Promise.all(r).then(()=>{})}}let Ui=!1;function Hi(){Ui||(Ui=!0,Ys(Gi),Xs(Gi,!0,e=>new $i(e)))}var Ki={__proto__:null,KHR_materials_unlit:$i,RegisterKHR_materials_unlit:Hi};Hi();const Wi="KHR_materials_clearcoat";class qi{constructor(e){this.name=Wi,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(Wi)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yr.LoadExtensionAsync(e,t,this.name,(o,s)=>b(this,void 0,void 0,function*(){const r=new Array;r.push(this._loader.loadMaterialPropertiesAsync(e,t,n)),r.push(this._loadClearCoatPropertiesAsync(o,s,n)),yield Promise.all(r)}))}_loadClearCoatPropertiesAsync(e,t,n){const o=this._loader._getOrCreateMaterialAdapter(n),s=new Array;return o.configureCoat(),o.coatWeight=void 0!==t.clearcoatFactor?t.clearcoatFactor:0,o.coatRoughness=void 0!==t.clearcoatRoughnessFactor?t.clearcoatRoughnessFactor:0,t.clearcoatTexture&&s.push(this._loader.loadTextureInfoAsync(`${e}/clearcoatTexture`,t.clearcoatTexture,e=>{e.name=`${n.name} (ClearCoat)`,o.coatWeightTexture=e})),t.clearcoatRoughnessTexture&&(t.clearcoatRoughnessTexture.nonColorData=!0,s.push(this._loader.loadTextureInfoAsync(`${e}/clearcoatRoughnessTexture`,t.clearcoatRoughnessTexture,e=>{e.name=`${n.name} (ClearCoat Roughness)`,o.coatRoughnessTexture=e}))),t.clearcoatNormalTexture&&(t.clearcoatNormalTexture.nonColorData=!0,s.push(this._loader.loadTextureInfoAsync(`${e}/clearcoatNormalTexture`,t.clearcoatNormalTexture,e=>{var s;e.name=`${n.name} (ClearCoat Normal)`,o.geometryCoatNormalTexture=e,null!=(null===(s=t.clearcoatNormalTexture)||void 0===s?void 0:s.scale)&&(o.geometryCoatNormalTextureScale=t.clearcoatNormalTexture.scale)})),o.setNormalMapInversions(!n.getScene().useRightHandedSystem,n.getScene().useRightHandedSystem)),Promise.all(s).then(()=>{})}}let zi=!1;function ji(){zi||(zi=!0,Ys(Wi),Xs(Wi,!0,e=>new qi(e)))}var Xi={__proto__:null,KHR_materials_clearcoat:qi,RegisterKHR_materials_clearcoat:ji};ji();const Yi="KHR_materials_coat";class Qi{constructor(e){this.name=Yi,this.order=191,this.useOpenPBR=!1,this._loader=e,this.enabled=this._loader.isExtensionUsed(Yi)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yr.LoadExtensionAsync(e,t,this.name,(o,s)=>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(o,s,n)),yield Promise.all(r)}))}_loadCoatPropertiesAsync(e,n,o){var s,r;const i=this._loader._getOrCreateMaterialAdapter(o),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=`${o.name} (Coat)`,i.coatWeightTexture=e})),n.coatRoughnessTexture&&(n.coatRoughnessTexture.nonColorData=!0,a.push(this._loader.loadTextureInfoAsync(`${e}/coatRoughnessTexture`,n.coatRoughnessTexture,e=>{e.name=`${o.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=`${o.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(!o.getScene().useRightHandedSystem,o.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=`${o.name} (Coat Color)`,i.coatColorTexture=e}));const u=null!==(s=n.coatAnisotropyStrength)&&void 0!==s?s: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=`${o.name} (Coat Anisotropy)`,i.geometryCoatTangentTexture=e}))),Promise.all(a).then(()=>{})}}let Zi=!1;function Ji(){Zi||(Zi=!0,Ys(Yi),Xs(Yi,!0,e=>new Qi(e)))}var ea={__proto__:null,KHR_materials_coat:Qi,RegisterKHR_materials_coat:Ji};Ji();const ta="KHR_materials_iridescence";class na{constructor(e){this.name=ta,this.order=195,this._loader=e,this.enabled=this._loader.isExtensionUsed(ta)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yr.LoadExtensionAsync(e,t,this.name,(o,s)=>b(this,void 0,void 0,function*(){const r=new Array;return r.push(this._loader.loadMaterialPropertiesAsync(e,t,n)),r.push(this._loadIridescencePropertiesAsync(o,s,n)),yield Promise.all(r).then(()=>{})}))}_loadIridescencePropertiesAsync(e,t,n){var o,s,r,i,a;const l=this._loader._getOrCreateMaterialAdapter(n),u=new Array;return l.thinFilmWeight=null!==(o=t.iridescenceFactor)&&void 0!==o?o:0,l.thinFilmIor=null!==(r=null!==(s=t.iridescenceIor)&&void 0!==s?s: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(()=>{})}}let oa=!1;function sa(){oa||(oa=!0,Ys(ta),Xs(ta,!0,e=>new na(e)))}var ra={__proto__:null,KHR_materials_iridescence:na,RegisterKHR_materials_iridescence:sa};sa();const ia="KHR_materials_anisotropy";class aa{constructor(e){this.name=ia,this.order=195,this._loader=e,this.enabled=this._loader.isExtensionUsed(ia)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yr.LoadExtensionAsync(e,t,this.name,(o,s)=>b(this,void 0,void 0,function*(){const r=new Array;r.push(this._loader.loadMaterialPropertiesAsync(e,t,n)),r.push(this._loadAnisotropyPropertiesAsync(o,s,n)),yield Promise.all(r)}))}_loadAnisotropyPropertiesAsync(e,t,n){return b(this,void 0,void 0,function*(){var o,s,r;const i=this._loader._getOrCreateMaterialAdapter(n),a=new Array,l=null!==(o=t.anisotropyStrength)&&void 0!==o?o:0,u=null!==(s=t.anisotropyRotation)&&void 0!==s?s: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)})}}let la=!1;function ua(){la||(la=!0,Ys(ia),Xs(ia,!0,e=>new aa(e)))}var ca={__proto__:null,KHR_materials_anisotropy:aa,RegisterKHR_materials_anisotropy:ua};ua();const da="KHR_materials_emissive_strength";class ha{constructor(e){this.name=da,this.order=170,this._loader=e,this.enabled=this._loader.isExtensionUsed(da)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yr.LoadExtensionAsync(e,t,this.name,(o,s)=>b(this,void 0,void 0,function*(){return yield this._loader.loadMaterialPropertiesAsync(e,t,n),this._loadEmissiveProperties(o,s,n),yield Promise.resolve()}))}_loadEmissiveProperties(e,t,n){void 0!==t.emissiveStrength&&(this._loader._getOrCreateMaterialAdapter(n).emissionLuminance=t.emissiveStrength)}}let fa=!1;function pa(){fa||(fa=!0,Ys(da),Xs(da,!0,e=>new ha(e)))}var ma={__proto__:null,KHR_materials_emissive_strength:ha,RegisterKHR_materials_emissive_strength:pa};pa();const _a="KHR_materials_sheen";class ga{constructor(e){this.name=_a,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(_a)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yr.LoadExtensionAsync(e,t,this.name,(o,s)=>b(this,void 0,void 0,function*(){const r=new Array;return r.push(this._loader.loadMaterialPropertiesAsync(e,t,n)),r.push(this._loadSheenPropertiesAsync(o,s,n)),yield Promise.all(r).then(()=>{})}))}_loadSheenPropertiesAsync(e,n,o){const s=this._loader._getOrCreateMaterialAdapter(o),r=new Array;s.configureFuzz();const i=void 0!==n.sheenColorFactor?t.Color3.FromArray(n.sheenColorFactor):t.Color3.Black(),a=void 0!==n.sheenRoughnessFactor?n.sheenRoughnessFactor:0;return s.fuzzWeight=1,s.fuzzColor=i,s.fuzzRoughness=a,n.sheenColorTexture&&r.push(this._loader.loadTextureInfoAsync(`${e}/sheenColorTexture`,n.sheenColorTexture,e=>{e.name=`${o.name} (Sheen Color)`,s.fuzzColorTexture=e})),n.sheenRoughnessTexture&&(n.sheenRoughnessTexture.nonColorData=!0,r.push(this._loader.loadTextureInfoAsync(`${e}/sheenRoughnessTexture`,n.sheenRoughnessTexture,e=>{e.name=`${o.name} (Sheen Roughness)`,s.fuzzRoughnessTexture=e}))),Promise.all(r).then(()=>{})}}let va=!1;function ya(){va||(va=!0,Ys(_a),Xs(_a,!0,e=>new ga(e)))}var ba={__proto__:null,KHR_materials_sheen:ga,RegisterKHR_materials_sheen:ya};ya();const xa="KHR_materials_fuzz";class Ta{constructor(e){this.name=xa,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(xa)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yr.LoadExtensionAsync(e,t,this.name,(o,s)=>b(this,void 0,void 0,function*(){const r=new Array;return r.push(this._loader.loadMaterialPropertiesAsync(e,t,n)),r.push(this._loadFuzzPropertiesAsync(o,s,n)),yield Promise.all(r).then(()=>{})}))}_loadFuzzPropertiesAsync(e,n,o){const s=this._loader._getOrCreateMaterialAdapter(o),r=new Array;return s.configureFuzz(),s.fuzzWeight=void 0!==n.fuzzFactor?n.fuzzFactor:0,s.fuzzColor=void 0!==n.fuzzColorFactor?t.Color3.FromArray(n.fuzzColorFactor):t.Color3.White(),s.fuzzRoughness=void 0!==n.fuzzRoughnessFactor?n.fuzzRoughnessFactor:.5,n.fuzzTexture&&r.push(this._loader.loadTextureInfoAsync(`${e}/fuzzTexture`,n.fuzzTexture,e=>{e.name=`${o.name} (Fuzz)`,s.fuzzWeightTexture=e})),n.fuzzColorTexture&&r.push(this._loader.loadTextureInfoAsync(`${e}/fuzzColorTexture`,n.fuzzColorTexture,e=>{e.name=`${o.name} (Fuzz Color)`,s.fuzzColorTexture=e})),n.fuzzRoughnessTexture&&(n.fuzzRoughnessTexture.nonColorData=!0,r.push(this._loader.loadTextureInfoAsync(`${e}/fuzzRoughnessTexture`,n.fuzzRoughnessTexture,e=>{e.name=`${o.name} (Fuzz Roughness)`,s.fuzzRoughnessTexture=e}))),Promise.all(r).then(()=>{})}}let Aa=!1;function Ma(){Aa||(Aa=!0,Ys(xa),Xs(xa,!0,e=>new Ta(e)))}var wa={__proto__:null,KHR_materials_fuzz:Ta,RegisterKHR_materials_fuzz:Ma};Ma();const Sa="KHR_materials_specular";class Ca{constructor(e){this.name=Sa,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(Sa)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yr.LoadExtensionAsync(e,t,this.name,(o,s)=>b(this,void 0,void 0,function*(){const r=new Array;r.push(this._loader.loadMaterialPropertiesAsync(e,t,n)),r.push(this._loadSpecularPropertiesAsync(o,s,n));const i=this._loader._getOrCreateMaterialAdapter(n);return s.extensions&&s.extensions.EXT_materials_specular_edge_color&&s.extensions.EXT_materials_specular_edge_color.specularEdgeColorEnabled&&i.enableSpecularEdgeColor(!0),yield Promise.all(r).then(()=>{})}))}_loadSpecularPropertiesAsync(e,n,o){var s;const r=this._loader._getOrCreateMaterialAdapter(o),i=new Array;return r.specularWeight=null!==(s=n.specularFactor)&&void 0!==s?s: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=`${o.name} (Specular)`,r.specularWeightTexture=e}))),n.specularColorTexture&&i.push(this._loader.loadTextureInfoAsync(`${e}/specularColorTexture`,n.specularColorTexture,e=>{e.name=`${o.name} (Specular Color)`,r.specularColorTexture=e})),Promise.all(i).then(()=>{})}}let Ra=!1;function Ia(){Ra||(Ra=!0,Ys(Sa),Xs(Sa,!0,e=>new Ca(e)))}var Oa={__proto__:null,KHR_materials_specular:Ca,RegisterKHR_materials_specular:Ia};Ia();const Fa="KHR_materials_ior";class Ea{constructor(e){this.name=Fa,this.order=180,this._loader=e,this.enabled=this._loader.isExtensionUsed(Fa)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yr.LoadExtensionAsync(e,t,this.name,(o,s)=>b(this,void 0,void 0,function*(){const r=new Array;return r.push(this._loader.loadMaterialPropertiesAsync(e,t,n)),r.push(this._loadIorPropertiesAsync(o,s,n)),yield Promise.all(r).then(()=>{})}))}_loadIorPropertiesAsync(e,t,n){const o=this._loader._getOrCreateMaterialAdapter(n),s=void 0!==t.ior?t.ior:Ea._DEFAULT_IOR;return o.specularIor=s,Promise.resolve()}}Ea._DEFAULT_IOR=1.5;let La=!1;function Na(){La||(La=!0,Ys(Fa),Xs(Fa,!0,e=>new Ea(e)))}var ka={__proto__:null,KHR_materials_ior:Ea,RegisterKHR_materials_ior:Na};Na();const Ba="KHR_materials_variants";class Pa{constructor(e){this.name=Ba,this._loader=e,this.enabled=this._loader.isExtensionUsed(Ba)&&!this._loader.parent.skipMaterials}dispose(){this._loader=null}static GetAvailableVariants(e){const t=this._GetExtensionMetadata(e);return t?Object.keys(t.variants):[]}getAvailableVariants(e){return Pa.GetAvailableVariants(e)}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 ${Ba} extension`);const o=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)o(e);else o(t);n.lastSelected=t}selectVariant(e,t){Pa.SelectVariant(e,t)}static Reset(e){const t=this._GetExtensionMetadata(e);if(!t)throw new Error(`Cannot reset on a glTF mesh that does not have the ${Ba} extension`);for(const e of t.original)e.mesh.material=e.material;t.lastSelected=null}reset(e){Pa.Reset(e)}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 ${Ba} extension`);return t.lastSelected}getLastSelectedVariant(e){return Pa.GetLastSelectedVariant(e)}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[Ba])||null}onLoading(){const e=this._loader.gltf.extensions;if(e&&e[this.name]){const t=e[this.name];this._variants=t.variants}}onReady(){var e;const t=this._loader.rootBabylonMesh;if(t){const n=this._loader.parent.extensionOptions[Ba];(null==n?void 0:n.defaultVariant)&&Pa.SelectVariant(t,n.defaultVariant),null===(e=null==n?void 0:n.onLoaded)||void 0===e||e.call(n,{get variants(){return Pa.GetAvailableVariants(t)},get selectedVariant(){const e=Pa.GetLastSelectedVariant(t);return e?Array.isArray(e)?e[0]:e:Pa.GetAvailableVariants(t)[0]},set selectedVariant(e){Pa.SelectVariant(t,e)}})}}_loadMeshPrimitiveAsync(e,n,o,s,r,i){return yr.LoadExtensionAsync(e,r,this.name,(a,l)=>b(this,void 0,void 0,function*(){const u=new Array;return u.push(this._loader._loadMeshPrimitiveAsync(e,n,o,s,r,n=>{if(i(n),n instanceof t.Mesh){const t=yr._GetDrawMode(e,r.mode),o=this._loader.rootBabylonMesh,s=o?o._internalMetadata=o._internalMetadata||{}:{},i=s.gltf=s.gltf||{},c=i[Ba]=i[Ba]||{lastSelected:null,original:[],variants:{}};c.original.push({mesh:n,material:n.material});for(let e=0;e<l.mappings.length;++e){const s=l.mappings[e],r=gr.Get(`${a}/mappings/${e}/material`,this._loader.gltf.materials,s.material);u.push(this._loader._loadMaterialAsync(`#/materials/${s.material}`,r,n,t,e=>{for(let t=0;t<s.variants.length;++t){const r=s.variants[t],i=gr.Get(`/extensions/${Ba}/variants/${r}`,this._variants,r);c.variants[i.name]=c.variants[i.name]||[],c.variants[i.name].push({mesh:n,material:e}),n.onClonedObservable.add(e=>{const t=e;let s,r=t;do{if(r=r.parent,!r)return;s=Pa._GetExtensionMetadata(r)}while(null===s);if(o&&s===Pa._GetExtensionMetadata(o)){r._internalMetadata={};for(const e in o._internalMetadata)r._internalMetadata[e]=o._internalMetadata[e];r._internalMetadata.gltf=[];for(const e in o._internalMetadata.gltf)r._internalMetadata.gltf[e]=o._internalMetadata.gltf[e];r._internalMetadata.gltf[Ba]={lastSelected:null,original:[],variants:{}};for(const e of s.original)r._internalMetadata.gltf[Ba].original.push({mesh:e.mesh,material:e.material});for(const e in s.variants)if(Object.prototype.hasOwnProperty.call(s.variants,e)){r._internalMetadata.gltf[Ba].variants[e]=[];for(const t of s.variants[e])r._internalMetadata.gltf[Ba].variants[e].push({mesh:t.mesh,material:t.material})}s=r._internalMetadata.gltf[Ba]}for(const e of s.original)e.mesh===n&&(e.mesh=t);for(const e of s.variants[i.name])e.mesh===n&&(e.mesh=t)})}}))}}})),yield Promise.all(u).then(([e])=>e)}))}}let Da=!1;function Va(){Da||(Da=!0,Ys(Ba),Xs(Ba,!0,e=>new Pa(e)))}var Ga={__proto__:null,KHR_materials_variants:Pa,RegisterKHR_materials_variants:Va};Va();class $a{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({},$a._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 o=!1,s=!1;const r=new Set;for(let e=0;e<n.subMaterials.length;e++){const t=n.subMaterials[e];if(!t){s=!0;continue}const i=this._getOrCreateAdapter(t);i&&i.isTranslucent()?(i.refractionBackgroundTexture=this._opaqueRenderTarget,o=!0,r.add(e)):s=!0}return o&&s?(this._translucentMaterialIndices.set(e,r),this._rebuildOpaqueOnlySubMeshes(e,r),"mixed"):(this._translucentMaterialIndices.delete(e),this._opaqueOnlySubMeshes.delete(e),o?"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 o;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=>{o=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=o;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 s=this._translucentMaterialIndices.entries();for(let e=s.next();!e.done;e=s.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 Ua(e,t){if(e.parent.dontUseTransmissionHelper)return;const n=t.getScene()._transmissionHelper,o=null!=n?n:new $a({},t.getScene());for(const t of Array.from(e._pbrMaterialImpls.values()))o.addMaterialImpl(t);n&&!n._isRenderTargetValid()&&n._setupRenderTargets()}const Ha="KHR_materials_transmission";class Ka{constructor(e){this.name=Ha,this.order=175,this._loader=e,this.enabled=this._loader.isExtensionUsed(Ha),this.enabled&&(e.parent.transparencyAsCoverage=!0)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yr.LoadExtensionAsync(e,t,this.name,(o,s)=>b(this,void 0,void 0,function*(){const r=new Array;return r.push(this._loader.loadMaterialPropertiesAsync(e,t,n)),r.push(this._loadTransparentPropertiesAsync(o,t,n,s)),yield Promise.all(r).then(()=>{})}))}_loadTransparentPropertiesAsync(e,t,n,o){const s=this._loader._getOrCreateMaterialAdapter(n),r=void 0!==o.transmissionFactor?o.transmissionFactor:0;if(0===r||!s)return Promise.resolve();s.configureTransmission(),s.transmissionWeight=r,r>0&&Ua(this._loader,n);let i=Promise.resolve(null);return o.transmissionTexture&&(o.transmissionTexture.nonColorData=!0,i=this._loader.loadTextureInfoAsync(`${e}/transmissionTexture`,o.transmissionTexture,e=>{e.name=`${n.name} (Transmission)`,s.transmissionWeightTexture=e})),i.then(()=>{})}}let Wa=!1;function qa(){Wa||(Wa=!0,Ys(Ha),Xs(Ha,!0,e=>new Ka(e)))}var za={__proto__:null,KHR_materials_transmission:Ka,RegisterKHR_materials_transmission:qa};qa();const ja="KHR_materials_diffuse_transmission";class Xa{constructor(e){this.name=ja,this.order=174,this._loader=e,this.enabled=this._loader.isExtensionUsed(ja),this.enabled&&(e.parent.transparencyAsCoverage=!0)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yr.LoadExtensionAsync(e,t,this.name,(o,s)=>b(this,void 0,void 0,function*(){const r=new Array;return r.push(this._loader.loadMaterialPropertiesAsync(e,t,n)),r.push(this._loadTranslucentPropertiesAsync(o,t,n,s)),yield Promise.all(r).then(()=>{})}))}_loadTranslucentPropertiesAsync(e,n,o,s){var r;const i=this._loader._getOrCreateMaterialAdapter(o);i.configureSubsurface(),i.subsurfaceWeight=null!==(r=s.diffuseTransmissionFactor)&&void 0!==r?r:0,i.subsurfaceWeight>0&&Ua(this._loader,o),i.diffuseTransmissionTint=void 0!==s.diffuseTransmissionColorFactor?t.Color3.FromArray(s.diffuseTransmissionColorFactor):t.Color3.White();const a=new Array;return s.diffuseTransmissionTexture&&(s.diffuseTransmissionTexture.nonColorData=!0,a.push(this._loader.loadTextureInfoAsync(`${e}/diffuseTransmissionTexture`,s.diffuseTransmissionTexture).then(e=>{e.name=`${o.name} (Diffuse Transmission)`,i.subsurfaceWeightTexture=e}))),s.diffuseTransmissionColorTexture&&a.push(this._loader.loadTextureInfoAsync(`${e}/diffuseTransmissionColorTexture`,s.diffuseTransmissionColorTexture).then(e=>{e.name=`${o.name} (Diffuse Transmission Color)`,i.diffuseTransmissionTintTexture=e})),Promise.all(a).then(()=>{})}}let Ya=!1;function Qa(){Ya||(Ya=!0,Ys(ja),Xs(ja,!0,e=>new Xa(e)))}var Za={__proto__:null,KHR_materials_diffuse_transmission:Xa,RegisterKHR_materials_diffuse_transmission:Qa};Qa();const Ja="KHR_materials_volume";class el{constructor(e){this.name=Ja,this.order=173,this._loader=e,this.enabled=this._loader.isExtensionUsed(Ja),this.enabled&&this._loader._disableInstancedMesh++}dispose(){this.enabled&&this._loader._disableInstancedMesh--,this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yr.LoadExtensionAsync(e,t,this.name,(o,s)=>b(this,void 0,void 0,function*(){const r=new Array;return r.push(this._loader.loadMaterialPropertiesAsync(e,t,n)),r.push(this._loadVolumePropertiesAsync(o,t,n,s)),yield Promise.all(r).then(()=>{})}))}_loadVolumePropertiesAsync(e,n,o,s){var r;const i=this._loader._getOrCreateMaterialAdapter(o);if(0===i.transmissionWeight&&0===i.subsurfaceWeight||!s.thicknessFactor)return Promise.resolve();i.geometryThinWalled=!1;const a=void 0!==s.attenuationDistance?s.attenuationDistance:Number.MAX_VALUE,l=void 0!==s.attenuationColor&&3==s.attenuationColor.length?t.Color3.FromArray(s.attenuationColor):t.Color3.White();i.configureVolume(),i.transmissionColor=l,i.transmissionDepth=a,i.volumeThickness=null!==(r=s.thicknessFactor)&&void 0!==r?r:0;const u=new Array;return s.thicknessTexture&&(s.thicknessTexture.nonColorData=!0,u.push(this._loader.loadTextureInfoAsync(`${e}/thicknessTexture`,s.thicknessTexture,e=>{e.name=`${o.name} (Thickness)`,i.volumeThicknessTexture=e}))),Promise.all(u).then(()=>{})}}let tl=!1;function nl(){tl||(tl=!0,Ys(Ja),Xs(Ja,!0,e=>new el(e)))}var ol={__proto__:null,KHR_materials_volume:el,RegisterKHR_materials_volume:nl};nl();const sl="KHR_materials_volume_scatter";class rl{constructor(e){this.name=sl,this.order=172,this._loader=e,this.enabled=this._loader.isExtensionUsed(sl),this.enabled&&this._loader._disableInstancedMesh++}dispose(){this.enabled&&this._loader._disableInstancedMesh--,this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yr.LoadExtensionAsync(e,t,this.name,(o,s)=>b(this,void 0,void 0,function*(){const r=new Array;return r.push(this._loader.loadMaterialPropertiesAsync(e,t,n)),r.push(this._loadVolumePropertiesAsync(o,t,n,s)),yield Promise.all(r).then(()=>{})}))}_loadVolumePropertiesAsync(e,n,o,s){const r=this._loader._getOrCreateMaterialAdapter(o);if(0===r.transmissionWeight&&0===r.subsurfaceWeight||r.geometryThinWalled)return Promise.resolve();const i=void 0!==s.multiscatterColorFactor&&3==s.multiscatterColorFactor.length?t.Color3.FromArray(s.multiscatterColorFactor):t.Color3.Black(),a=void 0!==s.scatterAnisotropy?s.scatterAnisotropy:0;let l=Promise.resolve(null);s.multiscatterColorTexture&&(s.multiscatterColorTexture.nonColorData=!0,l=this._loader.loadTextureInfoAsync(`${e}/multiscatterColorTexture`,s.multiscatterColorTexture,e=>{e.name=`${o.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),o=new t.Vector3(4.09712,4.09712,4.09712);o.addInPlace(new t.Vector3(4.20863,4.20863,4.20863).multiplyInPlace(n));const s=new t.Vector3(9.59217,9.59217,9.59217);return s.addInPlace(new t.Vector3(41.6808,41.6808,41.6808).multiplyInPlace(n)),s.addInPlace(new t.Vector3(17.7126,17.7126,17.7126).multiplyInPlace(n.multiply(n))),o.subtractInPlace(new t.Vector3(Math.sqrt(s.x),Math.sqrt(s.y),Math.sqrt(s.z))),new t.Vector3(1,1,1).subtract(o.multiply(o))}(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(()=>{})}}let il=!1;function al(){il||(il=!0,Ys(sl),Xs(sl,!0,e=>new rl(e)))}var ll={__proto__:null,KHR_materials_volume_scatter:rl,RegisterKHR_materials_volume_scatter:al};al();const ul="KHR_materials_dispersion";class cl{constructor(e){this.name=ul,this.order=174,this._loader=e,this.enabled=this._loader.isExtensionUsed(ul)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yr.LoadExtensionAsync(e,t,this.name,(o,s)=>b(this,void 0,void 0,function*(){const r=new Array;return r.push(this._loader.loadMaterialPropertiesAsync(e,t,n)),r.push(this._loadDispersionPropertiesAsync(o,t,n,s)),yield Promise.all(r).then(()=>{})}))}_loadDispersionPropertiesAsync(e,t,n,o){const s=this._loader._getOrCreateMaterialAdapter(n);return 0!=s.transmissionWeight&&o.dispersion?(s.transmissionDispersionAbbeNumber=20,s.transmissionDispersionScale=o.dispersion,Promise.resolve()):Promise.resolve()}}let dl=!1;function hl(){dl||(dl=!0,Ys(ul),Xs(ul,!0,e=>new cl(e)))}var fl={__proto__:null,KHR_materials_dispersion:cl,RegisterKHR_materials_dispersion:hl};hl();const pl="KHR_materials_diffuse_roughness";class ml{constructor(e){this.name=pl,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(pl)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yr.LoadExtensionAsync(e,t,this.name,(o,s)=>b(this,void 0,void 0,function*(){const r=new Array;return r.push(this._loader.loadMaterialPropertiesAsync(e,t,n)),r.push(this._loadDiffuseRoughnessPropertiesAsync(o,s,n)),yield Promise.all(r).then(()=>{})}))}_loadDiffuseRoughnessPropertiesAsync(e,t,n){var o;const s=this._loader._getOrCreateMaterialAdapter(n),r=new Array;return s.baseDiffuseRoughness=null!==(o=t.diffuseRoughnessFactor)&&void 0!==o?o:0,t.diffuseRoughnessTexture&&r.push(this._loader.loadTextureInfoAsync(`${e}/diffuseRoughnessTexture`,t.diffuseRoughnessTexture,e=>{e.name=`${n.name} (Diffuse Roughness)`,s.baseDiffuseRoughnessTexture=e})),Promise.all(r).then(()=>{})}}let _l=!1;function gl(){_l||(_l=!0,Ys(pl),Xs(pl,!0,e=>new ml(e)))}var vl={__proto__:null,KHR_materials_diffuse_roughness:ml,RegisterKHR_materials_diffuse_roughness:gl};gl();const yl="KHR_mesh_quantization";class bl{constructor(e){this.name=yl,this.enabled=e.isExtensionUsed(yl)}dispose(){}}let xl=!1;function Tl(){xl||(xl=!0,Ys(yl),Xs(yl,!0,e=>new bl(e)))}var Al={__proto__:null,KHR_mesh_quantization:bl,RegisterKHR_mesh_quantization:Tl};Tl();const Ml="KHR_texture_basisu";class wl{constructor(e){this.name=Ml,this._loader=e,this.enabled=e.isExtensionUsed(Ml)}dispose(){this._loader=null}_loadTextureAsync(e,t,n){return yr.LoadExtensionAsync(e,t,this.name,(o,s)=>b(this,void 0,void 0,function*(){const r=null==t.sampler?yr.DefaultSampler:gr.Get(`${e}/sampler`,this._loader.gltf.samplers,t.sampler),i=gr.Get(`${o}/source`,this._loader.gltf.images,s.source);return yield this._loader._createTextureAsync(e,r,i,e=>{n(e)},t._textureInfo.nonColorData?{useRGBAIfASTCBC7NotAvailableWhenUASTC:!0}:void 0,!t._textureInfo.nonColorData)}))}}let Sl=!1;function Cl(){Sl||(Sl=!0,Ys(Ml),Xs(Ml,!0,e=>new wl(e)))}var Rl={__proto__:null,KHR_texture_basisu:wl,RegisterKHR_texture_basisu:Cl};Cl();const Il="KHR_texture_transform";class Ol{constructor(e){this.name=Il,this._loader=e,this.enabled=this._loader.isExtensionUsed(Il)}dispose(){this._loader=null}loadTextureInfoAsync(e,n,o){return yr.LoadExtensionAsync(e,n,this.name,(s,r)=>b(this,void 0,void 0,function*(){return yield this._loader.loadTextureInfoAsync(e,n,e=>{if(!(e instanceof t.Texture))throw new Error(`${s}: 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),o(e)})}))}}let Fl=!1;function El(){Fl||(Fl=!0,Ys(Il),Xs(Il,!0,e=>new Ol(e)))}var Ll={__proto__:null,KHR_texture_transform:Ol,RegisterKHR_texture_transform:El};El();const Nl="KHR_xmp_json_ld";class kl{constructor(e){this.name=Nl,this.order=100,this._loader=e,this.enabled=this._loader.isExtensionUsed(Nl)}dispose(){this._loader=null}onLoading(){var e,t,n;if(null===this._loader.rootBabylonMesh)return;const o=null===(e=this._loader.gltf.extensions)||void 0===e?void 0:e.KHR_xmp_json_ld,s=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(o&&s){const e=+s.packet;o.packets&&e<o.packets.length&&(this._loader.rootBabylonMesh.metadata=this._loader.rootBabylonMesh.metadata||{},this._loader.rootBabylonMesh.metadata.xmp=o.packets[e])}}}let Bl=!1;function Pl(){Bl||(Bl=!0,Ys(Nl),Xs(Nl,!0,e=>new kl(e)))}var Dl={__proto__:null,KHR_xmp_json_ld:kl,RegisterKHR_xmp_json_ld:Pl};Pl();const Vl="KHR_animation_pointer";class Gl{constructor(e){this.name=Vl,this._loader=e,this._pathToObjectConverter=dr(this._loader.gltf)}get enabled(){return this._loader.isExtensionUsed(Vl)}dispose(){this._loader=null,delete this._pathToObjectConverter}_loadAnimationChannelAsync(e,n,o,s,r){var i;const a=null===(i=s.target.extensions)||void 0===i?void 0:i.KHR_animation_pointer;if(!a||!this._pathToObjectConverter)return null;"pointer"!==s.target.path&&t.Logger.Warn(`${e}/target/path: Value (${s.target.path}) must be (pointer) when using the ${this.name} extension`),null!=s.target.node&&t.Logger.Warn(`${e}/target/node: Value (${s.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,o,s,{object:t.object,info:t.info.interpolation},r)}catch(e){return t.Logger.Warn(`${l}/pointer: Invalid pointer (${u}) skipped`),null}}}let $l=!1;function Ul(){$l||($l=!0,Ys(Vl),Xs(Vl,!0,e=>new Gl(e)))}var Hl={__proto__:null,KHR_animation_pointer:Gl,RegisterKHR_animation_pointer:Ul};function Kl(e,n,o,s){return t.Color3.FromArray(n,o).scale(s)}function Wl(e,t,n,o){return t[n+3]*o}function ql(e,t,n,o){return t[n]*o}function zl(e,t,n,o){return-t[n]*o}function jl(e,t,n,o){return t[n+1]*o}function Xl(e,t,n,o){return t[n]*o*2}function Yl(e){return{scale:[new Zl(t.Animation.ANIMATIONTYPE_FLOAT,`${e}.uScale`,ql,()=>2),new Zl(t.Animation.ANIMATIONTYPE_FLOAT,`${e}.vScale`,jl,()=>2)],offset:[new Zl(t.Animation.ANIMATIONTYPE_FLOAT,`${e}.uOffset`,ql,()=>2),new Zl(t.Animation.ANIMATIONTYPE_FLOAT,`${e}.vOffset`,jl,()=>2)],rotation:[new Zl(t.Animation.ANIMATIONTYPE_FLOAT,`${e}.wAng`,zl,()=>1)]}}class Ql extends Sr{buildAnimations(e,t,n,o){return[{babylonAnimatable:e._babylonCamera,babylonAnimation:this._buildAnimation(t,n,o)}]}}class Zl extends Sr{buildAnimations(e,t,n,o){const s=[];for(const r in e._data)s.push({babylonAnimatable:e._data[r].babylonMaterial,babylonAnimation:this._buildAnimation(t,n,o)});return s}}class Jl extends Sr{buildAnimations(e,t,n,o){return[{babylonAnimatable:e._babylonLight,babylonAnimation:this._buildAnimation(t,n,o)}]}}class eu extends Sr{buildAnimations(e,t,n,o){return e._primitiveBabylonMeshes?e._primitiveBabylonMeshes.map(e=>({babylonAnimatable:e,babylonAnimation:this._buildAnimation(t,n,o)})):[]}}let tu=!1;function nu(){if(tu)return;tu=!0,Or(),fr("/cameras/{}/orthographic/xmag",[new Ql(t.Animation.ANIMATIONTYPE_FLOAT,"orthoLeft",zl,()=>1),new Ql(t.Animation.ANIMATIONTYPE_FLOAT,"orthoRight",jl,()=>1)]),fr("/cameras/{}/orthographic/ymag",[new Ql(t.Animation.ANIMATIONTYPE_FLOAT,"orthoBottom",zl,()=>1),new Ql(t.Animation.ANIMATIONTYPE_FLOAT,"orthoTop",jl,()=>1)]),fr("/cameras/{}/orthographic/zfar",[new Ql(t.Animation.ANIMATIONTYPE_FLOAT,"maxZ",ql,()=>1)]),fr("/cameras/{}/orthographic/znear",[new Ql(t.Animation.ANIMATIONTYPE_FLOAT,"minZ",ql,()=>1)]),fr("/cameras/{}/perspective/yfov",[new Ql(t.Animation.ANIMATIONTYPE_FLOAT,"fov",ql,()=>1)]),fr("/cameras/{}/perspective/zfar",[new Ql(t.Animation.ANIMATIONTYPE_FLOAT,"maxZ",ql,()=>1)]),fr("/cameras/{}/perspective/znear",[new Ql(t.Animation.ANIMATIONTYPE_FLOAT,"minZ",ql,()=>1)]),fr("/materials/{}/pbrMetallicRoughness/baseColorFactor",[new Zl(t.Animation.ANIMATIONTYPE_COLOR3,"albedoColor",Kl,()=>4),new Zl(t.Animation.ANIMATIONTYPE_FLOAT,"alpha",Wl,()=>4)]),fr("/materials/{}/pbrMetallicRoughness/metallicFactor",[new Zl(t.Animation.ANIMATIONTYPE_FLOAT,"metallic",ql,()=>1)]),fr("/materials/{}/pbrMetallicRoughness/metallicFactor",[new Zl(t.Animation.ANIMATIONTYPE_FLOAT,"roughness",ql,()=>1)]);const e=Yl("albedoTexture");fr("/materials/{}/pbrMetallicRoughness/baseColorTexture/extensions/KHR_texture_transform/scale",e.scale),fr("/materials/{}/pbrMetallicRoughness/baseColorTexture/extensions/KHR_texture_transform/offset",e.offset),fr("/materials/{}/pbrMetallicRoughness/baseColorTexture/extensions/KHR_texture_transform/rotation",e.rotation);const n=Yl("metallicTexture");fr("//materials/{}/pbrMetallicRoughness/metallicRoughnessTexture/scale",n.scale),fr("//materials/{}/pbrMetallicRoughness/metallicRoughnessTexture/offset",n.offset),fr("//materials/{}/pbrMetallicRoughness/metallicRoughnessTexture/rotation",n.rotation),fr("/materials/{}/emissiveFactor",[new Zl(t.Animation.ANIMATIONTYPE_COLOR3,"emissiveColor",Kl,()=>3)]);const o=Yl("bumpTexture");fr("/materials/{}/normalTexture/scale",[new Zl(t.Animation.ANIMATIONTYPE_FLOAT,"bumpTexture.level",ql,()=>1)]),fr("/materials/{}/normalTexture/extensions/KHR_texture_transform/scale",o.scale),fr("/materials/{}/normalTexture/extensions/KHR_texture_transform/offset",o.offset),fr("/materials/{}/normalTexture/extensions/KHR_texture_transform/rotation",o.rotation),fr("/materials/{}/occlusionTexture/strength",[new Zl(t.Animation.ANIMATIONTYPE_FLOAT,"ambientTextureStrength",ql,()=>1)]);const s=Yl("ambientTexture");fr("/materials/{}/occlusionTexture/extensions/KHR_texture_transform/scale",s.scale),fr("/materials/{}/occlusionTexture/extensions/KHR_texture_transform/offset",s.offset),fr("/materials/{}/occlusionTexture/extensions/KHR_texture_transform/rotation",s.rotation);const r=Yl("emissiveTexture");fr("/materials/{}/emissiveTexture/extensions/KHR_texture_transform/scale",r.scale),fr("/materials/{}/emissiveTexture/extensions/KHR_texture_transform/offset",r.offset),fr("/materials/{}/emissiveTexture/extensions/KHR_texture_transform/rotation",r.rotation),fr("/materials/{}/extensions/KHR_materials_anisotropy/anisotropyStrength",[new Zl(t.Animation.ANIMATIONTYPE_FLOAT,"anisotropy.intensity",ql,()=>1)]),fr("/materials/{}/extensions/KHR_materials_anisotropy/anisotropyRotation",[new Zl(t.Animation.ANIMATIONTYPE_FLOAT,"anisotropy.angle",ql,()=>1)]);const i=Yl("anisotropy.texture");fr("/materials/{}/extensions/KHR_materials_anisotropy/anisotropyTexture/extensions/KHR_texture_transform/scale",i.scale),fr("/materials/{}/extensions/KHR_materials_anisotropy/anisotropyTexture/extensions/KHR_texture_transform/offset",i.offset),fr("/materials/{}/extensions/KHR_materials_anisotropy/anisotropyTexture/extensions/KHR_texture_transform/rotation",i.rotation),fr("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatFactor",[new Zl(t.Animation.ANIMATIONTYPE_FLOAT,"clearCoat.intensity",ql,()=>1)]),fr("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatRoughnessFactor",[new Zl(t.Animation.ANIMATIONTYPE_FLOAT,"clearCoat.roughness",ql,()=>1)]);const a=Yl("clearCoat.texture");fr("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatTexture/extensions/KHR_texture_transform/scale",a.scale),fr("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatTexture/extensions/KHR_texture_transform/offset",a.offset),fr("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatTexture/extensions/KHR_texture_transform/rotation",a.rotation);const l=Yl("clearCoat.bumpTexture");fr("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatNormalTexture/scale",[new Zl(t.Animation.ANIMATIONTYPE_FLOAT,"clearCoat.bumpTexture.level",ql,()=>1)]),fr("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatNormalTexture/extensions/KHR_texture_transform/scale",l.scale),fr("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatNormalTexture/extensions/KHR_texture_transform/offset",l.offset),fr("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatNormalTexture/extensions/KHR_texture_transform/rotation",l.rotation);const u=Yl("clearCoat.textureRoughness");fr("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatRoughnessTexture/extensions/KHR_texture_transform/scale",u.scale),fr("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatRoughnessTexture/extensions/KHR_texture_transform/offset",u.offset),fr("/materials/{}/extensions/KHR_materials_clearcoat/clearcoatRoughnessTexture/extensions/KHR_texture_transform/rotation",u.rotation),fr("/materials/{}/extensions/KHR_materials_dispersion/dispersionFactor",[new Zl(t.Animation.ANIMATIONTYPE_FLOAT,"subSurface.dispersion",ql,()=>1)]),fr("/materials/{}/extensions/KHR_materials_emissive_strength/emissiveStrength",[new Zl(t.Animation.ANIMATIONTYPE_FLOAT,"emissiveIntensity",ql,()=>1)]),fr("/materials/{}/extensions/KHR_materials_ior/ior",[new Zl(t.Animation.ANIMATIONTYPE_FLOAT,"indexOfRefraction",ql,()=>1)]),fr("/materials/{}/extensions/KHR_materials_iridescence/iridescenceFactor",[new Zl(t.Animation.ANIMATIONTYPE_FLOAT,"iridescence.intensity",ql,()=>1)]),fr("/materials/{}/extensions/KHR_materials_iridescence/iridescenceIor",[new Zl(t.Animation.ANIMATIONTYPE_FLOAT,"iridescence.indexOfRefraction",ql,()=>1)]),fr("/materials/{}/extensions/KHR_materials_iridescence/iridescenceThicknessMinimum",[new Zl(t.Animation.ANIMATIONTYPE_FLOAT,"iridescence.minimumThickness",ql,()=>1)]),fr("/materials/{}/extensions/KHR_materials_iridescence/iridescenceThicknessMaximum",[new Zl(t.Animation.ANIMATIONTYPE_FLOAT,"iridescence.maximumThickness",ql,()=>1)]);const c=Yl("iridescence.texture");fr("/materials/{}/extensions/KHR_materials_iridescence/iridescenceTexture/extensions/KHR_texture_transform/scale",c.scale),fr("/materials/{}/extensions/KHR_materials_iridescence/iridescenceTexture/extensions/KHR_texture_transform/offset",c.offset),fr("/materials/{}/extensions/KHR_materials_iridescence/iridescenceTexture/extensions/KHR_texture_transform/rotation",c.rotation);const d=Yl("iridescence.thicknessTexture");fr("/materials/{}/extensions/KHR_materials_iridescence/iridescenceThicknessTexture/extensions/KHR_texture_transform/scale",d.scale),fr("/materials/{}/extensions/KHR_materials_iridescence/iridescenceThicknessTexture/extensions/KHR_texture_transform/offset",d.offset),fr("/materials/{}/extensions/KHR_materials_iridescence/iridescenceThicknessTexture/extensions/KHR_texture_transform/rotation",d.rotation),fr("/materials/{}/extensions/KHR_materials_sheen/sheenColorFactor",[new Zl(t.Animation.ANIMATIONTYPE_COLOR3,"sheen.color",Kl,()=>3)]),fr("/materials/{}/extensions/KHR_materials_sheen/sheenRoughnessFactor",[new Zl(t.Animation.ANIMATIONTYPE_FLOAT,"sheen.roughness",ql,()=>1)]);const h=Yl("sheen.texture");fr("/materials/{}/extensions/KHR_materials_sheen/sheenColorTexture/extensions/KHR_texture_transform/scale",h.scale),fr("/materials/{}/extensions/KHR_materials_sheen/sheenColorTexture/extensions/KHR_texture_transform/offset",h.offset),fr("/materials/{}/extensions/KHR_materials_sheen/sheenColorTexture/extensions/KHR_texture_transform/rotation",h.rotation);const f=Yl("sheen.textureRoughness");fr("/materials/{}/extensions/KHR_materials_sheen/sheenRoughnessTexture/extensions/KHR_texture_transform/scale",f.scale),fr("/materials/{}/extensions/KHR_materials_sheen/sheenRoughnessTexture/extensions/KHR_texture_transform/offset",f.offset),fr("/materials/{}/extensions/KHR_materials_sheen/sheenRoughnessTexture/extensions/KHR_texture_transform/rotation",f.rotation),fr("/materials/{}/extensions/KHR_materials_specular/specularFactor",[new Zl(t.Animation.ANIMATIONTYPE_FLOAT,"metallicF0Factor",ql,()=>1)]),fr("/materials/{}/extensions/KHR_materials_specular/specularColorFactor",[new Zl(t.Animation.ANIMATIONTYPE_COLOR3,"metallicReflectanceColor",Kl,()=>3)]);const p=Yl("metallicReflectanceTexture");fr("/materials/{}/extensions/KHR_materials_specular/specularTexture/extensions/KHR_texture_transform/scale",p.scale),fr("/materials/{}/extensions/KHR_materials_specular/specularTexture/extensions/KHR_texture_transform/offset",p.offset),fr("/materials/{}/extensions/KHR_materials_specular/specularTexture/extensions/KHR_texture_transform/rotation",p.rotation);const m=Yl("reflectanceTexture");fr("/materials/{}/extensions/KHR_materials_specular/specularColorTexture/extensions/KHR_texture_transform/scale",m.scale),fr("/materials/{}/extensions/KHR_materials_specular/specularColorTexture/extensions/KHR_texture_transform/offset",m.offset),fr("/materials/{}/extensions/KHR_materials_specular/specularColorTexture/extensions/KHR_texture_transform/rotation",m.rotation),fr("/materials/{}/extensions/KHR_materials_transmission/transmissionFactor",[new Zl(t.Animation.ANIMATIONTYPE_FLOAT,"subSurface.refractionIntensity",ql,()=>1)]);const _=Yl("subSurface.refractionIntensityTexture");fr("/materials/{}/extensions/KHR_materials_transmission/transmissionTexture/extensions/KHR_texture_transform/scale",_.scale),fr("/materials/{}/extensions/KHR_materials_transmission/transmissionTexture/extensions/KHR_texture_transform/offset",_.offset),fr("/materials/{}/extensions/KHR_materials_transmission/transmissionTexture/extensions/KHR_texture_transform/rotation",_.rotation),fr("/materials/{}/extensions/KHR_materials_volume/attenuationColor",[new Zl(t.Animation.ANIMATIONTYPE_COLOR3,"subSurface.tintColor",Kl,()=>3)]),fr("/materials/{}/extensions/KHR_materials_volume/attenuationDistance",[new Zl(t.Animation.ANIMATIONTYPE_FLOAT,"subSurface.tintColorAtDistance",ql,()=>1)]),fr("/materials/{}/extensions/KHR_materials_volume/thicknessFactor",[new Zl(t.Animation.ANIMATIONTYPE_FLOAT,"subSurface.maximumThickness",ql,()=>1)]);const g=Yl("subSurface.thicknessTexture");fr("/materials/{}/extensions/KHR_materials_volume/thicknessTexture/extensions/KHR_texture_transform/scale",g.scale),fr("/materials/{}/extensions/KHR_materials_volume/thicknessTexture/extensions/KHR_texture_transform/offset",g.offset),fr("/materials/{}/extensions/KHR_materials_volume/thicknessTexture/extensions/KHR_texture_transform/rotation",g.rotation),fr("/materials/{}/extensions/KHR_materials_diffuse_transmission/diffuseTransmissionFactor",[new Zl(t.Animation.ANIMATIONTYPE_FLOAT,"subSurface.translucencyIntensity",ql,()=>1)]);const v=Yl("subSurface.translucencyIntensityTexture");fr("materials/{}/extensions/KHR_materials_diffuse_transmission/diffuseTransmissionTexture/extensions/KHR_texture_transform/scale",v.scale),fr("materials/{}/extensions/KHR_materials_diffuse_transmission/diffuseTransmissionTexture/extensions/KHR_texture_transform/offset",v.offset),fr("materials/{}/extensions/KHR_materials_diffuse_transmission/diffuseTransmissionTexture/extensions/KHR_texture_transform/rotation",v.rotation),fr("/materials/{}/extensions/KHR_materials_diffuse_transmission/diffuseTransmissionColorFactor",[new Zl(t.Animation.ANIMATIONTYPE_COLOR3,"subSurface.translucencyColor",Kl,()=>3)]);const y=Yl("subSurface.translucencyColorTexture");fr("materials/{}/extensions/KHR_materials_diffuse_transmission/diffuseTransmissionColorTexture/extensions/KHR_texture_transform/scale",y.scale),fr("materials/{}/extensions/KHR_materials_diffuse_transmission/diffuseTransmissionColorTexture/extensions/KHR_texture_transform/offset",y.offset),fr("materials/{}/extensions/KHR_materials_diffuse_transmission/diffuseTransmissionColorTexture/extensions/KHR_texture_transform/rotation",y.rotation),fr("/extensions/KHR_lights_punctual/lights/{}/color",[new Jl(t.Animation.ANIMATIONTYPE_COLOR3,"diffuse",Kl,()=>3)]),fr("/extensions/KHR_lights_punctual/lights/{}/intensity",[new Jl(t.Animation.ANIMATIONTYPE_FLOAT,"intensity",ql,()=>1)]),fr("/extensions/KHR_lights_punctual/lights/{}/range",[new Jl(t.Animation.ANIMATIONTYPE_FLOAT,"range",ql,()=>1)]),fr("/extensions/KHR_lights_punctual/lights/{}/spot/innerConeAngle",[new Jl(t.Animation.ANIMATIONTYPE_FLOAT,"innerAngle",Xl,()=>1)]),fr("/extensions/KHR_lights_punctual/lights/{}/spot/outerConeAngle",[new Jl(t.Animation.ANIMATIONTYPE_FLOAT,"angle",Xl,()=>1)]),fr("/extensions/EXT_lights_area/lights/{}/color",[new Jl(t.Animation.ANIMATIONTYPE_COLOR3,"diffuse",Kl,()=>3)]),fr("/extensions/EXT_lights_area/lights/{}/intensity",[new Jl(t.Animation.ANIMATIONTYPE_FLOAT,"intensity",ql,()=>1)]),fr("/extensions/EXT_lights_area/lights/{}/size",[new Jl(t.Animation.ANIMATIONTYPE_FLOAT,"radius",ql,()=>1)]),fr("/extensions/EXT_lights_area/lights/{}/rect/aspect",[new Jl(t.Animation.ANIMATIONTYPE_FLOAT,"radius",ql,()=>1)]),fr("/nodes/{}/extensions/EXT_lights_ies/color",[new Jl(t.Animation.ANIMATIONTYPE_COLOR3,"diffuse",Kl,()=>3)]),fr("/nodes/{}/extensions/EXT_lights_ies/multiplier",[new Jl(t.Animation.ANIMATIONTYPE_FLOAT,"intensity",ql,()=>1)]),fr("/nodes/{}/extensions/KHR_node_visibility/visible",[new eu(t.Animation.ANIMATIONTYPE_FLOAT,"isVisible",ql,()=>1)])}var ou={__proto__:null,_RegisterKHRAnimationPointerData:nu};nu(),Ul();const su="MSFT_audio_emitter";class ru{constructor(e){this.name=su,this._loader=e,this.enabled=this._loader.isExtensionUsed(su)}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,gr.Assign(this._clips),gr.Assign(this._emitters)}}loadSceneAsync(e,t){return yr.LoadExtensionAsync(e,t,this.name,(n,o)=>b(this,void 0,void 0,function*(){const s=new Array;s.push(this._loader.loadSceneAsync(e,t));for(const e of o.emitters){const t=gr.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`);s.push(this._loadEmitterAsync(`${n}/emitters/${t.index}`,t))}yield Promise.all(s)}))}loadNodeAsync(e,n,o){return yr.LoadExtensionAsync(e,n,this.name,(e,s)=>b(this,void 0,void 0,function*(){const r=new Array,i=yield this._loader.loadNodeAsync(e,n,n=>{for(const o of s.emitters){const s=gr.Get(`${e}/emitters`,this._emitters,o);r.push(this._loadEmitterAsync(`${e}/emitters/${s.index}`,s).then(()=>{for(const e of s._babylonSounds)e.attachToMesh(n),null==s.innerAngle&&null==s.outerAngle||(e.setLocalDirectionToMesh(t.Vector3.Forward()),e.setDirectionalCone(2*t.Tools.ToDegrees(null==s.innerAngle?Math.PI:s.innerAngle),2*t.Tools.ToDegrees(null==s.outerAngle?Math.PI:s.outerAngle),0))}))}o(n)});return yield Promise.all(r),i}))}loadAnimationAsync(e,t){return yr.LoadExtensionAsync(e,t,this.name,(n,o)=>b(this,void 0,void 0,function*(){const s=yield this._loader.loadAnimationAsync(e,t),r=new Array;gr.Assign(o.events);for(const i of o.events)r.push(this._loadAnimationEventAsync(`${n}/events/${i.index}`,e,t,i,s));return yield Promise.all(r),s}))}_loadClipAsync(e,n){if(n._objectURL)return n._objectURL;let o;if(n.uri)o=this._loader.loadUriAsync(e,n,n.uri);else{const t=gr.Get(`${e}/bufferView`,this._loader.gltf.bufferViews,n.bufferView);o=this._loader.loadBufferViewAsync(`/bufferViews/${t.index}`,t)}return n._objectURL=o.then(e=>{const o=t.GetBlobBufferSource(e);return URL.createObjectURL(new Blob([o],{type:n.mimeType}))}),n._objectURL}_loadEmitterAsync(e,n){if(n._babylonSounds=n._babylonSounds||[],!n._babylonData){const e=new Array,o=n.name||`emitter${n.index}`,s={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=gr.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(o,e,this._loader.babylonScene,null,s);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),o=new t.WeightedSound(n.loop||!1,n._babylonSounds,e);n.innerAngle&&(o.directionalConeInnerAngle=2*t.Tools.ToDegrees(n.innerAngle)),n.outerAngle&&(o.directionalConeOuterAngle=2*t.Tools.ToDegrees(n.outerAngle)),n.volume&&(o.volume=n.volume),n._babylonData.sound=o});n._babylonData={loaded:r}}return n._babylonData.loaded}_getEventAction(e,t,n,o,s){switch(n){case"play":return e=>{const n=(s||0)+(e-o);t.play(n)};case"stop":return()=>{t.stop()};case"pause":return()=>{t.pause()};default:throw new Error(`${e}: Unsupported action ${n}`)}}_loadAnimationEventAsync(e,n,o,s,r){if(0==r.targetedAnimations.length)return Promise.resolve();const i=r.targetedAnimations[0],a=s.emitter,l=gr.Get(`/extensions/${this.name}/emitters`,this._emitters,a);return this._loadEmitterAsync(e,l).then(()=>{const n=l._babylonData.sound;if(n){const o=new t.AnimationEvent(s.time,this._getEventAction(e,n,s.action,s.time,s.startOffset));i.animation.addEvent(o),r.onAnimationGroupEndObservable.add(()=>{n.stop()}),r.onAnimationGroupPauseObservable.add(()=>{n.pause()})}})}}let iu=!1;function au(){iu||(iu=!0,Ys(su),Xs(su,!0,e=>new ru(e)))}var lu={__proto__:null,MSFT_audio_emitter:ru,RegisterMSFT_audio_emitter:au};au();const uu="MSFT_lod";class cu{constructor(e){var n,o;this.name=uu,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!==(o=null===(n=this._loader.parent.extensionOptions[uu])||void 0===n?void 0:n.maxLODsToLoad)&&void 0!==o?o:this.maxLODsToLoad,this.enabled=this._loader.isExtensionUsed(uu)}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,o){return yr.LoadExtensionAsync(e,n,this.name,(e,s)=>b(this,void 0,void 0,function*(){let r;const i=this._getLODs(e,n,this._loader.gltf.nodes,s.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 s=e=>{o(e),e.setEnabled(!1)},a=this._loader.loadNodeAsync(`/nodes/${n.index}`,n,s).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,o,s){return this._nodeIndexLOD?null:yr.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,o,t=>{0===e&&s(t)}).then(t=>{if(0!==e){s(t);const n=a[e-1]._data;n[o]&&(this._disposeMaterials([n[o].babylonMaterial]),delete n[o])}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,o){if(null!==this._nodeIndexLOD){this._loader.log("deferred");const s=this._nodeIndexLOD-1;return this._nodeSignalLODs[s]=this._nodeSignalLODs[s]||new t.Deferred,this._nodeSignalLODs[this._nodeIndexLOD-1].promise.then(()=>b(this,void 0,void 0,function*(){return yield this._loader.loadUriAsync(e,n,o)}))}if(null!==this._materialIndexLOD){this._loader.log("deferred");const s=this._materialIndexLOD-1;return this._materialSignalLODs[s]=this._materialSignalLODs[s]||new t.Deferred,this._materialSignalLODs[s].promise.then(()=>b(this,void 0,void 0,function*(){return yield this._loader.loadUriAsync(e,n,o)}))}return null}loadBufferAsync(e,n,o,s){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=o,i=r+s-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+o-a.start,s))});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,o){if(this.maxLODsToLoad<=0)throw new Error("maxLODsToLoad must be greater than zero");const s=[];for(let t=o.length-1;t>=0;t--)if(s.push(gr.Get(`${e}/ids/${o[t]}`,n,o[t])),s.length===this.maxLODsToLoad)return s;return s.push(t),s}_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 o=t.filter(e=>this._loader.babylonScene.meshes.every(t=>t.material!=e));this._disposeMaterials(o)}_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()}}let du=!1;function hu(){du||(du=!0,Ys(uu),Xs(uu,!0,e=>new cu(e)))}var fu={__proto__:null,MSFT_lod:cu,RegisterMSFT_lod:hu};hu();const pu="MSFT_minecraftMesh";class mu{constructor(e){this.name=pu,this._loader=e,this.enabled=this._loader.isExtensionUsed(pu)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yr.LoadExtraAsync(e,t,this.name,(o,s)=>b(this,void 0,void 0,function*(){if(s){if(!this._loader._pbrMaterialImpls.get("pbr"))throw new Error(`${o}: Material type not supported`);const s=this._loader.loadMaterialPropertiesAsync(e,t,n);return n.needAlphaBlending()&&(n.forceDepthWrite=!0,n.separateCullingPass=!0),n.backFaceCulling=n.forceDepthWrite,n.twoSidedLighting=!0,yield s}}))}}let _u=!1;function gu(){_u||(_u=!0,Ys(pu),Xs(pu,!0,e=>new mu(e)))}var vu={__proto__:null,MSFT_minecraftMesh:mu,RegisterMSFT_minecraftMesh:gu};gu();const yu="MSFT_sRGBFactors";class bu{constructor(e){this.name=yu,this._loader=e,this.enabled=this._loader.isExtensionUsed(yu)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,n){return yr.LoadExtraAsync(e,t,this.name,(o,s)=>b(this,void 0,void 0,function*(){if(s){const o=this._loader._getOrCreateMaterialAdapter(n),s=this._loader.loadMaterialPropertiesAsync(e,t,n),r=n.getScene().getEngine().useExactSrgbConversions;return o.baseColorTexture||o.baseColor.toLinearSpaceToRef(o.baseColor,r),o.specularColorTexture||o.specularColor.toLinearSpaceToRef(o.specularColor,r),yield s}}))}}let xu=!1;function Tu(){xu||(xu=!0,Ys(yu),Xs(yu,!0,e=>new bu(e)))}var Au={__proto__:null,MSFT_sRGBFactors:bu,RegisterMSFT_sRGBFactors:Tu};function Mu(e){const[t,n]=e.split(":");return wu({op:t,extension:n})}function wu(e,n=!0){var o;const s=e.extension?null===(o=Ru[e.extension])||void 0===o?void 0:o[e.op]:Iu[e.op];return!s&&n?(t.Logger.Warn(`No mapping found for operation ${e.op} and extension ${e.extension||"KHR_interactivity"}`),Su(e)):s}function Su(e){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}}function Cu(e,t,n){Ru[t]||(Ru[t]={}),Ru[t][e]=n}Tu();const Ru={BABYLON:{"flow/log":{blocks:["FlowGraphConsoleLogBlock"],inputs:{values:{message:{name:"message"},"[segment]":{name:"$1",compatibilityOnly:!0}}},outputs:{flows:{out:{name:"out",compatibilityOnly:!0}}}}}},Iu={"event/onStart":{blocks:["FlowGraphSceneReadyEventBlock"],outputs:{values:{event:{name:"event"}},flows:{out:{name:"done"}}}},"event/onTick":{blocks:["FlowGraphSceneTickEventBlock"],inputs:{},outputs:{values:{timeSinceStart:{name:"timeSinceStart",gltfType:"number"},timeSinceLastTick:{name:"deltaTime",gltfType:"number"},event:{name:"event"}},flows:{out:{name:"done"}}}},"event/send":{blocks:["FlowGraphSendCustomEventBlock"],configuration:{event:{name:"eventId",configurationType:"int",required:!0,indexSource:"events",validationOnly:!0}},inputs:{values:{"[segment]":{name:"$1"}}},outputs:{flows:{out:{name:"out"}}},extraProcessor(e,t,n,o,s){var r,i;if("event/send"!==t.op||!(null===(r=e.configuration)||void 0===r?void 0:r.event))throw new Error("Send event should have a single configuration object, the event itself");const a=null===(i=e.configuration.event.value)||void 0===i?void 0:i[0];if("number"!=typeof a)throw new Error("Event id should be a number");const l=o.arrays.events[a],u=s[0];return u.config||(u.config={}),u.config.eventId=l.eventId,u.config.eventData=l.eventData,s}},"event/receive":{blocks:["FlowGraphReceiveCustomEventBlock"],configuration:{event:{name:"eventId",configurationType:"int",required:!0,indexSource:"events",validationOnly:!0}},outputs:{values:{event:{name:"event"},"[segment]":{name:"$1"}},flows:{out:{name:"done"}}},validation(e,n){var o,s;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===(o=r.value)||void 0===o?void 0:o[0];return"number"!=typeof i?(t.Logger.Error("Event id should be a number"),{valid:!1,error:"Event id should be a number"}):(null===(s=n.events)||void 0===s?void 0:s[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,o,s){var r,i;if("event/receive"!==t.op||!(null===(r=e.configuration)||void 0===r?void 0:r.event))throw new Error("Receive event should have a single configuration object, the event itself");const a=null===(i=e.configuration.event.value)||void 0===i?void 0:i[0];if("number"!=typeof a)throw new Error("Event id should be a number");const l=o.arrays.events[a],u=s[0];return u.config||(u.config={}),u.config.eventId=l.eventId,u.config.eventData=l.eventData,s}},"event/stopPropagation":{blocks:["FlowGraphStopEventPropagationBlock"],inputs:{values:{event:{name:"event"},stopImmediate:{name:"stopImmediate"}},flows:{in:{name:"in"}}},outputs:{flows:{out:{name:"out"}}}},"math/E":Ou("FlowGraphEBlock",[]),"math/Pi":Ou("FlowGraphPIBlock",[]),"math/Tau":Ou("FlowGraphTauBlock",[]),"math/Inf":Ou("FlowGraphInfBlock",[]),"math/NaN":Ou("FlowGraphNaNBlock",[]),"math/abs":Ou("FlowGraphAbsBlock"),"math/sign":Ou("FlowGraphSignBlock"),"math/trunc":Ou("FlowGraphTruncBlock"),"math/floor":Ou("FlowGraphFloorBlock"),"math/ceil":Ou("FlowGraphCeilBlock"),"math/round":{blocks:["FlowGraphRoundBlock"],configuration:{},inputs:{values:{a:{name:"a"}}},outputs:{values:{value:{name:"value"}}},extraProcessor(e,t,n,o,s){var r;return(r=s[0]).config||(r.config={}),s[0].config.roundHalfAwayFromZero=!0,s}},"math/fract":Ou("FlowGraphFractBlock"),"math/neg":Ou("FlowGraphNegationBlock"),"math/add":Ou("FlowGraphAddBlock",["a","b"],!0),"math/sub":Ou("FlowGraphSubtractBlock",["a","b"],!0),"math/mul":{blocks:["FlowGraphMultiplyBlock"],inputs:{values:{a:{name:"a"},b:{name:"b"}}},outputs:{values:{value:{name:"value"}}},extraProcessor(e,t,n,o,s){var r;(r=s[0]).config||(r.config={}),s[0].config.useMatrixPerComponent=!0,s[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&&(s[0].config.type=o.arrays.types[i].flowGraphType),s},validation:e=>e.values?Fu(e):{valid:!0}},"math/div":Ou("FlowGraphDivideBlock",["a","b"],!0),"math/rem":Ou("FlowGraphModuloBlock",["a","b"]),"math/min":Ou("FlowGraphMinBlock",["a","b"]),"math/max":Ou("FlowGraphMaxBlock",["a","b"]),"math/clamp":Ou("FlowGraphClampBlock",["a","b","c"]),"math/saturate":Ou("FlowGraphSaturateBlock"),"math/mix":Ou("FlowGraphMathInterpolationBlock",["a","b","c"]),"math/smoothStep":Ou("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":Ou("FlowGraphMathSlerpBlock",["a","b","c"]),"math/slerp":Ou("FlowGraphVectorSlerpBlock",["a","b","c"]),"math/eq":Ou("FlowGraphEqualityBlock",["a","b"]),"ref/eq":Ou("FlowGraphEqualityBlock",["a","b"]),"math/lt":Ou("FlowGraphLessThanBlock",["a","b"]),"math/le":Ou("FlowGraphLessThanOrEqualBlock",["a","b"]),"math/gt":Ou("FlowGraphGreaterThanBlock",["a","b"]),"math/ge":Ou("FlowGraphGreaterThanOrEqualBlock",["a","b"]),"math/isNaN":Ou("FlowGraphIsNaNBlock"),"math/isInf":Ou("FlowGraphIsInfBlock"),"math/select":{blocks:["FlowGraphConditionalBlock"],inputs:{values:{condition:{name:"condition"},a:{name:"onTrue"},b:{name:"onFalse"}}},outputs:{values:{value:{name:"output",typeSourceInput:"a"}}}},"math/random":{blocks:["FlowGraphRandomBlock"],outputs:{values:{value:{name:"value"}}}},"math/sin":Ou("FlowGraphSinBlock"),"math/cos":Ou("FlowGraphCosBlock"),"math/tan":Ou("FlowGraphTanBlock"),"math/asin":Ou("FlowGraphASinBlock"),"math/acos":Ou("FlowGraphACosBlock"),"math/atan":Ou("FlowGraphATanBlock"),"math/atan2":Ou("FlowGraphATan2Block",["a","b"]),"math/sinh":Ou("FlowGraphSinhBlock"),"math/cosh":Ou("FlowGraphCoshBlock"),"math/tanh":Ou("FlowGraphTanhBlock"),"math/asinh":Ou("FlowGraphASinhBlock"),"math/acosh":Ou("FlowGraphACoshBlock"),"math/atanh":Ou("FlowGraphATanhBlock"),"math/exp":Ou("FlowGraphExponentialBlock"),"math/log":Ou("FlowGraphLogBlock"),"math/log2":Ou("FlowGraphLog2Block"),"math/log10":Ou("FlowGraphLog10Block"),"math/sqrt":Ou("FlowGraphSquareRootBlock"),"math/cbrt":Ou("FlowGraphCubeRootBlock"),"math/pow":Ou("FlowGraphPowerBlock",["a","b"]),"math/length":Ou("FlowGraphLengthBlock"),"math/normalize":Object.assign(Object.assign({},Ou("FlowGraphNormalizeBlock")),{outputs:{values:{value:{name:"value"},isValid:{name:"isValid",gltfType:"bool"}}}}),"math/dot":Ou("FlowGraphDotBlock",["a","b"]),"math/cross":Ou("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":Ou("FlowGraphTransposeBlock"),"math/determinant":Ou("FlowGraphDeterminantBlock"),"math/inverse":Object.assign(Object.assign({},Ou("FlowGraphInvertMatrixBlock")),{outputs:{values:{value:{name:"value"},isValid:{name:"isValid",gltfType:"bool"}}}}),"math/matMul":Ou("FlowGraphMatrixMultiplicationBlock",["a","b"]),"math/matCompose":{blocks:["FlowGraphMatrixCompose"],inputs:{values:{translation:{name:"position",gltfType:"float3"},rotation:{name:"rotationQuaternion",gltfType:"float4"},scale:{name:"scaling",gltfType:"float3"}}},outputs:{values:{value:{name:"value",gltfType:"float4x4"}}},extraProcessor(e,t,n,o,s,r){const i=s[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"),s}},"math/matDecompose":{blocks:["FlowGraphMatrixDecompose"],inputs:{values:{a:{name:"input",gltfType:"number"}}},outputs:{values:{translation:{name:"position"},rotation:{name:"rotationQuaternion"},scale:{name:"scaling"},scaling:{name:"scaling",compatibilityOnly:!0},isValid:{name:"isValid",compatibilityOnly:!0}}},extraProcessor(e,t,n,o,s){var r;return(r=s[0]).config||(r.config={}),s[0].config.keepDegenerateComponents=!0,s}},"math/quatConjugate":Ou("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,o,s){var r;return(r=s[0]).config||(r.config={}),s[0].config.type="Quaternion",s}},"math/quatAngleBetween":Ou("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":{blocks:["FlowGraphAxisAngleFromQuaternionBlock"],inputs:{values:{a:{name:"a",gltfType:"float4"}}},outputs:{values:{axis:{name:"axis",gltfType:"float3"},angle:{name:"angle",gltfType:"float"}}}},"math/quatFromDirections":Ou("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,o,s,r){var i,a,l;(l=s[0]).config||(l.config={});const u=s[0].dataInputs[0];return s[0].config.valueType=null!==(a=null===(i=r._connectionValues[u.uniqueId])||void 0===i?void 0:i.type)&&void 0!==a?a:"FlowGraphInteger",s}},"math/and":{blocks:["FlowGraphBitwiseAndBlock"],inputs:{values:{a:{name:"a"},b:{name:"b"}}},outputs:{values:{value:{name:"value"}}},extraProcessor(e,t,n,o,s,r){var i,a,l,u,c;(c=s[0]).config||(c.config={});const d=s[0].dataInputs[0],h=s[0].dataInputs[1];return s[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",s}},"math/or":{blocks:["FlowGraphBitwiseOrBlock"],inputs:{values:{a:{name:"a"},b:{name:"b"}}},outputs:{values:{value:{name:"value"}}},extraProcessor(e,t,n,o,s,r){var i,a,l,u,c;(c=s[0]).config||(c.config={});const d=s[0].dataInputs[0],h=s[0].dataInputs[1];return s[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",s}},"math/xor":{blocks:["FlowGraphBitwiseXorBlock"],inputs:{values:{a:{name:"a"},b:{name:"b"}}},outputs:{values:{value:{name:"value"}}},extraProcessor(e,t,n,o,s,r){var i,a,l,u,c;(c=s[0]).config||(c.config={});const d=s[0].dataInputs[0],h=s[0].dataInputs[1];return s[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",s}},"math/asr":Ou("FlowGraphBitwiseRightShiftBlock",["a","b"]),"math/lsl":Ou("FlowGraphBitwiseLeftShiftBlock",["a","b"]),"math/clz":Ou("FlowGraphLeadingZerosBlock"),"math/ctz":Ou("FlowGraphTrailingZerosBlock"),"math/popcnt":Ou("FlowGraphOneBitsCounterBlock"),"math/rad":Ou("FlowGraphDegToRadBlock"),"math/deg":Ou("FlowGraphRadToDegBlock"),"type/boolToInt":Ou("FlowGraphBooleanToInt"),"type/boolToFloat":Ou("FlowGraphBooleanToFloat"),"type/intToBool":Ou("FlowGraphIntToBoolean"),"type/intToFloat":Ou("FlowGraphIntToFloat"),"type/floatToInt":Ou("FlowGraphFloatToInt"),"type/floatToBool":Ou("FlowGraphFloatToBoolean"),"flow/sequence":{blocks:["FlowGraphSequenceBlock"],outputs:{flows:{"[segment]":{name:"$1"}}},extraProcessor(e,t,n,o,s){const r=s[0];return r.config||(r.config={}),r.config.outputSignalCount=Object.keys(e.flows||[]).length,r.signalOutputs.forEach((e,t)=>{e.name="out_"+t}),s}},"flow/branch":{blocks:["FlowGraphBranchBlock"],inputs:{values:{condition:{name:"condition",gltfType:"boolean"}}},outputs:{flows:{true:{name:"onTrue"},false:{name:"onFalse"}}}},"flow/switch":{blocks:["FlowGraphSwitchBlock"],configuration:{cases:{name:"cases",isArray:!0,inOptions:!0,defaultValue:[],configurationType:"int[]",invalidUsesDefault:!0,generatesOutputFlowSockets:!0,uniqueValues:!0}},inputs:{values:{selection:{name:"case"},default:{name:"default"}}},outputs:{flows:{default:{name:"default"},"[segment]":{name:"$1"}}},validation(e){var n;const o=null===(n=e.configuration)||void 0===n?void 0:n.cases;if(o&&o.value){if(!o.value.every(e=>"number"==typeof e&&Number.isInteger(e)&&e>=-2147483648&&e<=2147483647))return t.Logger.Warn("Switch cases should be integers. Using empty array instead."),o.value=[],{valid:!0};const e=new Set(o.value);o.value=Array.from(e)}return{valid:!0}},extraProcessor(e,t,n,o,s){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 s[0].signalOutputs.forEach(e=>{"default"!==e.name&&(e.name="out_"+e.name)}),s}},"flow/while":{blocks:["FlowGraphWhileLoopBlock"],inputs:{values:{condition:{name:"condition",gltfType:"boolean"}}},outputs:{flows:{loopBody:{name:"executionFlow"},completed:{name:"completed"}}}},"flow/for":{blocks:["FlowGraphForLoopBlock"],configuration:{initialIndex:{name:"initialIndex",gltfType:"int",inOptions:!0,defaultValue:0,configurationType:"int",invalidUsesDefault:!0}},inputs:{values:{startIndex:{name:"startIndex",gltfType:"int"},endIndex:{name:"endIndex",gltfType:"int"}}},outputs:{values:{index:{name:"index"}},flows:{loopBody:{name:"executionFlow"},completed:{name:"completed"}}},extraProcessor(e,t,n,o,s){const r=s[0];return r.config||(r.config={}),r.config.incrementIndexWhenLoopDone=!0,r.config.maxLoopIterations=2e4,s}},"flow/doN":{blocks:["FlowGraphDoNBlock"],configuration:{},inputs:{values:{n:{name:"maxExecutions",gltfType:"int"}},flows:{reset:{name:"reset"}}},outputs:{flows:{out:{name:"out"}},values:{currentCount:{name:"executionCount"}}}},"flow/multiGate":{blocks:["FlowGraphMultiGateBlock"],inputs:{flows:{reset:{name:"reset"}}},configuration:{isRandom:{name:"isRandom",gltfType:"boolean",inOptions:!0,defaultValue:!1,configurationType:"bool",invalidUsesDefault:!0,configurationGroup:"multiGate"},isLoop:{name:"isLoop",gltfType:"boolean",inOptions:!0,defaultValue:!1,configurationType:"bool",invalidUsesDefault:!0,configurationGroup:"multiGate"}},outputs:{flows:{"[segment]":{name:"$1"}},values:{lastIndex:{name:"lastIndex",gltfType:"int"}}},extraProcessor(e,t,n,o,s){var r;if("flow/multiGate"!==t.op)throw new Error("Invalid operation for MultiGate mapping");const i=s[0];return i.config||(i.config={}),i.config.outputSignalCount=Object.keys(null!==(r=e.flows)&&void 0!==r?r:{}).length,i.signalOutputs.forEach((e,t)=>{e.name="out_"+t}),s}},"flow/waitAll":{blocks:["FlowGraphWaitAllBlock"],configuration:{inputFlows:{name:"inputSignalCount",gltfType:"number",inOptions:!0,defaultValue:[0],configurationType:"int",invalidUsesDefault:!0,minimum:0,maximum:64,generatesInputFlowSockets:!0}},inputs:{flows:{reset:{name:"reset"},"[segment]":{name:"in_$1"}}},outputs:{flows:{out:{name:"out"},completed:{name:"completed"}},values:{remainingInputs:{name:"remainingInputs",gltfType:"int"}}},validation(e){var t,n;const o=null===(n=null===(t=e.configuration)||void 0===t?void 0:t.inputFlows)||void 0===n?void 0:n.value,s=null==o?void 0:o[0];return(1!==(null==o?void 0:o.length)||"number"!=typeof s||!Number.isInteger(s)||s<0||s>64)&&(e.configuration=e.configuration||{inputFlows:{value:[0]}},e.configuration.inputFlows.value=[0]),{valid:!0}}},"flow/throttle":{blocks:["FlowGraphThrottleBlock"],inputs:{values:{duration:{name:"duration",gltfType:"number"}},flows:{reset:{name:"reset"}}},outputs:{flows:{out:{name:"out"},err:{name:"error"}},values:{lastRemainingTime:{name:"lastRemainingTime",gltfType:"number"}}}},"flow/setDelay":{blocks:["FlowGraphSetDelayBlock"],inputs:{values:{duration:{name:"duration",gltfType:"number"}},flows:{cancel:{name:"cancel"}}},outputs:{flows:{out:{name:"out"},err:{name:"error"},done:{name:"done"}},values:{lastDelay:{name:"lastDelayIndex"},lastDelayIndex:{name:"lastDelayIndex",compatibilityOnly:!0}}}},"flow/cancelDelay":{blocks:["FlowGraphCancelDelayBlock"],inputs:{values:{delay:{name:"delayIndex",gltfType:"ref"}}},outputs:{flows:{out:{name:"out"}}}},"variable/get":{blocks:["FlowGraphGetVariableBlock"],validation(e){var n,o;return(null===(o=null===(n=e.configuration)||void 0===n?void 0:n.variable)||void 0===o?void 0:o.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",configurationType:"int",required:!0,indexSource:"variables",flowGraphType:"string",inOptions:!0,isVariable:!0,dataTransformer:(e,t)=>t.getVariableName(e)}},outputs:{values:{value:{name:"value"}}}},"variable/set":{blocks:["FlowGraphSetVariableBlock"],inputs:{values:{"[segment]":{name:"$1"}}},configuration:{variables:{name:"variables",gltfType:"number",configurationType:"int[]",required:!0,indexSource:"variables",minItems:1,generatesInputValueSockets:!0,flowGraphType:"string",inOptions:!0,isArray:!0,dataTransformer:(e,t)=>e.map(e=>t.getVariableName(e))}},outputs:{flows:{out:{name:"out",compatibilityOnly:!0}}},extraProcessor:(e,t,n,o,s)=>(s[0].dataInputs.forEach(e=>{e.name=o.getVariableName(+e.name)}),s)},"variable/interpolate":{blocks:["FlowGraphInterpolationBlock","FlowGraphContextBlock","FlowGraphPlayAnimationBlock","FlowGraphBezierCurveEasing","FlowGraphGetVariableBlock"],configuration:{variable:{name:"propertyName",configurationType:"int",required:!0,indexSource:"variables",inOptions:!0,isVariable:!0,dataTransformer:(e,t)=>t.getVariableName(e)},useSlerp:{name:"animationType",configurationType:"bool",required:!0,inOptions:!0,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,o,s,r){var i,a,l,u,c,d;const h=r[0],f=null===(a=null===(i=e.configuration)||void 0===i?void 0:i.variable.value)||void 0===a?void 0:a[0];if("number"!=typeof f)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 p=s.arrays.staticVariables[f];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(p.type));const m=r[4];return m.config||(m.config={}),(d=m.config).variable||(d.variable={}),m.config.variable.value=s.getVariableName(f),r}},"pointer/get":{blocks:["FlowGraphGetPropertyBlock","FlowGraphJsonPointerParserBlock"],validation:e=>Nu(e),configuration:{pointer:{name:"jsonPointer",toBlock:"FlowGraphJsonPointerParserBlock",configurationType:"string",required:!0,pointerTemplate:!0},type:{name:"type",configurationType:"int",required:!0,validationOnly:!0,indexSource:"types"}},inputs:{values:{"[segment]":{name:"$1",toBlock:"FlowGraphJsonPointerParserBlock"}}},outputs:{values:{value:{name:"value"},isValid:{name:"isValid",gltfType:"bool"}}},interBlockConnectors:[{input:"object",output:"object",inputBlockIndex:0,outputBlockIndex:1,isVariable:!0},{input:"propertyName",output:"propertyName",inputBlockIndex:0,outputBlockIndex:1,isVariable:!0},{input:"customGetFunction",output:"getFunction",inputBlockIndex:0,outputBlockIndex:1,isVariable:!0}],extraProcessor:(e,t,n,o,s)=>(s.forEach(e=>{"FlowGraphJsonPointerParserBlock"===e.className&&(e.config||(e.config={}),e.config.outputValue=!0)}),s)},"pointer/set":{blocks:["FlowGraphSetPropertyBlock","FlowGraphJsonPointerParserBlock"],validation:e=>Nu(e,new Set(["value"])),configuration:{pointer:{name:"jsonPointer",toBlock:"FlowGraphJsonPointerParserBlock",configurationType:"string",required:!0,pointerTemplate:!0},type:{name:"type",configurationType:"int",required:!0,validationOnly:!0,indexSource:"types"}},inputs:{values:{value:{name:"value"},"[segment]":{name:"$1",toBlock:"FlowGraphJsonPointerParserBlock"}}},outputs:{flows:{err:{name:"error"},out:{name:"out",compatibilityOnly:!0}}},interBlockConnectors:[{input:"object",output:"object",inputBlockIndex:0,outputBlockIndex:1,isVariable:!0},{input:"propertyName",output:"propertyName",inputBlockIndex:0,outputBlockIndex:1,isVariable:!0},{input:"customSetFunction",output:"setFunction",inputBlockIndex:0,outputBlockIndex:1,isVariable:!0}],extraProcessor:(e,t,n,o,s)=>(s.forEach(e=>{"FlowGraphJsonPointerParserBlock"===e.className&&(e.config||(e.config={}),e.config.outputValue=!0)}),s)},"pointer/interpolate":{blocks:["FlowGraphInterpolationBlock","FlowGraphJsonPointerParserBlock","FlowGraphPlayAnimationBlock","FlowGraphBezierCurveEasing"],validation:e=>Nu(e,new Set(["value","duration","p1","p2"])),configuration:{pointer:{name:"jsonPointer",toBlock:"FlowGraphJsonPointerParserBlock",configurationType:"string",required:!0,pointerTemplate:!0},type:{name:"type",configurationType:"int",required:!0,validationOnly:!0,indexSource:"types",allowedSignatures:["float","float2","float3","float4","float2x2","float3x3","float4x4"]}},inputs:{values:{value:{name:"value_1"},"[segment]":{name:"$1",toBlock:"FlowGraphJsonPointerParserBlock"},duration:{name:"duration_1",gltfType:"number"},p1:{name:"controlPoint1",toBlock:"FlowGraphBezierCurveEasing"},p2:{name:"controlPoint2",toBlock:"FlowGraphBezierCurveEasing"}},flows:{in:{name:"in",toBlock:"FlowGraphPlayAnimationBlock"}}},outputs:{flows:{err:{name:"error",toBlock:"FlowGraphPlayAnimationBlock"},out:{name:"out",toBlock:"FlowGraphPlayAnimationBlock"},done:{name:"done",toBlock:"FlowGraphPlayAnimationBlock"}}},interBlockConnectors:[{input:"object",output:"object",inputBlockIndex:2,outputBlockIndex:1,isVariable:!0},{input:"propertyName",output:"propertyName",inputBlockIndex:0,outputBlockIndex:1,isVariable:!0},{input:"customBuildAnimation",output:"generateAnimationsFunction",inputBlockIndex:0,outputBlockIndex:1,isVariable:!0},{input:"animation",output:"animation",inputBlockIndex:2,outputBlockIndex:0,isVariable:!0},{input:"easingFunction",output:"easingFunction",inputBlockIndex:0,outputBlockIndex:3,isVariable:!0},{input:"value_0",output:"value",inputBlockIndex:0,outputBlockIndex:1,isVariable:!0}],extraProcessor:(e,t,n,o,s)=>(s.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 s;const r=null===(s=e.values)||void 0===s?void 0:s[n];if("value"===n&&r){const e=r.type;void 0!==e&&(t.config.animationType=o.arrays.types[e].flowGraphType)}}))}),s)},"animation/start":{blocks:["FlowGraphPlayAnimationBlock","FlowGraphArrayIndexBlock","KHR_interactivity/FlowGraphGLTFDataProvider"],inputs:{values:{animation:{name:"index",gltfType:"ref",toBlock:"FlowGraphArrayIndexBlock"},speed:{name:"speed",gltfType:"number"},startTime:{name:"from",gltfType:"number",convertConnectedTimeToFrames:!0,dataTransformer:(e,t)=>[e[0]*t._animationTargetFps]},endTime:{name:"to",gltfType:"number",convertConnectedTimeToFrames:!0,dataTransformer:(e,t)=>[e[0]*t._animationTargetFps]}}},outputs:{flows:{out:{name:"out"},err:{name:"error"},done:{name:"done"}}},interBlockConnectors:[{input:"animationGroup",output:"value",inputBlockIndex:0,outputBlockIndex:1,isVariable:!0},{input:"array",output:"animationGroups",inputBlockIndex:1,outputBlockIndex:2,isVariable:!0}],extraProcessor(e,t,n,o,s,r,i){const a=s.find(e=>"FlowGraphPlayAnimationBlock"===e.className);a&&(a.config.useVirtualTimeline=!0);const l=s.find(e=>"FlowGraphArrayIndexBlock"===e.className);l&&(l.config.referenceCollection="animations");const u=s[s.length-1];return u.config||(u.config={}),u.config.glTF=i,s}},"animation/stop":{blocks:["FlowGraphStopAnimationBlock","FlowGraphArrayIndexBlock","KHR_interactivity/FlowGraphGLTFDataProvider"],inputs:{values:{animation:{name:"index",gltfType:"ref",toBlock:"FlowGraphArrayIndexBlock"}}},outputs:{flows:{out:{name:"out"},err:{name:"error"}}},interBlockConnectors:[{input:"animationGroup",output:"value",inputBlockIndex:0,outputBlockIndex:1,isVariable:!0},{input:"array",output:"animationGroups",inputBlockIndex:1,outputBlockIndex:2,isVariable:!0}],extraProcessor(e,t,n,o,s,r,i){const a=s.find(e=>"FlowGraphStopAnimationBlock"===e.className);a&&(a.config.skipOnAnimationEnd=!0);const l=s.find(e=>"FlowGraphArrayIndexBlock"===e.className);l&&(l.config.referenceCollection="animations");const u=s[s.length-1];return u.config||(u.config={}),u.config.glTF=i,s}},"animation/stopAt":{blocks:["FlowGraphStopAnimationBlock","FlowGraphArrayIndexBlock","KHR_interactivity/FlowGraphGLTFDataProvider"],configuration:{},inputs:{values:{animation:{name:"index",gltfType:"ref",toBlock:"FlowGraphArrayIndexBlock"},stopTime:{name:"stopAtFrame",gltfType:"number",convertConnectedTimeToFrames:!0,dataTransformer:(e,t)=>[e[0]*t._animationTargetFps]}}},outputs:{flows:{out:{name:"out"},err:{name:"error"},done:{name:"done"}}},interBlockConnectors:[{input:"animationGroup",output:"value",inputBlockIndex:0,outputBlockIndex:1,isVariable:!0},{input:"array",output:"animationGroups",inputBlockIndex:1,outputBlockIndex:2,isVariable:!0}],extraProcessor(e,t,n,o,s,r,i){const a=s.find(e=>"FlowGraphStopAnimationBlock"===e.className);a&&(a.config.useVirtualStopAt=!0,a.config.skipOnAnimationEnd=!0);const l=s.find(e=>"FlowGraphArrayIndexBlock"===e.className);l&&(l.config.referenceCollection="animations");const u=s[s.length-1];return u.config||(u.config={}),u.config.glTF=i,s}},"math/switch":{blocks:["FlowGraphDataSwitchBlock"],configuration:{cases:{name:"cases",isArray:!0,inOptions:!0,defaultValue:[],configurationType:"int[]",invalidUsesDefault:!0,generatesCaseInputValueSockets:!0,uniqueValues:!0}},inputs:{values:{selection:{name:"case",gltfType:"int"},default:{name:"default"},"[case]":{name:"$1"}}},outputs:{values:{value:{name:"value"}}},validation(e){var n;const o=null===(n=e.configuration)||void 0===n?void 0:n.cases;if(o&&o.value){if(!o.value.every(e=>"number"==typeof e&&/^-?\d+$/.test(e.toString())))return t.Logger.Warn("Switch cases should be integers. Using empty array instead."),o.value=[],{valid:!0};const e=new Set(o.value);o.value=Array.from(e)}return{valid:!0}},extraProcessor(e,t,n,o,s){const r=s[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,s}},"debug/log":{blocks:["FlowGraphConsoleLogBlock"],inputs:{flows:{in:{name:"in"}},values:{"[parameter]":{name:"$1"}}},outputs:{flows:{out:{name:"out"}}},configuration:{severity:{name:"severity",configurationType:"int",defaultValue:0,invalidUsesDefault:!0,validationOnly:!0,configurationGroup:"debugLog"},message:{name:"messageTemplate",configurationType:"string",defaultValue:"",invalidUsesDefault:!0,inOptions:!0,configurationGroup:"debugLog",debugLogTemplate:!0}}}};function Ou(e,t=["a"],n){return{blocks:[e],inputs:{values:t.reduce((e,t)=>(e[t]={name:t},e),{})},outputs:{values:{value:{name:"value",typeSourceInput:t[0]}}},extraProcessor(e,t,o,s,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 o;return void 0!==(null===(o=e.values)||void 0===o?void 0:o[n].type)&&(t=e.values[n].type,!0)}),-1!==t&&(r[0].config.type=s.arrays.types[t].flowGraphType)}return r},validation:e=>n?Fu(e):{valid:!0}}}function Fu(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 Eu(e){for(let t=0;t<e.length;t++){const n=e[t];if(-1==="[]{}".indexOf(n))continue;let o=1;for(;e[t+o]===n;)o++;if(o%2!=0)return!0;t+=o-1}return!1}function Lu(e){let t=0,n=-1;const o=[],s=new Set;for(let r=0;r<e.length;r++){const i=e[r];if("{"===i)if(0===t)t=1;else{if(1!==t)return{valid:!1,sockets:[]};t=0}else if("}"===i)if(0===t)t=3;else if(3===t)t=0;else{if(2!==t)return{valid:!1,sockets:[]};{const i=e.substring(n+1,r);s.has(i)||(s.add(i),o.push(i)),t=0}}else if(1===t)n=r-1,t=2;else if(3===t)return{valid:!1,sockets:[]}}return{valid:0===t,sockets:0===t?o:[]}}function Nu(e,t=new Set){var n,o,s;const r=null===(s=null===(o=null===(n=e.configuration)||void 0===n?void 0:n.pointer)||void 0===o?void 0:o.value)||void 0===s?void 0:s[0];if("string"!=typeof r)return{valid:!1,error:"A pointer operation requires a string `pointer` configuration value"};if(0!==r.length&&"/"!==r[0])return{valid:!1,error:`The JSON Pointer Template "${r}" is not a syntactically valid JSON Pointer`};const i=e=>({valid:!1,error:`The JSON Pointer Template "${r}" is invalid: ${e}`}),a=new Set;for(const e of r.split("/")){if(/~(?:[^01]|$)/.test(e))return i(`the path segment "${e}" contains an invalid RFC 6901 escape`);const n="["===e[0]&&"["!==e[1],o="{"===e[0]&&"{"!==e[1];if(!n&&!o){if(Eu(e))return i(`the path segment "${e}" contains an odd number of consecutive brackets`);continue}const s=n?"]":"}",r=e.substring(1,e.length-1);if(e.length<3||e[e.length-1]!==s||/[[{]/.test(r)||/[\]}]/.test(r))return i(`the template parameter path segment "${e}" is malformed`);const l=r.replace(/~1/g,"/").replace(/~0/g,"~");if(t.has(l))return i(`the template parameter "${l}" uses a reserved input socket id`);if(a.has(l))return i(`the template parameter "${l}" is used more than once`);a.add(l)}return{valid:!0}}function ku(){return Object.keys(Iu)}const Bu="f798712c5685bc9223a628140fba707db8889300",Pu={float:{length:1,flowGraphType:"number",elementType:"number"},bool:{length:1,flowGraphType:"boolean",elementType:"boolean"},float2:{length:2,flowGraphType:"Vector2",elementType:"number"},float3:{length:3,flowGraphType:"Vector3",elementType:"number"},float4:{length:4,flowGraphType:"Vector4",elementType:"number"},float4x4:{length:16,flowGraphType:"Matrix",elementType:"number"},float2x2:{length:4,flowGraphType:"Matrix2D",elementType:"number"},float3x3:{length:9,flowGraphType:"Matrix3D",elementType:"number"},int:{length:1,flowGraphType:"FlowGraphInteger",elementType:"number"},ref:{length:1,flowGraphType:"string",elementType:"string"},custom:{length:0,flowGraphType:"any",elementType:"any"}};function Du(e){if(Array.isArray(e))return e.map(e=>Du(e));if(null!==e&&"object"==typeof e){const t={};for(const[n,o]of Object.entries(e))Object.defineProperty(t,n,{configurable:!0,enumerable:!0,value:Du(o),writable:!0});return t}return e}function Vu(e){return Du(e)}function Gu(e,t){return"number"==typeof e&&Number.isInteger(e)&&e>=0&&e<t}function $u(e,t,n){e.push({path:t,message:n,severity:"error"})}function Uu(e){return""===e||/^(?:\/(?:[^~]|~[01])*)*$/.test(e)}function Hu(e,t,n,o,s,r){var i,a,l,u,c,d;if(e&&Object.prototype.hasOwnProperty.call(e,t))return!0;if(t===r&&e&&Object.prototype.hasOwnProperty.call(e,r))return!0;if(!Object.keys(null!=e?e:{}).some(e=>e.startsWith("[")&&e.endsWith("]")))return!1;if("event/receive"===n.operation){const e=null===(l=null===(a=null===(i=o.configuration)||void 0===i?void 0:i.event)||void 0===a?void 0:a.value)||void 0===l?void 0:l[0];return"number"==typeof e&&Object.prototype.hasOwnProperty.call(null!==(d=null===(c=null===(u=s.events)||void 0===u?void 0:u[e])||void 0===c?void 0:c.values)&&void 0!==d?d:{},t)}return!0}function Ku(e,t,n,o){var s,r;return!!Gu(e,null!==(r=null===(s=t.types)||void 0===s?void 0:s.length)&&void 0!==r?r:0)||($u(n,o,`Type index ${String(e)} is out of range.`),!1)}function Wu(e,t,n,o){if(!Ku(e.type,t,n,`${o}/type`))return;if(void 0===e.value)return;const s=t.types[e.type],r=Pu[s.signature];r&&"custom"!==s.signature&&e.value.length!==r.length&&$u(n,`${o}/value`,`Expected ${r.length} value component(s) for type "${s.signature}", received ${e.value.length}.`);for(let t=0;t<e.value.length;t++){const r=e.value[t];let i=!0;switch(s.signature){case"bool":i="boolean"==typeof r;break;case"int":i="number"==typeof r&&Number.isInteger(r)&&r>=-2147483648&&r<=2147483647;break;case"float":case"float2":case"float3":case"float4":case"float2x2":case"float3x3":case"float4x4":i="number"==typeof r&&Number.isFinite(r);break;case"ref":i="string"==typeof r&&Uu(r)}i||$u(n,`${o}/value/${t}`,`Value component is invalid for type "${s.signature}".`)}}function qu(e,t){if(!e)return!1;const n=e=>"number"==typeof e&&Number.isInteger(e)&&e>=-2147483648&&e<=2147483647;switch(t){case"bool":return 1===e.length&&"boolean"==typeof e[0];case"int":return 1===e.length&&n(e[0]);case"int[]":return e.every(n);case"string":return 1===e.length&&"string"==typeof e[0];default:return e.length>0}}function zu(e,t,n){var o,s,r,i,a,l,u,c;switch(t){case"types":return null!==(s=null===(o=e.types)||void 0===o?void 0:o.length)&&void 0!==s?s:0;case"variables":return null!==(i=null===(r=e.variables)||void 0===r?void 0:r.length)&&void 0!==i?i:0;case"events":return null!==(l=null===(a=e.events)||void 0===a?void 0:a.length)&&void 0!==l?l:0;case"nodes":return null!==(c=null===(u=e.nodes)||void 0===u?void 0:u.length)&&void 0!==c?c:0;case"assetNodes":return null!=n?n:0;default:return 0}}function ju(e,t,n,o){var s,r;if(!e||!qu(e.value,t.configurationType)||!e.value)return!1;if(void 0!==t.minItems&&e.value.length<t.minItems)return!1;if(void 0!==t.minimum&&e.value.some(e=>"number"!=typeof e||e<t.minimum))return!1;if(void 0!==t.maximum&&e.value.some(e=>"number"!=typeof e||e>t.maximum))return!1;if(t.indexSource){const s=zu(n,t.indexSource,o);if(e.value.some(e=>!Gu(e,s)))return!1}if(t.allowedSignatures){const o=e.value[0],i="number"==typeof o?null===(r=null===(s=n.types)||void 0===s?void 0:s[o])||void 0===r?void 0:r.signature:void 0;if(!i||!t.allowedSignatures.includes(i))return!1}return!(t.debugLogTemplate&&!Lu(e.value[0]).valid)}function Xu(e,t,n,o){var s,r;for(const[i,a]of Object.entries(null!==(s=t.configuration)&&void 0!==s?s:{})){if(!a.generatesOutputFlowSockets)continue;const t=null===(r=e.configuration)||void 0===r?void 0:r[i],s=ju(t,a,n,o)?t.value:a.defaultValue;return new Set(Array.isArray(s)?s.map(String):[])}}function Yu(e,t,n){var o;const s=null===(o=e.outputs)||void 0===o?void 0:o.flows;return!(!s||!Object.prototype.hasOwnProperty.call(s,t))||(!Object.keys(null!=s?s:{}).some(e=>e.startsWith("[")&&e.endsWith("]"))||!n||n.has(t))}function Qu(e,t,n){var o,s,r,i,a,l,u,c;const d=Vu(e);for(let e=0;e<(null!==(s=null===(o=d.nodes)||void 0===o?void 0:o.length)&&void 0!==s?s:0);e++){const o=d.nodes[e],s=t[o.declaration];if(!s||"unknown-core"===s.support||"unsupported-extension"===s.support)continue;const h=wu(s.source,!1);if(!(null==h?void 0:h.configuration))continue;const f=new Map;for(const[e,t]of Object.entries(h.configuration))if(t.configurationGroup){const s=ju(null===(r=o.configuration)||void 0===r?void 0:r[e],t,d,n);f.set(t.configurationGroup,(null===(i=f.get(t.configurationGroup))||void 0===i||i)&&s)}for(const[e,t]of Object.entries(h.configuration)){const s=(!t.configurationGroup||!0===f.get(t.configurationGroup))&&ju(null===(a=o.configuration)||void 0===a?void 0:a[e],t,d,n);s||void 0===t.defaultValue?s&&t.uniqueValues&&(null===(c=null===(u=o.configuration)||void 0===u?void 0:u[e])||void 0===c?void 0:c.value)&&(o.configuration[e].value=Array.from(new Set(o.configuration[e].value))):(null!==(l=o.configuration)&&void 0!==l||(o.configuration={}),o.configuration[e]={value:Array.isArray(t.defaultValue)?Du(t.defaultValue):[t.defaultValue]})}}return d}function Zu(e){const t=[];for(const n of e.split("/")){const e=n.startsWith("[")&&!n.startsWith("[[")?"int":n.startsWith("{")&&!n.startsWith("{{")?"ref":void 0;if(e){const o=n.substring(1,n.length-1).replace(/~1/g,"/").replace(/~0/g,"~");t.push({name:o,signature:e})}}return t}function Ju(e,t,n,o=new Set){var s;return"node"in e?ec(e.node,null!==(s=e.socket)&&void 0!==s?s:"value",t,n,o):e.type}function ec(e,t,n,o,s=new Set){var r,i,a,l,u,c,d,h,f,p,m,_,g,v,y,b,x,T,A,M,w,S,C,R,I;const O=`${e}:${t}`;if(s.has(O))return;if(s.add(O),!Gu(e,null!==(i=null===(r=n.nodes)||void 0===r?void 0:r.length)&&void 0!==i?i:0))return;const F=n.nodes[e];if(!Gu(F.declaration,o.length))return;const E=o[F.declaration],L=null===(l=null===(a=E.source.outputValueSockets)||void 0===a?void 0:a[t])||void 0===l?void 0:l.type;if(void 0!==L)return L;if("isValid"===t)return(()=>{var e;return null===(e=n.types)||void 0===e?void 0:e.findIndex(e=>"bool"===e.signature)})();if("pointer/get"===E.operation&&"value"===t){const e=null===(d=null===(c=null===(u=F.configuration)||void 0===u?void 0:u.type)||void 0===c?void 0:c.value)||void 0===d?void 0:d[0];return"number"==typeof e?e:void 0}if("variable/get"===E.operation&&"value"===t){const e=null===(p=null===(f=null===(h=F.configuration)||void 0===h?void 0:h.variable)||void 0===f?void 0:f.value)||void 0===p?void 0:p[0];return"number"==typeof e?null===(_=null===(m=n.variables)||void 0===m?void 0:m[e])||void 0===_?void 0:_.type:void 0}if("math/switch"===E.operation&&"value"===t){const e=null===(g=F.values)||void 0===g?void 0:g.default;return e?Ju(e,n,o,s):void 0}if("event/receive"===E.operation&&"event"!==t){const e=null===(b=null===(y=null===(v=F.configuration)||void 0===v?void 0:v.event)||void 0===y?void 0:y.value)||void 0===b?void 0:b[0];return"number"==typeof e?null===(M=null===(A=null===(T=null===(x=n.events)||void 0===x?void 0:x[e])||void 0===T?void 0:T.values)||void 0===A?void 0:A[t])||void 0===M?void 0:M.type:void 0}const N=function(e,t){return"value"!==t?"math/rgbToOkLCh"===e&&["l","c","h"].includes(t)||"math/rgbFromOkLCh"===e&&["r","g","b"].includes(t)||e.startsWith("math/extract")?"float":"math/matDecompose"===e?"rotation"===t?"float4":"translation"===t||"scale"===t?"float3":void 0:"math/quatToAxisAngle"===e?"axis"===t?"float3":"angle"===t?"float":void 0:"flow/doN"===e&&"currentCount"===t||"flow/for"===e&&"index"===t?"int":"flow/setDelay"===e&&"lastDelay"===t?"ref":"flow/throttle"===e&&"lastRemainingTime"===t?"float":"event/onStart"!==e&&"event/onTick"!==e&&"event/receive"!==e||"event"!==t?"event/onTick"===e&&"timeSinceLastTick"===t||"event/onTick"===e&&"timeSinceStart"===t?"float":void 0:"ref":["math/E","math/Pi","math/Tau","math/Inf","math/NaN","math/random","math/length","math/dot","math/determinant","math/quatAngleBetween"].includes(e)?"float":["math/eq","ref/eq","math/lt","math/le","math/gt","math/ge","math/isNaN","math/isInf","type/intToBool","type/floatToBool"].includes(e)?"bool":["math/clz","math/ctz","math/popcnt","type/boolToInt","type/floatToInt"].includes(e)?"int":["type/boolToFloat","type/intToFloat"].includes(e)?"float":void 0}(E.operation,t);if(N)return null===(w=n.types)||void 0===w?void 0:w.findIndex(e=>e.signature===N);const k=wu(E.source,!1),B=null===(C=null===(S=null==k?void 0:k.outputs)||void 0===S?void 0:S.values)||void 0===C?void 0:C[t],P=null==B?void 0:B.gltfType,D="number"===P?"float":"boolean"===P?"bool":P;if(D&&D in Pu)return null===(R=n.types)||void 0===R?void 0:R.findIndex(e=>e.signature===D);const V=(null==B?void 0:B.typeSourceInput)?null===(I=F.values)||void 0===I?void 0:I[B.typeSourceInput]:void 0;return V?Ju(V,n,o,s):void 0}function tc(e,t,n,o,s,r,i){var a,l,u,c,d,h,f,p,m,_,g,v,y,b,x,T,A,M,w,S,C,R,I,O,F,E,L,N,k,B,P,D,V,G,$,U,H,K,W,q,z,j,X;const Y=`${r}/nodes/${t}`;if(!Gu(e.declaration,o.length))return void $u(s,`${Y}/declaration`,`Declaration index ${String(e.declaration)} is out of range.`);const Q=o[e.declaration],Z="unsupported-extension"===Q.support?Su(Q.source):wu(Q.source,!1);if("unknown-core"===Q.support||!Z)return;const J=(e,t,n)=>{e.invalidUsesDefault||void 0!==e.defaultValue?function(e,t,n){e.push({path:t,message:n,severity:"warning"})}(s,t,`${n} The default configuration will be used.`):$u(s,t,n)};for(const[t,n]of Object.entries(null!==(a=e.configuration)&&void 0!==a?a:{}))n.value&&0===n.value.length&&$u(s,`${Y}/configuration/${t}/value`,"Configuration value arrays must contain at least one item when present.");for(const[t,r]of Object.entries(null!==(l=Z.configuration)&&void 0!==l?l:{})){const a=null===(u=e.configuration)||void 0===u?void 0:u[t],l=!!a&&qu(a.value,r.configurationType);if(!a&&r.required?$u(s,`${Y}/configuration/${t}`,`Required configuration "${t}" is missing.`):a&&!l&&J(r,`${Y}/configuration/${t}`,`Configuration "${t}" is invalid.`),l&&a.value&&void 0!==r.minItems&&a.value.length<r.minItems&&$u(s,`${Y}/configuration/${t}/value`,`Configuration "${t}" requires at least ${r.minItems} value(s).`),l&&a.value&&r.indexSource){const e=zu(n,r.indexSource,i);for(let n=0;n<a.value.length;n++)Gu(a.value[n],e)||J(r,`${Y}/configuration/${t}/value/${n}`,`Index is out of range for graph ${r.indexSource}.`)}if(l&&a.value&&r.allowedSignatures){const e=a.value[0],o="number"==typeof e?null===(d=null===(c=n.types)||void 0===c?void 0:c[e])||void 0===d?void 0:d.signature:void 0;o&&r.allowedSignatures.includes(o)||J(r,`${Y}/configuration/${t}/value/0`,`Type "${String(o)}" is not supported by this operation.`)}if(l&&a.value&&r.debugLogTemplate&&!Lu(a.value[0]).valid&&J(r,`${Y}/configuration/${t}/value/0`,`Configuration "${t}" is not a valid debug message template.`),l&&a.value&&(void 0!==r.minimum||void 0!==r.maximum)){const e=a.value[0];(void 0!==r.minimum&&e<r.minimum||void 0!==r.maximum&&e>r.maximum)&&J(r,`${Y}/configuration/${t}/value/0`,`Configuration "${t}" must be between ${String(r.minimum)} and ${String(r.maximum)}.`)}if(l&&a.value&&r.generatesInputValueSockets)for(const t of a.value){if("number"!=typeof t||!Gu(t,null!==(f=null===(h=n.variables)||void 0===h?void 0:h.length)&&void 0!==f?f:0))continue;const r=null===(p=e.values)||void 0===p?void 0:p[String(t)];r?Ju(r,n,o)!==n.variables[t].type&&$u(s,`${Y}/values/${t}/type`,`Configured input value socket "${t}" has the wrong type.`):$u(s,`${Y}/values/${t}`,`Required configured input value socket "${t}" is missing.`)}if(l&&a.value&&r.generatesCaseInputValueSockets){const t=(null===(m=e.values)||void 0===m?void 0:m.default)?Ju(e.values.default,n,o):void 0;for(const r of a.value){const i=null===(_=e.values)||void 0===_?void 0:_[String(r)];i?void 0!==t&&Ju(i,n,o)!==t&&$u(s,`${Y}/values/${r}/type`,`Case input value socket "${r}" must match the default socket type.`):$u(s,`${Y}/values/${r}`,`Required case input value socket "${r}" is missing.`)}}if(l&&a.value&&r.pointerTemplate&&"string"==typeof a.value[0])for(const t of Zu(a.value[0])){const r=null===(g=e.values)||void 0===g?void 0:g[t.name],i=null!==(y=null===(v=n.types)||void 0===v?void 0:v.findIndex(e=>e.signature===t.signature))&&void 0!==y?y:-1;r?(i<0||Ju(r,n,o)!==i)&&$u(s,`${Y}/values/${t.name}/type`,`Pointer template input "${t.name}" must have type "${t.signature}".`):$u(s,`${Y}/values/${t.name}`,`Required pointer template input "${t.name}" is missing.`)}}if("debug/log"===Q.operation){const t=null===(b=Z.configuration)||void 0===b?void 0:b.severity,o=null===(x=Z.configuration)||void 0===x?void 0:x.message,r=!!t&&ju(null===(T=e.configuration)||void 0===T?void 0:T.severity,t,n,i),a=!!o&&ju(null===(A=e.configuration)||void 0===A?void 0:A.message,o,n,i),l=r&&a?e.configuration.message.value[0]:"";for(const t of Lu(l).sockets)(null===(M=e.values)||void 0===M?void 0:M[t])||$u(s,`${Y}/values/${t}`,`Required debug message template input "${t}" is missing.`)}for(const[t,r]of Object.entries(null!==(S=null===(w=Z.inputs)||void 0===w?void 0:w.values)&&void 0!==S?S:{})){if(t.startsWith("[")||(null===(C=e.values)||void 0===C?void 0:C[t])||$u(s,`${Y}/values/${t}`,`Required input value socket "${t}" is missing.`),"event/send"===Q.operation){const t=null===(O=null===(I=null===(R=e.configuration)||void 0===R?void 0:R.event)||void 0===I?void 0:I.value)||void 0===O?void 0:O[0],r="number"==typeof t?null===(F=n.events)||void 0===F?void 0:F[t]:void 0;for(const[t,i]of Object.entries(null!==(E=null==r?void 0:r.values)&&void 0!==E?E:{})){const r=null===(L=e.values)||void 0===L?void 0:L[t];r?Ju(r,n,o)!==i.type&&$u(s,`${Y}/values/${t}/type`,`Custom event input value socket "${t}" has the wrong type.`):$u(s,`${Y}/values/${t}`,`Required custom event input value socket "${t}" is missing.`)}}const i="number"===r.gltfType?"float":"boolean"===r.gltfType?"bool":r.gltfType,a=null===(N=e.values)||void 0===N?void 0:N[t];if(a&&i&&i in Pu){const e=Ju(a,n,o);void 0!==e&&(null===(B=null===(k=n.types)||void 0===k?void 0:k[e])||void 0===B?void 0:B.signature)!==i&&$u(s,`${Y}/values/${t}/type`,`Input value socket "${t}" must have type "${i}".`)}}if(Z.validation)try{const t=Du(e);for(const e of Object.values(null!==(P=t.values)&&void 0!==P?P:{}))void 0===e.type&&(e.type=Ju(e,n,o));const r=Z.validation(t,n);r.valid||$u(s,Y,null!==(D=r.error)&&void 0!==D?D:`Operation "${Q.operation}" is invalid.`)}catch(e){$u(s,Y,e.message)}for(const[r,i]of Object.entries(null!==(V=e.values)&&void 0!==V?V:{}))if("unsupported-extension"!==Q.support||(null===(G=Q.source.inputValueSockets)||void 0===G?void 0:G[r])||$u(s,`${Y}/values/${r}`,`Input value socket "${r}" is not defined by operation "${Q.operation}".`),"node"in i){if("value"in i&&$u(s,`${Y}/values/${r}`,"An input value socket cannot define both inline and node sources."),!Gu(i.node,null!==(U=null===($=n.nodes)||void 0===$?void 0:$.length)&&void 0!==U?U:0)){$u(s,`${Y}/values/${r}/node`,`Node index ${String(i.node)} is out of range.`);continue}i.node>=t&&$u(s,`${Y}/values/${r}/node`,"Value connections must reference an earlier node."),void 0!==i.type&&Ku(i.type,n,s,`${Y}/values/${r}/type`);const e=n.nodes[i.node];if(Gu(e.declaration,o.length)){const t=o[e.declaration],a="unsupported-extension"===t.support?Su(t.source):wu(t.source,!1),l=null!==(H=i.socket)&&void 0!==H?H:"value",u=Hu(null===(K=null==a?void 0:a.outputs)||void 0===K?void 0:K.values,l,t,e,n,"value");a&&!u&&$u(s,`${Y}/values/${r}/socket`,`Output value socket "${l}" does not exist on node ${i.node}.`);const c=null===(q=null===(W=t.source.outputValueSockets)||void 0===W?void 0:W[l])||void 0===q?void 0:q.type,d=null!=c?c:ec(i.node,l,n,o);void 0!==i.type&&void 0!==d&&i.type!==d&&$u(s,`${Y}/values/${r}/type`,`Type assertion does not match output socket "${l}".`)}}else Wu(i,n,s,`${Y}/values/${r}`);for(const[o,r]of Object.entries(null!==(z=e.flows)&&void 0!==z?z:{}))Yu(Z,o,Xu(e,Z,n,i))||$u(s,`${Y}/flows/${o}`,`Output flow socket "${o}" is not defined by operation "${Q.operation}".`),Gu(r.node,null!==(X=null===(j=n.nodes)||void 0===j?void 0:j.length)&&void 0!==X?X:0)?r.node<=t&&$u(s,`${Y}/flows/${o}/node`,"Flow connections must reference a later node."):$u(s,`${Y}/flows/${o}/node`,`Node index ${String(r.node)} is out of range.`)}function nc(e,t=0,n,o){var s,r,i,a,l,u,c,d,h,f,p,m,_,g,v,y,b;const x=[],T=`/extensions/KHR_interactivity/graphs/${t}`;null===e||"object"!=typeof e||Array.isArray(e)?($u(x,T,"Behavior graph must be an object."),e={}):e=Vu(e);const A={types:()=>({signature:"custom"}),variables:()=>({type:-1}),events:()=>({}),declarations:()=>({op:""}),nodes:()=>({declaration:-1})};for(const t of["types","variables","events","declarations","nodes"]){const n=e[t];void 0===n||Array.isArray(n)?Array.isArray(n)&&0===n.length?$u(x,`${T}/${t}`,`"${t}" must contain at least one item when present.`):Array.isArray(n)&&(e[t]=n.map((e,n)=>null===e||"object"!=typeof e||Array.isArray(e)?($u(x,`${T}/${t}/${n}`,`Each "${t}" item must be an object.`),A[t]()):e)):($u(x,`${T}/${t}`,`"${t}" must be an array when present.`),e[t]=[])}for(let t=0;t<(null!==(r=null===(s=e.events)||void 0===s?void 0:s.length)&&void 0!==r?r:0);t++)e.events[t].values&&0===Object.keys(e.events[t].values).length&&$u(x,`${T}/events/${t}/values`,'"values" must contain at least one property when present.');for(let t=0;t<(null!==(a=null===(i=e.declarations)||void 0===i?void 0:i.length)&&void 0!==a?a:0);t++){const n=e.declarations[t];for(const e of["inputValueSockets","outputValueSockets"])n[e]&&0===Object.keys(n[e]).length&&$u(x,`${T}/declarations/${t}/${e}`,`"${e}" must contain at least one property when present.`)}for(let t=0;t<(null!==(u=null===(l=e.nodes)||void 0===l?void 0:l.length)&&void 0!==u?u:0);t++){const n=e.nodes[t];for(const e of["configuration","values","flows"])n[e]&&0===Object.keys(n[e]).length&&$u(x,`${T}/nodes/${t}/${e}`,`"${e}" must contain at least one property when present.`)}const M=new Set,w=(null!==(c=e.declarations)&&void 0!==c?c:[]).map((t,o)=>{var s,r,i,a;const l=Object.keys(null!==(s=t.inputValueSockets)&&void 0!==s?s:{}).sort().map(e=>`${JSON.stringify(e)}:${t.inputValueSockets[e].type}`).join(","),u=`${JSON.stringify(t.op)}:${JSON.stringify(null!==(r=t.extension)&&void 0!==r?r:"")}:${l}`;M.has(u)&&$u(x,`${T}/declarations/${o}`,"Duplicate equivalent declaration."),M.add(u);const{support:c}=function(e,t,n){const o=e.extension&&n&&!n.has(e.extension)?void 0:wu(e,!1);return o?e.extension&&o.declarationSchema&&!function(e,t,n){const o=(e,n)=>{const o=Object.keys(null!=e?e:{}).sort(),s=Object.keys(n).sort();return o.length===s.length&&!o.some((e,t)=>e!==s[t])&&o.every(o=>{var s,r;return(null===(r=null===(s=t.types)||void 0===s?void 0:s[e[o].type])||void 0===r?void 0:r.signature)===n[o]})};return o(e.inputValueSockets,n.inputValueSockets)&&o(e.outputValueSockets,n.outputValueSockets)}(e,t,o.declarationSchema)?{mapping:void 0,support:"unsupported-extension"}:{mapping:o,support:e.extension?"extension":"core"}:{mapping:void 0,support:e.extension?"unsupported-extension":"unknown-core"}}(t,e,n);"unknown-core"===c&&$u(x,`${T}/declarations/${o}/op`,`Unknown core operation "${t.op}".`),t.extension||!t.inputValueSockets&&!t.outputValueSockets||$u(x,`${T}/declarations/${o}`,"Core operation declarations cannot define dynamic value sockets.");for(const[n,s]of Object.entries(null!==(i=t.inputValueSockets)&&void 0!==i?i:{}))Ku(s.type,e,x,`${T}/declarations/${o}/inputValueSockets/${n}/type`);for(const[n,s]of Object.entries(null!==(a=t.outputValueSockets)&&void 0!==a?a:{}))Ku(s.type,e,x,`${T}/declarations/${o}/outputValueSockets/${n}/type`);return{index:o,operation:t.extension?`${t.op}:${t.extension}`:t.op,support:c,source:t}}),S=new Set;for(let t=0;t<(null!==(h=null===(d=e.types)||void 0===d?void 0:d.length)&&void 0!==h?h:0);t++){const n=e.types[t].signature;"custom"!==n&&S.has(n)&&$u(x,`${T}/types/${t}/signature`,`Duplicate built-in type signature "${n}".`),S.add(n),"custom"===n||Pu[n]||$u(x,`${T}/types/${t}/signature`,`Unknown built-in type signature "${n}".`)}for(let t=0;t<(null!==(p=null===(f=e.variables)||void 0===f?void 0:f.length)&&void 0!==p?p:0);t++)Wu(e.variables[t],e,x,`${T}/variables/${t}`);for(let t=0;t<(null!==(_=null===(m=e.events)||void 0===m?void 0:m.length)&&void 0!==_?_:0);t++){const n=e.events[t].id;void 0!==n&&e.events.slice(0,t).some(e=>e.id===n)&&$u(x,`${T}/events/${t}/id`,`Duplicate event id "${n}".`),e.events[t].values&&Object.prototype.hasOwnProperty.call(e.events[t].values,"event")&&$u(x,`${T}/events/${t}/values/event`,'Custom event value socket id "event" is reserved.');for(const[n,o]of Object.entries(null!==(g=e.events[t].values)&&void 0!==g?g:{}))Wu(o,e,x,`${T}/events/${t}/values/${n}`)}for(let t=0;t<(null!==(y=null===(v=e.nodes)||void 0===v?void 0:v.length)&&void 0!==y?y:0);t++)tc(e.nodes[t],t,e,w,x,T,o);return{index:t,path:T,name:null!==(b=e.name)&&void 0!==b?b:`Graph ${t+1}`,source:e,effectiveSource:Qu(e,w,o),declarations:w,diagnostics:x,valid:!x.some(e=>"error"===e.severity)}}function oc(e,t,n){var o;const s=Du(e),r=[];Array.isArray(s.graphs)||($u(r,"/extensions/KHR_interactivity/graphs",'"graphs" must be an array.'),s.graphs=[]),0===s.graphs.length&&$u(r,"/extensions/KHR_interactivity/graphs","At least one behavior graph is required.");const i=null!==(o=s.graph)&&void 0!==o?o:0,a=Gu(i,s.graphs.length)?i:-1;-1===a&&$u(r,"/extensions/KHR_interactivity/graph",`Default graph index ${String(i)} is out of range.`);const l=s.graphs.map((e,o)=>nc(e,o,t,n));return s.graphs=l.map(e=>e.source),{specificationCommit:Bu,source:s,defaultGraphIndex:a,graphs:l,diagnostics:r}}const sc="/extensions/KHR_interactivity/events/",rc="/extensions/KHR_interactivity/delays/";function ic(e,t){return e&&Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}class ac{constructor(e,t,n=60,o=0,s,r){var i,a;this._gltf=t,this._animationTargetFps=n,this._graphIndex=o,this._supportedExtensions=s,this._declarationModels=r,this._types=[],this._mappings=[],this._staticVariables=[],this._events=[],this._internalEventsCounter=0,this._nodes=[],this._insertedBlocks=[],this._interactivityGraph=this._declarationModels?Qu(e,this._declarationModels,null!==(a=null===(i=this._gltf.nodes)||void 0===i?void 0:i.length)&&void 0!==a?a:0):Vu(e),this._parseTypes(),this._parseDeclarations(),this._parseVariables(),this._parseEvents(),this._parseNodes()}get _strictValidation(){return!!this._declarationModels}_hasDefaultFlowInput(e){return"flow/waitAll"!==e&&(e.startsWith("flow/")||e.startsWith("animation/")||"pointer/set"===e||"pointer/interpolate"===e||"variable/set"===e||"variable/interpolate"===e||"event/send"===e||"event/stopPropagation"===e||"flow/log:BABYLON"===e)}_getAllowedDynamicValueSockets(e,t,n){var o,s,r,i,a,l,u,c,d,h,f,p,m,_,g,v,y,b;if(("debug/log"===e||"flow/log:BABYLON"===e)&&"input"===n){const n=null===(r=null===(s=null===(o=t.configuration)||void 0===o?void 0:o["debug/log"===e?"message":"messageTemplate"])||void 0===s?void 0:s.value)||void 0===r?void 0:r[0];return new Set("string"==typeof n?Lu(n).sockets:[])}if("event/send"===e&&"input"===n||"event/receive"===e&&"output"===n){const e=null===(l=null===(a=null===(i=t.configuration)||void 0===i?void 0:i.event)||void 0===a?void 0:a.value)||void 0===l?void 0:l[0];if("number"==typeof e)return new Set(Object.keys(null!==(d=null===(c=null===(u=this._interactivityGraph.events)||void 0===u?void 0:u[e])||void 0===c?void 0:c.values)&&void 0!==d?d:{}))}if("variable/set"===e&&"input"===n)return new Set((null!==(p=null===(f=null===(h=t.configuration)||void 0===h?void 0:h.variables)||void 0===f?void 0:f.value)&&void 0!==p?p:[]).map(String));if("math/switch"===e&&"input"===n)return new Set((null!==(g=null===(_=null===(m=t.configuration)||void 0===m?void 0:m.cases)||void 0===_?void 0:_.value)&&void 0!==g?g:[]).map(String));if(("pointer/get"===e||"pointer/set"===e||"pointer/interpolate"===e)&&"input"===n){const e=null===(b=null===(y=null===(v=t.configuration)||void 0===v?void 0:v.pointer)||void 0===y?void 0:y.value)||void 0===b?void 0:b[0];if("string"==typeof e)return new Set(e.split("/").filter(e=>e.startsWith("[")&&!e.startsWith("[[")||e.startsWith("{")&&!e.startsWith("{{")).map(e=>e.substring(1,e.length-1).replace(/~1/g,"/").replace(/~0/g,"~")))}}_getAllowedDynamicFlowSockets(e,t,n){var o,s,r;for(const[i,a]of Object.entries(null!==(o=t.configuration)&&void 0!==o?o:{})){if(!("input"===n?a.generatesInputFlowSockets:a.generatesOutputFlowSockets))continue;const t=null===(r=null===(s=e.configuration)||void 0===s?void 0:s[i])||void 0===r?void 0:r.value,o=t&&t.length>0&&("int"!==a.configurationType||1===t.length)&&t.every(e=>{var t,n;return"number"==typeof e&&Number.isInteger(e)&&e>=(null!==(t=a.minimum)&&void 0!==t?t:-2147483648)&&e<=(null!==(n=a.maximum)&&void 0!==n?n:2147483647)}),l=o?t:a.defaultValue;if("input"===n){const e=Array.isArray(l)&&"number"==typeof l[0]?l[0]:0;return new Set(Array.from({length:e},(e,t)=>String(t)))}return new Set(Array.isArray(l)?l.map(String):[])}}get arrays(){return{types:this._types,mappings:this._mappings,staticVariables:this._staticVariables,events:this._events,nodes:this._nodes}}_parseTypes(){if(this._interactivityGraph.types)for(const e of this._interactivityGraph.types)this._types.push(Pu[e.signature])}_parseDeclarations(){var e;if(this._interactivityGraph.declarations)for(let n=0;n<this._interactivityGraph.declarations.length;n++){const o=this._interactivityGraph.declarations[n],s=null===(e=this._declarationModels)||void 0===e?void 0:e[n],r=!o.extension||!this._supportedExtensions||this._supportedExtensions.has(o.extension),i="unsupported-extension"===(null==s?void 0:s.support)?void 0:r?wu(o,!1):void 0;if(!i&&!o.extension)throw new Error(`Unknown core KHR_interactivity operation "${o.op}".`);const a=null!=i?i:o.extension?Su(o):void 0;if(!a)throw t.Logger.Error(["No mapping found for declaration",o]),new Error("Error parsing declarations");this._mappings.push({flowGraphMapping:a,fullOperationName:o.extension?o.op+":"+o.extension:o.op,declaration:null!=s?s:{index:n,operation:o.extension?`${o.op}:${o.extension}`:o.op,support:i?o.extension?"extension":"core":"unsupported-extension",source:o}})}}_parseVariables(){if(this._interactivityGraph.variables)for(const e of this._interactivityGraph.variables){const t=this._parseVariable(e);this._staticVariables.push(t)}}_parseVariable(e,n){var o,s;const r=this._types[e.type];if(!r)throw t.Logger.Error(["No type found for variable",e]),new Error("Error parsing variables");if(e.value&&"custom"!==(null===(s=null===(o=this._interactivityGraph.types)||void 0===o?void 0:o[e.type])||void 0===s?void 0:s.signature)&&e.value.length!==r.length)throw t.Logger.Error(["Invalid value length for variable",e,r]),new Error("Error parsing variables");const i=e.value?e.value.slice():[];if(!i.length)switch(r.flowGraphType){case"boolean":i.push(!1);break;case"FlowGraphInteger":i.push(0);break;case"number":i.push(NaN);break;case"string":i.push("");break;case"Vector2":i.push(NaN,NaN);break;case"Vector3":i.push(NaN,NaN,NaN);break;case"Vector4":case"Matrix2D":case"Quaternion":i.push(NaN,NaN,NaN,NaN);break;case"Matrix":for(let e=0;e<16;e++)i.push(NaN);break;case"Matrix3D":for(let e=0;e<9;e++)i.push(NaN)}return"number"===r.elementType&&"string"==typeof i[0]?i[0]=parseFloat(i[0]):"string"===r.flowGraphType&&"string"==typeof i[0]&&(i[0]=this._normalizeStaticReference(i[0])),{type:r.flowGraphType,value:n?n(i,this):i}}_normalizeStaticReference(e){if(!e||e.startsWith(sc)||e.startsWith(rc))return"";if(!e.startsWith("/"))return"";let t=this._gltf;for(const n of e.substring(1).split("/")){const e=n.replace(/~1/g,"/").replace(/~0/g,"~");if(Array.isArray(t)){if(!/^(0|[1-9]\d*)$/.test(e))return"";t=t[parseInt(e,10)]}else{if(null===t||"object"!=typeof t||!Object.prototype.hasOwnProperty.call(t,e))return"";t=t[e]}}return null!==t&&"object"==typeof t?e:""}_parseEvents(){var e;if(!this._interactivityGraph.events)return;const n=new Set(this._interactivityGraph.events.flatMap(e=>void 0===e.id?[]:[e.id])),o=`__babylon_khr_internal_${this._graphIndex}_`;for(const s of this._interactivityGraph.events){let r;if(void 0===s.id){do{r=o+this._internalEventsCounter++}while(n.has(r));n.add(r)}const i={eventId:null!==(e=s.id)&&void 0!==e?e:r};s.values&&(i.eventData=Object.keys(s.values).map(e=>{var n;const o=null===(n=s.values)||void 0===n?void 0:n[e];if(!o)throw t.Logger.Error(["No value found for event key",e]),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:e,type:r.flowGraphType,eventData:!0,value:i}})),this._events.push(i)}}_parseNodes(){var e;if(this._interactivityGraph.nodes)for(let n=0;n<this._interactivityGraph.nodes.length;n++){const o=this._interactivityGraph.nodes[n];if("number"!=typeof o.declaration)throw t.Logger.Error(["No declaration found for node",o]),new Error("Error parsing nodes");const s=this._mappings[o.declaration];if(!s)throw t.Logger.Error(["No mapping found for node",o]),new Error("Error parsing nodes");if(s.flowGraphMapping.validation){const t=s.flowGraphMapping.validation(o,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[o.declaration].op} - ${t.error}`)}const r=[];"unsupported-extension"===s.declaration.support&&r.push(this._createUnsupportedExtensionBlock(o,n,s));for(let e=0;e<s.flowGraphMapping.blocks.length;e++){const t=s.flowGraphMapping.blocks[e],i=this._getEmptyBlock(t,s.fullOperationName,n,o.declaration,e);this._parseNodeConfiguration(o,i,s.flowGraphMapping,t),r.push(i)}this._nodes.push({blocks:r,fullOperationName:s.fullOperationName})}}_getEmptyBlock(e,n,o,s,r){return{uniqueId:t.RandomGUID(),className:e,dataInputs:[],dataOutputs:[],signalInputs:[],signalOutputs:[],config:{},type:n,metadata:void 0===o?{}:{khrInteractivity:{graphIndex:this._graphIndex,nodeIndex:o,declarationIndex:s,operation:n,role:null!=r?r:0,sourcePath:`/extensions/KHR_interactivity/graphs/${this._graphIndex}/nodes/${o}`}}}}_createUnsupportedExtensionBlock(e,t,n){var o,s,r,i;const a=this._getEmptyBlock("KHR_interactivity/FlowGraphUnsupportedInteractivityBlock",n.fullOperationName,t,e.declaration,0),l=new Set;for(const e of null!==(o=this._interactivityGraph.nodes)&&void 0!==o?o:[])for(const n of Object.values(null!==(s=e.flows)&&void 0!==s?s:{}))n.node===t&&l.add(null!==(r=n.socket)&&void 0!==r?r:"in");const u=e=>Object.entries(null!=e?e:{}).map(([e,t])=>{var n,o,s;return{name:e,type:null===(n=this._types[t.type])||void 0===n?void 0:n.flowGraphType,signature:null===(s=null===(o=this._interactivityGraph.types)||void 0===o?void 0:o[t.type])||void 0===s?void 0:s.signature}});a.config={operation:n.fullOperationName,inputValueSockets:u(n.declaration.source.inputValueSockets),outputValueSockets:u(n.declaration.source.outputValueSockets),inputFlowSockets:Array.from(l).sort(),outputFlowSockets:Object.keys(null!==(i=e.flows)&&void 0!==i?i:{}).sort()};for(const e of a.config.inputValueSockets)a.dataInputs.push(this._createNewSocketConnection(e.name));for(const e of a.config.outputValueSockets)a.dataOutputs.push(this._createNewSocketConnection(e.name,!0));for(const e of a.config.inputFlowSockets)a.signalInputs.push(this._createNewSocketConnection(e));for(const e of a.config.outputFlowSockets)a.signalOutputs.push(this._createNewSocketConnection(e,!0));return a}_parseNodeConfiguration(e,n,o,s){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=o.configuration)||void 0===r?void 0:r[e];if((l||!this._strictValidation)&&(!(null==l?void 0:l.validationOnly)&&(l&&l.toBlock?l.toBlock===s:0===o.blocks.indexOf(s)))){let o=null==l?void 0:l.defaultValue;(null==a?void 0:a.value)&&(o=a.value),(null==l?void 0:l.isArray)||(1!==o.length&&t.Logger.Warn(`Invalid non-array value length: ${o.length}`),o=o[0]),(null==l?void 0:l.dataTransformer)&&(o=l.dataTransformer(o,this)),void 0!==o&&(n.config[(null==l?void 0:l.name)||e]={value:o})}}}_parseNodeConnections(e){var n,o,s,r,i,a,l,u,c,d,h,f,p,m,_,g,v,y,b,x,T,A,M,w;for(let S=0;S<this._nodes.length;S++){const C=null===(n=this._interactivityGraph.nodes)||void 0===n?void 0:n[S];if(!C)throw t.Logger.Error(["No node found for interactivity node",this._nodes[S]]),new Error("Error parsing node connections");const R=this._nodes[S],I=this._mappings[C.declaration];if(!I)throw t.Logger.Error(["No mapping found for node",C]),new Error("Error parsing node connections");if(0===R.blocks.length){t.Logger.Warn(`Skipping connections for no-op node #${S} (unsupported operation: ${R.fullOperationName})`);continue}const O=C.flows||{},F=Object.keys(O).sort();for(const e of F){const n=O[e];let m=ic(null===(o=I.flowGraphMapping.outputs)||void 0===o?void 0:o.flows,e);this._strictValidation&&(null==m?void 0:m.compatibilityOnly)&&(m=void 0);let _=!1;if(!m)for(const e in null===(s=I.flowGraphMapping.outputs)||void 0===s?void 0:s.flows)if(e.startsWith("[")&&e.endsWith("]")){const t=null===(i=null===(r=I.flowGraphMapping.outputs)||void 0===r?void 0:r.flows)||void 0===i?void 0:i[e];if(!this._strictValidation||!(null==t?void 0:t.compatibilityOnly)){_=!0,m=t;break}}const g=_?this._getAllowedDynamicFlowSockets(C,I.flowGraphMapping,"output"):void 0;if(this._strictValidation&&g&&!g.has(e)&&(m=void 0),!m&&!this._isUnsupportedExtensionBlock(R.blocks[0]))continue;const v=m?_?m.name.replace("$1",e):m.name:e,y=n.node,b=this._nodes[y];if(!b)throw t.Logger.Error(["No node found for input node id",y]),new Error("Error parsing node connections");if(0===b.blocks.length){t.Logger.Warn(`Dropping flow connection from node #${S} "${e}" to no-op node #${y} (unsupported operation: ${b.fullOperationName})`);continue}const x=m&&m.toBlock&&R.blocks.find(e=>e.className===m.toBlock)||R.blocks[0],T=null!==(a=x.signalOutputs.find(e=>e.name===v))&&void 0!==a?a:this._createNewSocketConnection(v,!0);x.signalOutputs.includes(T)||x.signalOutputs.push(T);const A=null===(l=this._mappings[this._interactivityGraph.nodes[y].declaration])||void 0===l?void 0:l.flowGraphMapping;if(!A)throw t.Logger.Error(["No mapping found for input node",b]),new Error("Error parsing node connections");let M=ic(null===(u=A.inputs)||void 0===u?void 0:u.flows,n.socket||"in");this._strictValidation&&(null==M?void 0:M.compatibilityOnly)&&(M=void 0);let w=!1;if(!M){for(const e in null===(c=A.inputs)||void 0===c?void 0:c.flows)if(e.startsWith("[")&&e.endsWith("]")){const t=null===(h=null===(d=A.inputs)||void 0===d?void 0:d.flows)||void 0===h?void 0:h[e];this._strictValidation&&(null==t?void 0:t.compatibilityOnly)||(w=!0,M=t)}const e=w?this._getAllowedDynamicFlowSockets(this._interactivityGraph.nodes[y],A,"input"):void 0;if(this._strictValidation&&e&&!e.has(null!==(f=n.socket)&&void 0!==f?f:"in")&&(M=void 0),!M&&"in"===(null!==(p=n.socket)&&void 0!==p?p:"in")&&this._hasDefaultFlowInput(b.fullOperationName)&&(M={name:"in"}),!M&&!this._isUnsupportedExtensionBlock(b.blocks[0]))continue}const F=M?w?M.name.replace("$1",n.socket||""):M.name:n.socket||"in",E=M&&M.toBlock&&b.blocks.find(e=>e.className===M.toBlock)||b.blocks[0];let L=E.signalInputs.find(e=>e.name===F);L||(L=this._createNewSocketConnection(F),E.signalInputs.push(L)),L.connectedPointIds.push(T.uniqueId),T.connectedPointIds.push(L.uniqueId)}const E=C.values||{},L=Object.keys(E);for(const n of L){const o=E[n];let s=ic(null===(m=I.flowGraphMapping.inputs)||void 0===m?void 0:m.values,n);this._strictValidation&&(null==s?void 0:s.compatibilityOnly)&&(s=void 0);let r=!1;if(!s)for(const e in null===(_=I.flowGraphMapping.inputs)||void 0===_?void 0:_.values)if(e.startsWith("[")&&e.endsWith("]")){const t=null===(v=null===(g=I.flowGraphMapping.inputs)||void 0===g?void 0:g.values)||void 0===v?void 0:v[e];this._strictValidation&&(null==t?void 0:t.compatibilityOnly)||(r=!0,s=t)}const i=r?this._getAllowedDynamicValueSockets(I.fullOperationName,C,"input"):void 0;if(!s||i&&!i.has(n))continue;const a=s?r?s.name.replace("$1",n):s.name:n,l=s&&s.toBlock&&R.blocks.find(e=>e.className===s.toBlock)||R.blocks[0],u=null!==(y=l.dataInputs.find(e=>e.name===a))&&void 0!==y?y:this._createNewSocketConnection(a);l.dataInputs.includes(u)||l.dataInputs.push(u);const c=!!(null==s?void 0:s.convertConnectedTimeToFrames);if(void 0!==o.value){const t=this._parseVariable(o,s&&s.dataTransformer);e._connectionValues[u.uniqueId]=t}else{if(void 0===o.node)throw t.Logger.Error(["Invalid value for value connection",o]),new Error("Error parsing node connections");{const s=o.node,r=o.socket||"value",i=this._nodes[s];if(!i)throw t.Logger.Error(["No node found for output socket reference",o]),new Error("Error parsing node connections");if(0===i.blocks.length){t.Logger.Warn(`Dropping value connection from no-op node #${s} (unsupported operation: ${i.fullOperationName}) into node #${S} "${n}"; consumer will use type-default value`);continue}const a=null===(b=this._mappings[this._interactivityGraph.nodes[s].declaration])||void 0===b?void 0:b.flowGraphMapping;if(!a)throw t.Logger.Error(["No mapping found for output socket reference",o]),new Error("Error parsing node connections");let l=ic(null===(x=a.outputs)||void 0===x?void 0:x.values,r);this._strictValidation&&(null==l?void 0:l.compatibilityOnly)&&(l=void 0);let d=!1;if(!l){for(const e in null===(T=a.outputs)||void 0===T?void 0:T.values)if(e.startsWith("[")&&e.endsWith("]")){const t=null===(M=null===(A=a.outputs)||void 0===A?void 0:A.values)||void 0===M?void 0:M[e];this._strictValidation&&(null==t?void 0:t.compatibilityOnly)||(d=!0,l=t)}const e=d?this._getAllowedDynamicValueSockets(i.fullOperationName,this._interactivityGraph.nodes[s],"output"):void 0;if(!l||e&&!e.has(r))continue}const h=l?d?l.name.replace("$1",r):null==l?void 0:l.name:r,f=l&&l.toBlock&&i.blocks.find(e=>e.className===l.toBlock)||i.blocks[0];let p=f.dataOutputs.find(e=>e.name===h);p||(p=this._createNewSocketConnection(h,!0),f.dataOutputs.push(p)),c?this._connectWithSecondsToFramesConversion(e,p,u,S,C.declaration):(u.connectedPointIds.push(p.uniqueId),p.connectedPointIds.push(u.uniqueId))}}}if(I.flowGraphMapping.interBlockConnectors)for(const e of I.flowGraphMapping.interBlockConnectors){const t=e.input,n=e.output,o=e.isVariable;this._connectFlowGraphNodes(t,n,R.blocks[e.inputBlockIndex],R.blocks[e.outputBlockIndex],o)}if(I.flowGraphMapping.extraProcessor){const n=null===(w=this._interactivityGraph.declarations)||void 0===w?void 0:w[C.declaration];if(!n)throw t.Logger.Error(["No declaration found for extra processor",C]),new Error("Error parsing node connections");R.blocks=I.flowGraphMapping.extraProcessor(C,n,I.flowGraphMapping,this,R.blocks,e,this._gltf)}}}_createNewSocketConnection(e,n){return{uniqueId:t.RandomGUID(),name:e,_connectionType:n?1:0,connectedPointIds:[]}}_isUnsupportedExtensionBlock(e){return"KHR_interactivity/FlowGraphUnsupportedInteractivityBlock"===(null==e?void 0:e.className)}_connectWithSecondsToFramesConversion(e,t,n,o,s){const r=this._getEmptyBlock("FlowGraphMultiplyBlock","FlowGraphMultiplyBlock",o,s,-1);r.config={type:"number"};const i=this._createNewSocketConnection("a"),a=this._createNewSocketConnection("b"),l=this._createNewSocketConnection("value",!0);r.dataInputs.push(i,a),r.dataOutputs.push(l),e._connectionValues[a.uniqueId]={type:"number",value:[this._animationTargetFps]},i.connectedPointIds.push(t.uniqueId),t.connectedPointIds.push(i.uniqueId),n.connectedPointIds.push(l.uniqueId),l.connectedPointIds.push(n.uniqueId),this._insertedBlocks.push(r)}_connectFlowGraphNodes(e,t,n,o,s){const r=s?n.dataInputs:n.signalInputs,i=s?o.dataOutputs:o.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(){var e;const n={uniqueId:t.RandomGUID(),_userVariables:{},_connectionValues:{}};this._parseNodeConnections(n);for(let e=0;e<this._staticVariables.length;e++){const t=this._staticVariables[e];n._userVariables[this.getVariableName(e)]=t}const o=this._nodes.reduce((e,t)=>e.concat(t.blocks),[]).concat(this._insertedBlocks);return{name:null!==(e=this._interactivityGraph.name)&&void 0!==e?e:`Graph ${this._graphIndex+1}`,rightHanded:!0,allBlocks:o,executionContexts:[n]}}}class lc{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 uc="/extensions/BABYLON_scene_objects/";class cc{constructor(e,t){this._scene=e,this._tree=t}convert(e){if(!e.startsWith(uc))throw new Error(`BabylonScenePathToObjectConverter: path "${e}" does not start with the expected prefix "${uc}".`);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],o=this._tree[n];if(!o)throw new Error(`BabylonScenePathToObjectConverter: unknown collection "${n}" in path "${e}".`);if(2===t.length&&"length"===t[1])return{object:this._getCollectionArray(n),info:o.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 s=parseInt(t[1],10);if(!Number.isFinite(s)||s<0)throw new Error(`BabylonScenePathToObjectConverter: invalid uniqueId "${t[1]}" in path "${e}".`);const r=this._lookupInstanceByUniqueId(n,s);if(!r)throw new Error(`BabylonScenePathToObjectConverter: no ${n} instance found with uniqueId ${s} (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=o.__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 dc={isKhrInteractivityRef:!0};class hc{convert(e){const n=e===sc,o=e.endsWith("/")?e.slice(0,-1):e;if(n||o.startsWith(sc)){const t=o.substring(37);return{object:dc,info:{type:"object",isReadOnly:!0,get:()=>n?e:t.length>0?o:void 0,getTarget:()=>dc}}}const s=o.substring(37),r=/^\d+$/.test(s)?parseInt(s,10):NaN;return{object:dc,info:{type:"object",isReadOnly:!0,get:(e,n,o)=>{const s=o;if(!(!s||isNaN(r)||r<0))return t.IsDelayActive(s,r)?new t.FlowGraphInteger(r):void 0},getTarget:()=>dc}}}}const fc="/extensions/KHR_interactivity/limits/",pc={major:2,minor:0},mc=2147483647,_c={maxActiveAnimations:mc,maxActiveDelays:mc,maxActivePropertyInterpolations:mc,maxActiveVariableInterpolations:mc},gc={isKhrInteractivityAssetCapability:!0};class vc{constructor(e,t){this._gltf=e,this._isExtensionEnabled=t}convert(e){const t=e.endsWith("/")?e.slice(0,-1):e;if(t.startsWith(fc)){const n=_c[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("."),o=parseInt(t,10),s=parseInt(n,10);return isNaN(o)?pc:o!==pc.major?o<pc.major?{major:o,minor:isNaN(s)?0:s}:pc:{major:o,minor:Math.min(isNaN(s)?0:s,pc.minor)}}(null===(e=this._gltf.asset)||void 0===e?void 0:e.version)["majorVersion"===n?"major":"minor"]});const o=n.split("/");if(3===o.length&&"extensions"===o[0]&&"enabled"===o[2]){const e=o[1];return this._createAccessor("boolean",()=>this._isExtensionEnabled(e))}throw new Error(`Path ${e} is invalid`)}_createAccessor(e,t){return{object:gc,info:{type:e,isReadOnly:!0,get:t,getTarget:()=>gc}}}}class yc{encodeEventReference(e){return function(e){return sc+e}(e)}decodeEventReference(e){return function(e){return"string"==typeof(t=e)&&t.startsWith(sc)?e.substring(37):void 0;var t}(e)}decodeIndexReference(e,t){if(0===e.length||"/"!==e[0])return;const n=t?`/${t}/`:"/";if(!e.startsWith(n))return;const o=t?e.substring(n.length):e.substring(e.lastIndexOf("/")+1);return/^(0|[1-9]\d*)$/.test(o)?parseInt(o,10):void 0}getObjectReference(e,t){var n,o;const s=null===(o=null===(n=e._internalMetadata)||void 0===n?void 0:n.gltf)||void 0===o?void 0:o.pointers;if(!Array.isArray(s))return;const r=s.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 bc="KHR_interactivity",xc=new WeakMap;function Tc(e){const t=xc.get(e);return null==t?void 0:t[t.length-1]}function Ac(e){var t;return null!==(t=xc.get(e))&&void 0!==t?t:[]}class Mc{constructor(e){this._loader=e,this.name=bc,this.order=200,this.enabled=this._loader.isExtensionUsed(bc),e._skipStartAnimationStep=!0}_initializePathConverter(e){var n;this._gltfPathConverter=dr(this._loader.gltf,t=>wc(e,this._loader.parent.targetFps,t));const o=[{prefix:uc,converter:new cc(e,{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}}}})}],s=new hc;o.push({prefix:sc,converter:s}),o.push({prefix:rc,converter:s});const r=new Set((null!==(n=this._loader.gltf.extensionsUsed)&&void 0!==n?n:[]).filter(e=>{var t;return js.has(e)&&!1!==(null===(t=this._loader.parent.extensionOptions[e])||void 0===t?void 0:t.enabled)})),i=new vc(this._loader.gltf,e=>r.has(e));o.push({prefix:"/extensions/KHR_interactivity/asset/",converter:i}),o.push({prefix:fc,converter:i});const a=new lc(o,this._gltfPathConverter);return this._pathConverter=a,a}dispose(){this._loader=null,delete this._gltfPathConverter,delete this._pathConverter}onReady(){return b(this,void 0,void 0,function*(){var e,n,o,s,r,i,a,l;if(!this._loader.babylonScene)return;const u=this._loader.babylonScene,c=this._initializePathConverter(u),d=null===(e=this._loader.gltf.extensions)||void 0===e?void 0:e.KHR_interactivity;if(!d)return;const h=new Set((null!==(n=this._loader.gltf.extensionsUsed)&&void 0!==n?n:[]).filter(e=>{var t;return!1!==(null===(t=this._loader.parent.extensionOptions[e])||void 0===t?void 0:t.enabled)})),f=oc(d,h,null!==(s=null===(o=this._loader.gltf.nodes)||void 0===o?void 0:o.length)&&void 0!==s?s:0),p=this._loader.parent.extensionOptions[bc],m=null===(r=null==p?void 0:p.autoStart)||void 0===r||r,_=null!==(i=null==p?void 0:p.parseOnly)&&void 0!==i&&i,g=null===(a=null==p?void 0:p.strictValidation)||void 0===a||a,v=null!==(l=xc.get(u))&&void 0!==l?l:[],y={assetIndex:v.length,document:f,graphs:[],pathConverter:c,glTF:this._loader.gltf,hostResolver:new yc};v.push(y),xc.set(u,v),yield Promise.all(f.graphs.map(e=>b(this,void 0,void 0,function*(){var n,o;const s={graph:e,diagnostics:e.diagnostics.slice()};if(y.graphs[e.index]=s,e.valid||!g)try{const n=new ac(g?e.effectiveSource:e.source,this._loader.gltf,this._loader.parent.targetFps,e.index,h,g?e.declarations:void 0).serializeToFlowGraph();if(s.serializedFlowGraph=n,_)return;const o=new t.FlowGraphCoordinator({scene:u,hostResolver:y.hostResolver});o.dispatchEventsSynchronously=!1,s.coordinator=o,s.flowGraph=yield t.ParseFlowGraphAsync(n,{coordinator:o,pathConverter:c}),m&&e.index===f.defaultGraphIndex&&o.start()}catch(r){const i=null!==(n=null==r?void 0:r.message)&&void 0!==n?n:String(r);s.diagnostics.push({path:e.path,message:i,severity:"error"}),t.Logger.Error(`KHR_interactivity: rejecting behavior graph #${e.index}: ${i}`),null===(o=s.coordinator)||void 0===o||o.dispose(),delete s.coordinator,delete s.flowGraph,delete s.serializedFlowGraph}else t.Logger.Error(`KHR_interactivity: rejecting behavior graph #${e.index}: ${e.diagnostics.map(e=>e.message).join("; ")}`)})))})}}function wc(e,n,o){pr("/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},o),pr("/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},o);const s=n=>{const o=e.activeCamera;return o&&o.mode!==t.Constants.ORTHOGRAPHIC_CAMERA?n(o):NaN},r=n=>{const o=e.activeCamera;return o&&o.mode===t.Constants.ORTHOGRAPHIC_CAMERA?n(o):NaN};pr("/extensions/KHR_interactivity/?/activeCamera/perspective/aspectRatio",{get:()=>s(e=>e.getEngine().getAspectRatio(e)),type:"number",getTarget:()=>e.activeCamera},o),pr("/extensions/KHR_interactivity/?/activeCamera/perspective/yfov",{get:()=>s(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},o),pr("/extensions/KHR_interactivity/?/activeCamera/perspective/znear",{get:()=>s(e=>e.minZ),type:"number",getTarget:()=>e.activeCamera},o),pr("/extensions/KHR_interactivity/?/activeCamera/perspective/zfar",{get:()=>s(e=>0===e.maxZ?1/0:e.maxZ),type:"number",getTarget:()=>e.activeCamera},o),pr("/extensions/KHR_interactivity/?/activeCamera/orthographic/xmag",{get:()=>r(e=>{var t,n;const o=e.getEngine().getRenderWidth()/2;return((null!==(t=e.orthoRight)&&void 0!==t?t:o)-(null!==(n=e.orthoLeft)&&void 0!==n?n:-o))/2}),type:"number",getTarget:()=>e.activeCamera},o),pr("/extensions/KHR_interactivity/?/activeCamera/orthographic/ymag",{get:()=>r(e=>{var t,n;const o=e.getEngine().getRenderHeight()/2;return((null!==(t=e.orthoTop)&&void 0!==t?t:o)-(null!==(n=e.orthoBottom)&&void 0!==n?n:-o))/2}),type:"number",getTarget:()=>e.activeCamera},o),pr("/extensions/KHR_interactivity/?/activeCamera/orthographic/znear",{get:()=>r(e=>e.minZ),type:"number",getTarget:()=>e.activeCamera},o),pr("/extensions/KHR_interactivity/?/activeCamera/orthographic/zfar",{get:()=>r(e=>e.maxZ),type:"number",getTarget:()=>e.activeCamera},o);const i=e=>{var t,o,s,r;return null!==(r=null===(s=null===(o=null===(t=e._babylonAnimationGroup)||void 0===t?void 0:t.targetedAnimations)||void 0===o?void 0:o[0])||void 0===s?void 0:s.animation.framePerSecond)&&void 0!==r?r:n};pr("/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},o),pr("/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)/i(e)},type:"number",getTarget:e=>e._babylonAnimationGroup},o),pr("/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)/i(e)},type:"number",getTarget:e=>e._babylonAnimationGroup},o),pr("/animations/{}/extensions/KHR_interactivity/playhead",{get:e=>{var t,n;return(null!==(n=null===(t=e._babylonAnimationGroup)||void 0===t?void 0:t.getRetainedCurrentFrame())&&void 0!==n?n:0)/i(e)},type:"number",getTarget:e=>e._babylonAnimationGroup},o),pr("/animations/{}/extensions/KHR_interactivity/virtualPlayhead",{get:e=>{var t,n;return(null!==(n=null===(t=e._babylonAnimationGroup)||void 0===t?void 0:t.getVirtualCurrentFrame())&&void 0!==n?n:0)/i(e)},type:"number",getTarget:e=>e._babylonAnimationGroup},o)}let Sc=!1;function Cc(){Sc||(Sc=!0,t.addToBlockFactory(bc,"FlowGraphGLTFDataProvider",()=>b(this,void 0,void 0,function*(){return(yield Promise.resolve().then(function(){return gd})).FlowGraphGLTFDataProvider})),t.addToBlockFactory(bc,"FlowGraphUnsupportedInteractivityBlock",()=>b(this,void 0,void 0,function*(){return(yield Promise.resolve().then(function(){return wd})).FlowGraphUnsupportedInteractivityBlock})),t.addToBlockFactory(bc,"FlowGraphObjectReferenceBlock",()=>b(this,void 0,void 0,function*(){return(yield Promise.resolve().then(function(){return bd})).FlowGraphObjectReferenceBlock})),t.addToBlockFactory(bc,"FlowGraphEventReferenceBlock",()=>b(this,void 0,void 0,function*(){return(yield Promise.resolve().then(function(){return Td})).FlowGraphEventReferenceBlock})))}let Rc=!1;function Ic(){Rc||(Rc=!0,Cc(),Ys(bc),Xs(bc,!0,e=>new Mc(e)))}var Oc={__proto__:null,GetKHRInteractivityImportResult:Tc,GetKHRInteractivityImportResults:Ac,KHR_interactivity:Mc,RegisterKHR_interactivity:Ic,_AddInteractivityObjectModel:wc,_RegisterKHRInteractivityRuntime:Cc};Ic();const Fc="KHR_node_visibility";class Ec{constructor(e){this.name=Fc,this._loader=e,this.enabled=e.isExtensionUsed(Fc)}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}}let Lc=!1;function Nc(){Lc||(Lc=!0,pr("/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,o;null===(n=t._primitiveBabylonMeshes)||void 0===n||n.forEach(e=>{e.inheritVisibility=!0}),t._babylonTransformNode&&(t._babylonTransformNode.isVisible=e),null===(o=t._primitiveBabylonMeshes)||void 0===o||o.forEach(t=>{t.isVisible=e})},getTarget:e=>e._babylonTransformNode,getPropertyName:[()=>"isVisible"],type:"boolean"}))}let kc=!1;function Bc(){kc||(kc=!0,Nc(),Ys(Fc),Xs(Fc,!0,e=>new Ec(e)))}var Pc={__proto__:null,KHR_node_visibility:Ec,RegisterKHR_node_visibility:Bc,_RegisterKHRNodeVisibilityRuntime:Nc};Bc();const Dc=new WeakMap,Vc=new WeakMap,Gc=new WeakMap;function $c(e){return"selectable"===e?Gc:Vc}function Uc(e,t){var n;return null===(n=$c(t).get(e))||void 0===n||n}function Hc(e,t,n){"selectable"===t?e.isPickable=n:e._isPointerMovePickable=n}function Kc(e,t){var n;const o=function(e,t){let n=e;for(;n;){if(!Uc(n,t))return!1;n=n.parent}return!0}(e,t),s=null!==(n=e._primitiveBabylonMeshes)&&void 0!==n?n:[];for(const e of s)Hc(e,t,o);const r=e._babylonTransformNode;r&&"isPickable"in r&&Hc(r,t,o)}function Wc(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parent}return!1}function qc(e,t,n){var o;const s=$c(t);for(const t of e)Dc.set(t,e),s.set(t,null===(o=n(t))||void 0===o||o);for(const n of e)Kc(n,t)}function zc(e,t){return Uc(e,t)}function jc(e,t,n){var o;$c(t).set(e,n);const s=null!==(o=Dc.get(e))&&void 0!==o?o:[e];for(const n of s)Wc(n,e)&&Kc(n,t)}const Xc="KHR_node_selectability";class Yc{constructor(e){this.name=Xc,this.order=100,this._loader=e,this.enabled=e.isExtensionUsed(Xc)}onReady(){return b(this,void 0,void 0,function*(){var e;qc(null!==(e=this._loader.gltf.nodes)&&void 0!==e?e:[],"selectable",e=>{var t,n;return null===(n=null===(t=e.extensions)||void 0===t?void 0:t.KHR_node_selectability)||void 0===n?void 0:n.selectable})})}dispose(){this._loader=null}}let Qc=!1;function Zc(){Qc||(Qc=!0,Cu("event/onSelect",Xc,{blocks:["FlowGraphMeshPickEventBlock","FlowGraphGetVariableBlock","FlowGraphIndexOfBlock","KHR_interactivity/FlowGraphGLTFDataProvider","KHR_interactivity/FlowGraphEventReferenceBlock"],declarationSchema:{inputValueSockets:{},outputValueSockets:{selectedNode:"ref",selectionRayOrigin:"float3",selectionPoint:"float3",controllerIndex:"int",event:"ref"}},configuration:{nodeIndex:{name:"variable",configurationType:"int",toBlock:"FlowGraphGetVariableBlock",indexSource:"assetNodes",invalidUsesDefault:!0,dataTransformer:e=>"pickedMesh_"+e}},outputs:{values:{selectedNodeIndex:{name:"index",toBlock:"FlowGraphIndexOfBlock"},selectedNode:{name:"nodeReference",toBlock:"KHR_interactivity/FlowGraphEventReferenceBlock"},controllerIndex:{name:"controllerIndex",toBlock:"KHR_interactivity/FlowGraphEventReferenceBlock"},selectionPoint:{name:"selectionPoint",toBlock:"KHR_interactivity/FlowGraphEventReferenceBlock"},selectionRayOrigin:{name:"selectionRayOrigin",toBlock:"KHR_interactivity/FlowGraphEventReferenceBlock"},event:{name:"value",toBlock:"KHR_interactivity/FlowGraphEventReferenceBlock"}},flows:{out:{name:"out",toBlock:"KHR_interactivity/FlowGraphEventReferenceBlock"}}},interBlockConnectors:[{input:"asset",output:"value",inputBlockIndex:0,outputBlockIndex:1,isVariable:!0},{input:"array",output:"nodes",inputBlockIndex:2,outputBlockIndex:3,isVariable:!0},{input:"object",output:"pickedMesh",inputBlockIndex:2,outputBlockIndex:0,isVariable:!0},{input:"node",output:"pickedMesh",inputBlockIndex:4,outputBlockIndex:0,isVariable:!0},{input:"controllerIndexInput",output:"pointerId",inputBlockIndex:4,outputBlockIndex:0,isVariable:!0},{input:"selectionPointInput",output:"pickedPoint",inputBlockIndex:4,outputBlockIndex:0,isVariable:!0},{input:"selectionRayOriginInput",output:"pickOrigin",inputBlockIndex:4,outputBlockIndex:0,isVariable:!0},{input:"in",output:"done",inputBlockIndex:4,outputBlockIndex:0}],extraProcessor(e,t,n,o,s,r,i){var a,l,u,c,d,h,f,p,m;const _=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],g="number"==typeof _&&Number.isInteger(_)&&_>=0&&_<(null!==(d=null===(c=null==i?void 0:i.nodes)||void 0===c?void 0:c.length)&&void 0!==d?d:0),v=g?"pickedMesh_"+_:"pickedMesh_unbound";s[1].config.variable=v,r._userVariables[v]=g?{className:"Mesh",id:null===(f=null===(h=null==i?void 0:i.nodes)||void 0===h?void 0:h[_]._babylonTransformNode)||void 0===f?void 0:f.id,uniqueId:null===(m=null===(p=null==i?void 0:i.nodes)||void 0===p?void 0:p[_]._babylonTransformNode)||void 0===m?void 0:m.uniqueId}:{type:"any",value:[{}]};const y=`${Xc}:event/onSelect:${_}`;return s[0].config.eventKey=y,s[0].config.useNaNDefaults=!0,s[0].config.pointerIdDefault=-1,s[4].config.eventKey=y,s}}),pr("/nodes/{}/extensions/KHR_node_selectability/selectable",{get:e=>zc(e,"selectable"),set:(e,t)=>{jc(t,"selectable",e)},getTarget:e=>e._babylonTransformNode,getPropertyName:[()=>"isPickable"],type:"boolean"}))}let Jc=!1;function ed(){Jc||(Jc=!0,Zc(),Ys(Xc),Xs(Xc,!0,e=>new Yc(e)))}var td={__proto__:null,KHR_node_selectability:Yc,RegisterKHR_node_selectability:ed,_RegisterKHRNodeSelectabilityRuntime:Zc};ed();const nd="KHR_node_hoverability",od="targetMeshPointerOver_",sd="targetMeshPointerOut_";class rd{constructor(e){this.name=nd,this.order=100,this._loader=e,this.enabled=e.isExtensionUsed(nd)}onReady(){return b(this,void 0,void 0,function*(){var e;qc(null!==(e=this._loader.gltf.nodes)&&void 0!==e?e:[],"hoverable",e=>{var t,n;return null===(n=null===(t=e.extensions)||void 0===t?void 0:t.KHR_node_hoverability)||void 0===n?void 0:n.hoverable})})}dispose(){this._loader=null}}let id=!1;function ad(){id||(id=!0,Cu("event/onHoverIn",nd,{blocks:["FlowGraphPointerOverEventBlock","FlowGraphGetVariableBlock","FlowGraphIndexOfBlock","KHR_interactivity/FlowGraphGLTFDataProvider","KHR_interactivity/FlowGraphEventReferenceBlock"],declarationSchema:{inputValueSockets:{},outputValueSockets:{hoveredNode:"ref",controllerIndex:"int",event:"ref"}},configuration:{nodeIndex:{name:"variable",configurationType:"int",toBlock:"FlowGraphGetVariableBlock",indexSource:"assetNodes",invalidUsesDefault:!0,dataTransformer:e=>od+e}},outputs:{values:{hoverNodeIndex:{name:"index",toBlock:"FlowGraphIndexOfBlock"},hoveredNode:{name:"nodeReference",toBlock:"KHR_interactivity/FlowGraphEventReferenceBlock"},controllerIndex:{name:"controllerIndex",toBlock:"KHR_interactivity/FlowGraphEventReferenceBlock"},event:{name:"value",toBlock:"KHR_interactivity/FlowGraphEventReferenceBlock"}},flows:{out:{name:"out",toBlock:"KHR_interactivity/FlowGraphEventReferenceBlock"}}},interBlockConnectors:[{input:"targetMesh",output:"value",inputBlockIndex:0,outputBlockIndex:1,isVariable:!0},{input:"array",output:"nodes",inputBlockIndex:2,outputBlockIndex:3,isVariable:!0},{input:"object",output:"meshUnderPointer",inputBlockIndex:2,outputBlockIndex:0,isVariable:!0},{input:"node",output:"meshUnderPointer",inputBlockIndex:4,outputBlockIndex:0,isVariable:!0},{input:"controllerIndexInput",output:"pointerId",inputBlockIndex:4,outputBlockIndex:0,isVariable:!0},{input:"in",output:"done",inputBlockIndex:4,outputBlockIndex:0}],extraProcessor(e,t,n,o,s,r,i){var a,l,u,c,d,h,f,p,m;const _=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],g="number"==typeof _&&Number.isInteger(_)&&_>=0&&_<(null!==(d=null===(c=null==i?void 0:i.nodes)||void 0===c?void 0:c.length)&&void 0!==d?d:0),v=g?od+_:od+"unbound";s[1].config.variable=v,r._userVariables[v]=g?{className:"Mesh",id:null===(f=null===(h=null==i?void 0:i.nodes)||void 0===h?void 0:h[_]._babylonTransformNode)||void 0===f?void 0:f.id,uniqueId:null===(m=null===(p=null==i?void 0:i.nodes)||void 0===p?void 0:p[_]._babylonTransformNode)||void 0===m?void 0:m.uniqueId}:{type:"any",value:[{}]};const y=`${nd}:event/onHoverIn:${_}`;return s[0].config.eventKey=y,s[4].config.eventKey=y,s}}),Cu("event/onHoverOut",nd,{blocks:["FlowGraphPointerOutEventBlock","FlowGraphGetVariableBlock","FlowGraphIndexOfBlock","KHR_interactivity/FlowGraphGLTFDataProvider","KHR_interactivity/FlowGraphEventReferenceBlock"],declarationSchema:{inputValueSockets:{},outputValueSockets:{hoveredNode:"ref",controllerIndex:"int",event:"ref"}},configuration:{nodeIndex:{name:"variable",configurationType:"int",toBlock:"FlowGraphGetVariableBlock",indexSource:"assetNodes",invalidUsesDefault:!0,dataTransformer:e=>sd+e}},outputs:{values:{hoverNodeIndex:{name:"index",toBlock:"FlowGraphIndexOfBlock"},hoveredNode:{name:"nodeReference",toBlock:"KHR_interactivity/FlowGraphEventReferenceBlock"},controllerIndex:{name:"controllerIndex",toBlock:"KHR_interactivity/FlowGraphEventReferenceBlock"},event:{name:"value",toBlock:"KHR_interactivity/FlowGraphEventReferenceBlock"}},flows:{out:{name:"out",toBlock:"KHR_interactivity/FlowGraphEventReferenceBlock"}}},interBlockConnectors:[{input:"targetMesh",output:"value",inputBlockIndex:0,outputBlockIndex:1,isVariable:!0},{input:"array",output:"nodes",inputBlockIndex:2,outputBlockIndex:3,isVariable:!0},{input:"object",output:"meshOutOfPointer",inputBlockIndex:2,outputBlockIndex:0,isVariable:!0},{input:"node",output:"meshOutOfPointer",inputBlockIndex:4,outputBlockIndex:0,isVariable:!0},{input:"controllerIndexInput",output:"pointerId",inputBlockIndex:4,outputBlockIndex:0,isVariable:!0},{input:"in",output:"done",inputBlockIndex:4,outputBlockIndex:0}],extraProcessor(e,t,n,o,s,r,i){var a,l,u,c,d,h,f,p,m;const _=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],g="number"==typeof _&&Number.isInteger(_)&&_>=0&&_<(null!==(d=null===(c=null==i?void 0:i.nodes)||void 0===c?void 0:c.length)&&void 0!==d?d:0),v=g?sd+_:sd+"unbound";s[1].config.variable=v,r._userVariables[v]=g?{className:"Mesh",id:null===(f=null===(h=null==i?void 0:i.nodes)||void 0===h?void 0:h[_]._babylonTransformNode)||void 0===f?void 0:f.id,uniqueId:null===(m=null===(p=null==i?void 0:i.nodes)||void 0===p?void 0:p[_]._babylonTransformNode)||void 0===m?void 0:m.uniqueId}:{type:"any",value:[{}]};const y=`${nd}:event/onHoverOut:${_}`;return s[0].config.eventKey=y,s[4].config.eventKey=y,s}}),pr("/nodes/{}/extensions/KHR_node_hoverability/hoverable",{get:e=>zc(e,"hoverable"),set:(e,t)=>{jc(t,"hoverable",e)},getTarget:e=>e._babylonTransformNode,getPropertyName:[()=>"pointerOverDisableMeshTesting"],type:"boolean"}))}let ld=!1;function ud(){ld||(ld=!0,ad(),Ys(nd),Xs(nd,!0,e=>new rd(e)))}var cd={__proto__:null,KHR_node_hoverability:rd,RegisterKHR_node_hoverability:ud,_RegisterKHRNodeHoverabilityRuntime:ad};ud();const dd="ExtrasAsMetadata";class hd{_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=dd,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 o=this._loader.createMaterial(e,t,n);return this._assignExtras(o,t),o}loadAnimationAsync(e,t){return this._loader.loadAnimationAsync(e,t).then(e=>(this._assignExtras(e,t),e))}}let fd=!1;function pd(){fd||(fd=!0,Ys(dd),Xs(dd,!1,e=>new hd(e)))}var md={__proto__:null,ExtrasAsMetadata:hd,RegisterExtrasAsMetadata:pd};pd();class _d extends t.FlowGraphBlock{constructor(e={}){var n,o;super(e);const s=e.glTF,r=(null===(n=null==s?void 0:s.animations)||void 0===n?void 0:n.map(e=>e._babylonAnimationGroup))||[];this.animationGroups=this.registerDataOutput("animationGroups",t.RichTypeAny,r);const i=(null===(o=null==s?void 0:s.nodes)||void 0===o?void 0:o.map(e=>e._babylonTransformNode))||[];this.nodes=this.registerDataOutput("nodes",t.RichTypeAny,i)}getClassName(){return"FlowGraphGLTFDataProvider"}}var gd={__proto__:null,FlowGraphGLTFDataProvider:_d};function vd(e,t){let n=t;for(;n;){const t=e.getObjectReference(n,"nodes");if(null==t?void 0:t.startsWith("/nodes/"))return t;n=n.parent}return""}class yd extends t.FlowGraphBlock{constructor(e){super(e),this.object=this.registerDataInput("object",t.RichTypeAny),this.value=this.registerDataOutput("value",t.RichTypeString,"")}_updateOutputs(e){this.value.setValue(vd(e,this.object.getValue(e)),e)}getClassName(){return"FlowGraphObjectReferenceBlock"}}var bd={__proto__:null,FlowGraphObjectReferenceBlock:yd,GetInteractivityObjectReference:vd};class xd extends t.FlowGraphExecutionBlock{constructor(e){super(e),this.config=e,this._assetInverse=t.Matrix.Identity(),this._selectionPointValue=t.Vector3.Zero(),this._selectionRayOriginValue=t.Vector3.Zero();const n=new t.Vector3(NaN,NaN,NaN);this.node=this.registerDataInput("node",t.RichTypeAny),this.controllerIndexInput=this.registerDataInput("controllerIndexInput",t.RichTypeNumber,-1),this.selectionPointInput=this.registerDataInput("selectionPointInput",t.RichTypeVector3,n),this.selectionRayOriginInput=this.registerDataInput("selectionRayOriginInput",t.RichTypeVector3,n),this.nodeReference=this.registerDataOutput("nodeReference",t.RichTypeString,""),this.controllerIndex=this.registerDataOutput("controllerIndex",t.RichTypeNumber,-1),this.selectionPoint=this.registerDataOutput("selectionPoint",t.RichTypeVector3,n),this.selectionRayOrigin=this.registerDataOutput("selectionRayOrigin",t.RichTypeVector3,n),this.value=this.registerDataOutput("value",t.RichTypeString,""),this.out=this._registerSignalOutput("out")}_execute(e){var n;this.nodeReference.setValue(vd(e,this.node.getValue(e)),e);const o=this.controllerIndexInput.getValue(e);if(o<0)this.controllerIndex.setValue(-1,e);else{const t=e._getGlobalContextVariable("khrInteractivityControllerIndices",new Map);let n=t.get(o);void 0===n&&(n=t.size,t.set(o,n),e._setGlobalContextVariable("khrInteractivityControllerIndices",t)),this.controllerIndex.setValue(n,e)}const s=this.node.getValue(e);let r=null==s?void 0:s.parent;for(;null==r?void 0:r.parent;)r=r.parent;(null==r?void 0:r.getWorldMatrix)?(r.getWorldMatrix().invertToRef(this._assetInverse),t.Vector3.TransformCoordinatesToRef(this.selectionPointInput.getValue(e),this._assetInverse,this._selectionPointValue),t.Vector3.TransformCoordinatesToRef(this.selectionRayOriginInput.getValue(e),this._assetInverse,this._selectionRayOriginValue),this.selectionPoint.setValue(this._selectionPointValue,e),this.selectionRayOrigin.setValue(this._selectionRayOriginValue,e)):(this.selectionPoint.setValue(this.selectionPointInput.getValue(e),e),this.selectionRayOrigin.setValue(this.selectionRayOriginInput.getValue(e),e)),this.value.setValue(e.getEventReference(null!==(n=this.config.eventKey)&&void 0!==n?n:"gltf:manual"),e),this.out._activateSignal(e)}getClassName(){return"FlowGraphEventReferenceBlock"}}var Td={__proto__:null,FlowGraphEventReferenceBlock:xd};function Ad(e){switch(e){case"bool":return!1;case"int":return new t.FlowGraphInteger(0);case"float":return NaN;case"float2":return new t.Vector2(NaN,NaN);case"float3":return new t.Vector3(NaN,NaN,NaN);case"float4":return new t.Vector4(NaN,NaN,NaN,NaN);case"float2x2":return new t.FlowGraphMatrix2D([NaN,NaN,NaN,NaN]);case"float3x3":return new t.FlowGraphMatrix3D([NaN,NaN,NaN,NaN,NaN,NaN,NaN,NaN,NaN]);case"float4x4":return t.Matrix.FromArray([NaN,NaN,NaN,NaN,NaN,NaN,NaN,NaN,NaN,NaN,NaN,NaN,NaN,NaN,NaN,NaN]);case"ref":return"";default:return}}class Md extends t.FlowGraphExecutionBlock{constructor(e){var n,o,s,r;super(e),this.config=e,this._unregisterSignalInput("in"),this._unregisterSignalOutput("error");for(const o of null!==(n=e.inputValueSockets)&&void 0!==n?n:[])this.registerDataInput(o.name,t.getRichTypeByFlowGraphType(o.type));for(const n of null!==(o=e.outputValueSockets)&&void 0!==o?o:[])this.registerDataOutput(n.name,t.getRichTypeByFlowGraphType(n.type),Ad(n.signature));for(const t of null!==(s=e.inputFlowSockets)&&void 0!==s?s:[])this._registerSignalInput(t);for(const t of null!==(r=e.outputFlowSockets)&&void 0!==r?r:[])this._registerSignalOutput(t)}_execute(e,t){}getClassName(){return"FlowGraphUnsupportedInteractivityBlock"}}var wd={__proto__:null,FlowGraphUnsupportedInteractivityBlock:Md},Sd={__proto__:null,AddObjectAccessorToKey:pr,CloneKHRInteractivityGraph:Vu,CreateEffectiveKHRInteractivityGraph:Qu,CreateKHRInteractivityDocument:oc,CreateKHRInteractivityGraphModel:nc,EXT_lights_area:Fi,EXT_lights_ies:li,EXT_lights_image_based:Pr,EXT_mesh_gpu_instancing:Ur,EXT_meshopt_compression:zr,EXT_texture_avif:oi,EXT_texture_webp:Zr,ExtrasAsMetadata:hd,FlowGraphEventReferenceBlock:xd,FlowGraphGLTFDataProvider:_d,FlowGraphObjectReferenceBlock:yd,FlowGraphUnsupportedInteractivityBlock:Md,GetInteractivityNodeState:zc,GetInteractivityObjectReference:vd,GetKHRInteractivityImportResult:Tc,GetKHRInteractivityImportResults:Ac,GetMappingForKey:hr,GetPathToObjectConverter:dr,InitializeInteractivityNodeState:qc,InteractivityGraphToFlowGraphParser:ac,KHR_INTERACTIVITY_SPECIFICATION_COMMIT:Bu,KHR_animation_pointer:Gl,KHR_draco_mesh_compression:fi,KHR_gaussian_splatting:xi,KHR_interactivity:Mc,KHR_lights:Si,KHR_materials_anisotropy:aa,KHR_materials_clearcoat:qi,KHR_materials_coat:Qi,KHR_materials_diffuse_roughness:ml,KHR_materials_diffuse_transmission:Xa,KHR_materials_dispersion:cl,KHR_materials_emissive_strength:ha,KHR_materials_fuzz:Ta,KHR_materials_ior:Ea,KHR_materials_iridescence:na,KHR_materials_pbrSpecularGlossiness:Bi,KHR_materials_sheen:ga,KHR_materials_specular:Ca,KHR_materials_transmission:Ka,KHR_materials_unlit:$i,KHR_materials_variants:Pa,KHR_materials_volume:el,KHR_materials_volume_scatter:rl,KHR_mesh_quantization:bl,KHR_node_hoverability:rd,KHR_node_selectability:Yc,KHR_node_visibility:Ec,KHR_texture_basisu:wl,KHR_texture_transform:Ol,KHR_xmp_json_ld:kl,MSFT_audio_emitter:ru,MSFT_lod:cu,MSFT_minecraftMesh:mu,MSFT_sRGBFactors:bu,ParseDebugLogTemplate:Lu,RegisterEXT_lights_area:Li,RegisterEXT_lights_ies:ci,RegisterEXT_lights_image_based:Vr,RegisterEXT_mesh_gpu_instancing:Kr,RegisterEXT_meshopt_compression:Xr,RegisterEXT_texture_avif:ri,RegisterEXT_texture_webp:ei,RegisterExtrasAsMetadata:pd,RegisterKHR_animation_pointer:Ul,RegisterKHR_draco_mesh_compression:mi,RegisterKHR_gaussian_splatting:Ai,RegisterKHR_interactivity:Ic,RegisterKHR_lights:Ri,RegisterKHR_materials_anisotropy:ua,RegisterKHR_materials_clearcoat:ji,RegisterKHR_materials_coat:Ji,RegisterKHR_materials_diffuse_roughness:gl,RegisterKHR_materials_diffuse_transmission:Qa,RegisterKHR_materials_dispersion:hl,RegisterKHR_materials_emissive_strength:pa,RegisterKHR_materials_fuzz:Ma,RegisterKHR_materials_ior:Na,RegisterKHR_materials_iridescence:sa,RegisterKHR_materials_pbrSpecularGlossiness:Di,RegisterKHR_materials_sheen:ya,RegisterKHR_materials_specular:Ia,RegisterKHR_materials_transmission:qa,RegisterKHR_materials_unlit:Hi,RegisterKHR_materials_variants:Va,RegisterKHR_materials_volume:nl,RegisterKHR_materials_volume_scatter:al,RegisterKHR_mesh_quantization:Tl,RegisterKHR_node_hoverability:ud,RegisterKHR_node_selectability:ed,RegisterKHR_node_visibility:Bc,RegisterKHR_texture_basisu:Cl,RegisterKHR_texture_transform:El,RegisterKHR_xmp_json_ld:Pl,RegisterMSFT_audio_emitter:au,RegisterMSFT_lod:hu,RegisterMSFT_minecraftMesh:gu,RegisterMSFT_sRGBFactors:Tu,SetInteractivityNodeState:jc,SetInterpolationForKey:fr,TransmissionHelper:$a,_AddInteractivityObjectModel:wc,_RegisterKHRInteractivityRuntime:Cc,_RegisterKHRNodeHoverabilityRuntime:ad,_RegisterKHRNodeSelectabilityRuntime:Zc,_RegisterKHRNodeVisibilityRuntime:Nc,addNewInteractivityFlowGraphMapping:Cu,ensureTransmissionHelper:Ua,getAllSupportedNativeNodeTypes:ku,getMappingForDeclaration:wu,getMappingForFullOperationName:Mu,getNoOpMappingForDeclaration:Su,gltfTypeToBabylonType:Pu},Cd={__proto__:null,AddObjectAccessorToKey:pr,AnimationPropertyInfo:Sr,ArrayItem:gr,CloneKHRInteractivityGraph:Vu,CreateEffectiveKHRInteractivityGraph:Qu,CreateKHRInteractivityDocument:oc,CreateKHRInteractivityGraphModel:nc,EXT_lights_area:Fi,EXT_lights_ies:li,EXT_lights_image_based:Pr,EXT_mesh_gpu_instancing:Ur,EXT_meshopt_compression:zr,EXT_texture_avif:oi,EXT_texture_webp:Zr,ExtrasAsMetadata:hd,FlowGraphEventReferenceBlock:xd,FlowGraphGLTFDataProvider:_d,FlowGraphObjectReferenceBlock:yd,FlowGraphUnsupportedInteractivityBlock:Md,GLTFFileLoader:ts,GLTFLoader:yr,GetInteractivityNodeState:zc,GetInteractivityObjectReference:vd,GetKHRInteractivityImportResult:Tc,GetKHRInteractivityImportResults:Ac,GetMappingForKey:hr,GetPathToObjectConverter:dr,InitializeInteractivityNodeState:qc,InteractivityGraphToFlowGraphParser:ac,KHR_INTERACTIVITY_SPECIFICATION_COMMIT:Bu,KHR_animation_pointer:Gl,KHR_draco_mesh_compression:fi,KHR_gaussian_splatting:xi,KHR_interactivity:Mc,KHR_lights:Si,KHR_materials_anisotropy:aa,KHR_materials_clearcoat:qi,KHR_materials_coat:Qi,KHR_materials_diffuse_roughness:ml,KHR_materials_diffuse_transmission:Xa,KHR_materials_dispersion:cl,KHR_materials_emissive_strength:ha,KHR_materials_fuzz:Ta,KHR_materials_ior:Ea,KHR_materials_iridescence:na,KHR_materials_pbrSpecularGlossiness:Bi,KHR_materials_sheen:ga,KHR_materials_specular:Ca,KHR_materials_transmission:Ka,KHR_materials_unlit:$i,KHR_materials_variants:Pa,KHR_materials_volume:el,KHR_materials_volume_scatter:rl,KHR_mesh_quantization:bl,KHR_node_hoverability:rd,KHR_node_selectability:Yc,KHR_node_visibility:Ec,KHR_texture_basisu:wl,KHR_texture_transform:Ol,KHR_xmp_json_ld:kl,LoadBoundingInfoFromPositionAccessor:vr,MSFT_audio_emitter:ru,MSFT_lod:cu,MSFT_minecraftMesh:mu,MSFT_sRGBFactors:bu,OpenPBRMaterialLoadingAdapter:Er,PBRMaterialLoadingAdapter:Nr,ParseDebugLogTemplate:Lu,RegisterEXT_lights_area:Li,RegisterEXT_lights_ies:ci,RegisterEXT_lights_image_based:Vr,RegisterEXT_mesh_gpu_instancing:Kr,RegisterEXT_meshopt_compression:Xr,RegisterEXT_texture_avif:ri,RegisterEXT_texture_webp:ei,RegisterExtrasAsMetadata:pd,RegisterGLTF2Loader:xr,RegisterGLTFLoaderAnimation:Or,RegisterKHR_animation_pointer:Ul,RegisterKHR_draco_mesh_compression:mi,RegisterKHR_gaussian_splatting:Ai,RegisterKHR_interactivity:Ic,RegisterKHR_lights:Ri,RegisterKHR_materials_anisotropy:ua,RegisterKHR_materials_clearcoat:ji,RegisterKHR_materials_coat:Ji,RegisterKHR_materials_diffuse_roughness:gl,RegisterKHR_materials_diffuse_transmission:Qa,RegisterKHR_materials_dispersion:hl,RegisterKHR_materials_emissive_strength:pa,RegisterKHR_materials_fuzz:Ma,RegisterKHR_materials_ior:Na,RegisterKHR_materials_iridescence:sa,RegisterKHR_materials_pbrSpecularGlossiness:Di,RegisterKHR_materials_sheen:ya,RegisterKHR_materials_specular:Ia,RegisterKHR_materials_transmission:qa,RegisterKHR_materials_unlit:Hi,RegisterKHR_materials_variants:Va,RegisterKHR_materials_volume:nl,RegisterKHR_materials_volume_scatter:al,RegisterKHR_mesh_quantization:Tl,RegisterKHR_node_hoverability:ud,RegisterKHR_node_selectability:ed,RegisterKHR_node_visibility:Bc,RegisterKHR_texture_basisu:Cl,RegisterKHR_texture_transform:El,RegisterKHR_xmp_json_ld:Pl,RegisterMSFT_audio_emitter:au,RegisterMSFT_lod:hu,RegisterMSFT_minecraftMesh:gu,RegisterMSFT_sRGBFactors:Tu,SetInteractivityNodeState:jc,SetInterpolationForKey:fr,TransformNodeAnimationPropertyInfo:Cr,TransmissionHelper:$a,WeightAnimationPropertyInfo:Rr,_AddInteractivityObjectModel:wc,_RegisterKHRInteractivityRuntime:Cc,_RegisterKHRNodeHoverabilityRuntime:ad,_RegisterKHRNodeSelectabilityRuntime:Zc,_RegisterKHRNodeVisibilityRuntime:Nc,addNewInteractivityFlowGraphMapping:Cu,ensureTransmissionHelper:Ua,getAllSupportedNativeNodeTypes:ku,getMappingForDeclaration:wu,getMappingForFullOperationName:Mu,getNoOpMappingForDeclaration:Su,getQuaternion:Mr,getVector3:Ar,getWeights:wr,gltfTypeToBabylonType:Pu,registerGLTFExtension:Xs,registeredGLTFExtensions:js,unregisterGLTFExtension:Ys};class Rd{constructor(){this.materials=[]}parseMTL(e,n,o,s){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=!!s,l=new t.StandardMaterial(h,e),l._parentContainer=s,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=Rd._GetTexture(o,h,e);else if("map_kd"===d&&l)l.diffuseTexture=Rd._GetTexture(o,h,e);else if("map_ks"===d&&l)l.specularTexture=Rd._GetTexture(o,h,e);else if("map_ns"===d);else if("map_bump"===d&&l){const t=h.split(i),n=t.indexOf("-bm");let s=null;n>=0&&(s=t[n+1],t.splice(n,2)),l.bumpTexture=Rd._GetTexture(o,t.join(" "),e),l.bumpTexture&&null!==s&&(l.bumpTexture.level=parseFloat(s))}else"map_d"===d&&l&&(l.opacityTexture=Rd._GetTexture(o,h,e))}l&&this.materials.push(l)}static _GetTexture(e,n,o){if(!n)return null;let s=e;if("file:"===e){let e=n.lastIndexOf("\\");-1===e&&(e=n.lastIndexOf("/")),s+=e>-1?n.substring(e+1):n}else s+=n;return new t.Texture(s,o,!1,Rd.INVERT_TEXTURE_Y)}}Rd.INVERT_TEXTURE_Y=!0;class Id{constructor(e,n,o){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=o}_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 o;null!==(t=e.indiceUvsFromObj)&&void 0!==t||(e.indiceUvsFromObj=-1),null!==(n=e.indiceNormalFromObj)&&void 0!==n||(e.indiceNormalFromObj=-1),o=this._loadingOptions.optimizeWithUV?this._isInArrayUV(this._tuplePosNorm,[e.indicePositionFromObj,e.indiceNormalFromObj,e.indiceUvsFromObj]):this._isInArray(this._tuplePosNorm,[e.indicePositionFromObj,e.indiceNormalFromObj]),-1===o?(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(o)}_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,o=parseInt(t[1])-1;this._setData({indicePositionFromObj:n,indiceUvsFromObj:o,positionVectorFromOBJ:this._positions[n],textureVectorFromOBJ:this._uvs[o],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,o=parseInt(t[1])-1,s=parseInt(t[2])-1;this._setData({indicePositionFromObj:n,indiceUvsFromObj:o,indiceNormalFromObj:s,positionVectorFromOBJ:this._positions[n],textureVectorFromOBJ:this._uvs[o],normalsVectorFromOBJ:this._normals[s]})}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,o=parseInt(t[1])-1;this._setData({indicePositionFromObj:n,indiceNormalFromObj:o,positionVectorFromOBJ:this._positions[n],normalsVectorFromOBJ:this._normals[o],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]),o=this._uvs.length+parseInt(t[1]),s=this._normals.length+parseInt(t[2]);this._setData({indicePositionFromObj:n,indiceUvsFromObj:o,indiceNormalFromObj:s,positionVectorFromOBJ:this._positions[n],textureVectorFromOBJ:this._uvs[o],normalsVectorFromOBJ:this._normals[s],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),o=e.getVerticesData(t.VertexBuffer.NormalKind),s={};if(!n||!o)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 o=s[t];o||(o=[],s[t]=o),o.push(e)}const r=new t.Vector3;for(const e in s){const t=s[e];if(t.length<2)continue;const n=t[0];for(let e=1;e<t.length;++e){const s=t[e];o[3*n+0]+=o[3*s+0],o[3*n+1]+=o[3*s+1],o[3*n+2]+=o[3*s+2]}r.copyFromFloats(o[3*n+0],o[3*n+1],o[3*n+2]),r.normalize();for(let e=0;e<t.length;++e){const n=t[e];o[3*n+0]=r.x,o[3*n+1]=r.y,o[3*n+2]=r.z}}e.setVerticesData(t.VertexBuffer.NormalKind,o)}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 o=e.match(/[a-z0-9]/g);if(!o||o.length%8!=0)return[];const s=[];for(let e=0;e<o.length/8;e++){const n=o[8*e+2]+o[8*e+3],r=o[8*e+4]+o[8*e+5],i=o[8*e+6]+o[8*e+7];s.push(new t.Color4(parseInt(n,16)/255,parseInt(r,16)/255,parseInt(i,16)/255,1))}return s}parse(e,n,o,s,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):o.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 f=[];h.push(f);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((Id._IsGroupElement(t)||Id._IsObjectElement(t))&&(f=[],h.push(f)),Id._IsLineElement(t)){const e=t.split(" ");for(let t=1;t<e.length-1;t++)f.push(`l ${e[t]} ${e[t+1]}`)}else f.push(t)}const p=h.flat();for(let e=0;e<p.length;e++){const n=p[e].trim().replace(/\s\s/g," ");let o;if(0!==n.length&&"#"!==n.charAt(0))if(Id.VertexPattern.test(n)){if(o=n.match(/[^ ]+/g),this._positions.push(new t.Vector3(parseFloat(o[1]),parseFloat(o[2]),parseFloat(o[3]))),this._loadingOptions.importVertexColors)if(o.length>=7){const e=parseFloat(o[4]),n=parseFloat(o[5]),s=parseFloat(o[6]);this._colors.push(new t.Color4(e>1?e/255:e,n>1?n/255:n,s>1?s/255:s,7===o.length||void 0===o[7]?1:parseFloat(o[7])))}else this._colors.push(this._grayColor)}else if(null!==(o=Id.NormalPattern.exec(n)))this._normals.push(new t.Vector3(parseFloat(o[1]),parseFloat(o[2]),parseFloat(o[3])));else if(null!==(o=Id.UVPattern.exec(n)))this._uvs.push(new t.Vector2(parseFloat(o[1])*this._loadingOptions.UVScaling.x,parseFloat(o[2])*this._loadingOptions.UVScaling.y));else if(null!==(o=Id.FacePattern3.exec(n)))this._setDataForCurrentFaceWithPattern3(o[1].trim().split(" "),1);else if(null!==(o=Id.FacePattern4.exec(n)))this._setDataForCurrentFaceWithPattern4(o[1].trim().split(" "),1);else if(null!==(o=Id.FacePattern5.exec(n)))this._setDataForCurrentFaceWithPattern5(o[1].trim().split(" "),1);else if(null!==(o=Id.FacePattern2.exec(n)))this._setDataForCurrentFaceWithPattern2(o[1].trim().split(" "),1);else if(null!==(o=Id.FacePattern1.exec(n)))this._setDataForCurrentFaceWithPattern1(o[1].trim().split(" "),1);else if(null!==(o=Id.LinePattern1.exec(n)))this._setDataForCurrentFaceWithPattern1(o[1].trim().split(" "),0),this._hasLineData=!0;else if(null!==(o=Id.LinePattern2.exec(n)))this._setDataForCurrentFaceWithPattern2(o[1].trim().split(" "),0),this._hasLineData=!0;else if(o=Id._GetZbrushMRGB(n,!this._loadingOptions.importVertexColors))for(const e of o)this._extColors.push(e);else if(null!==(o=Id.LinePattern3.exec(n)))this._setDataForCurrentFaceWithPattern3(o[1].trim().split(" "),0),this._hasLineData=!0;else if(Id.GroupDescriptor.test(n)||Id.ObjectDescriptor.test(n)){const e={name:n.substring(2).trim(),indices:null,positions:null,normals:null,uvs:null,colors:null,materialName:this._materialNameFromObj,isObject:Id.ObjectDescriptor.test(n)};this._addPreviousObjMesh(),this._meshesFromObj.push(e),this._hasMeshes=!0,this._isFirstMaterial=!0,this._increment=1}else if(Id.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 Id.MtlLibGroupDescriptor.test(n)?r(n.substring(7).trim()):Id.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(),o),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],o._blockEntityCollection=!!s;const r=new t.Mesh(this._meshesFromObj[n].name,o);if(r._parentContainer=s,o._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)}}}Id.ObjectDescriptor=/^o/,Id.GroupDescriptor=/^g/,Id.MtlLibGroupDescriptor=/^mtllib /,Id.UseMtlDescriptor=/^usemtl /,Id.SmoothDescriptor=/^s /,Id.VertexPattern=/^v(\s+[\d|.|+|\-|e|E]+){3,7}/,Id.NormalPattern=/^vn(\s+[\d|.|+|\-|e|E]+)( +[\d|.|+|\-|e|E]+)( +[\d|.|+|\-|e|E]+)/,Id.UVPattern=/^vt(\s+[\d|.|+|\-|e|E]+)( +[\d|.|+|\-|e|E]+)/,Id.FacePattern1=/^f\s+(([\d]{1,}[\s]?){3,})+/,Id.FacePattern2=/^f\s+((([\d]{1,}\/[\d]{1,}[\s]?){3,})+)/,Id.FacePattern3=/^f\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){3,})+)/,Id.FacePattern4=/^f\s+((([\d]{1,}\/\/[\d]{1,}[\s]?){3,})+)/,Id.FacePattern5=/^f\s+(((-[\d]{1,}\/-[\d]{1,}\/-[\d]{1,}[\s]?){3,})+)/,Id.LinePattern1=/^l\s+(([\d]{1,}[\s]?){2,})+/,Id.LinePattern2=/^l\s+((([\d]{1,}\/[\d]{1,}[\s]?){2,})+)/,Id.LinePattern3=/^l\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){2,})+)/;const Od={name:"obj",extensions:{".obj":{isBinary:!0}}};class Fd{static get INVERT_TEXTURE_Y(){return Rd.INVERT_TEXTURE_Y}static set INVERT_TEXTURE_Y(e){Rd.INVERT_TEXTURE_Y=e}constructor(e){this.name=Od.name,this.extensions=Od.extensions,this._assetContainer=null,this._loadingOptions=Object.assign(Object.assign({},Fd._DefaultLoadingOptions),null!=e?e:{})}static get _DefaultLoadingOptions(){return{encoding:Fd.ENCODING,computeNormals:Fd.COMPUTE_NORMALS,optimizeNormals:Fd.OPTIMIZE_NORMALS,importVertexColors:Fd.IMPORT_VERTEX_COLORS,invertY:Fd.INVERT_Y,invertTextureY:Fd.INVERT_TEXTURE_Y,UVScaling:Fd.UV_SCALING,materialLoadingFailsSilently:Fd.MATERIAL_LOADING_FAILS_SILENTLY,optimizeWithUV:Fd.OPTIMIZE_WITH_UV,skipMaterials:Fd.SKIP_MATERIALS,useLegacyBehavior:Fd.USE_LEGACY_BEHAVIOR}}_loadMTL(e,n,o,s){const r=n+e;t.Tools.LoadFile(r,o,void 0,void 0,!0,(e,t)=>{s(r,t)})}_decode(e){var t;if("string"==typeof e)return e;const n=new Uint8Array(e),o=null!==(t=this._loadingOptions.encoding)&&void 0!==t?t:"auto";if("auto"!==o)return new TextDecoder(o).decode(n);if(255===n[0]&&254===n[1])return new TextDecoder("utf-16le").decode(n);if(254===n[0]&&255===n[1])return new TextDecoder("utf-16be").decode(n);try{return new TextDecoder("utf-8",{fatal:!0}).decode(n)}catch(e){return new TextDecoder("gb18030").decode(n)}}createPlugin(e){return new Fd(e[Od.name])}canDirectLoad(){return!1}importMeshAsync(e,t,n,o){return this._parseSolidAsync(e,t,n,o).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,o){const s=new t.AssetContainer(e);return this._assetContainer=s,this.importMeshAsync(null,e,n,o).then(e=>(e.meshes.forEach(e=>s.meshes.push(e)),e.meshes.forEach(e=>{const t=e.material;t&&-1==s.materials.indexOf(t)&&(s.materials.push(t),t.getActiveTextures().forEach(e=>{-1==s.textures.indexOf(e)&&s.textures.push(e)}))}),this._assetContainer=null,s)).catch(e=>{throw this._assetContainer=null,e})}_parseSolidAsync(e,n,o,s){let r="";const i=new Rd,a=[],l=[];o=(o=this._decode(o)).replace(/#.*$/gm,"").trim(),new Id(a,l,this._loadingOptions).parse(e,o,n,this._assetContainer,e=>{r=e});const u=[];return""===r||this._loadingOptions.skipMaterials||u.push(new Promise((e,o)=>{this._loadMTL(r,s,u=>{try{i.parseMTL(n,this._decode(u),s,this._assetContainer);for(let e=0;e<i.materials.length;e++){let t=0;const n=[];let o;for(;(o=a.indexOf(i.materials[e].name,t))>-1;)n.push(o),t=o+1;if(-1===o&&0===n.length)i.materials[e].dispose();else for(let t=0;t<n.length;t++){const o=l[n[t]],s=i.materials[e];o.material=s,o.getTotalIndices()||(s.pointsCloud=!0)}}e()}catch(n){t.Tools.Warn(`Error processing MTL file: '${r}'`),this._loadingOptions.materialLoadingFailsSilently?e():o(n)}},(n,s)=>{t.Tools.Warn(`Error downloading MTL file: '${r}'`),this._loadingOptions.materialLoadingFailsSilently?e():o(s)})})),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(o=>{var s,r;if(e(o)){let i=null!==(s=o.material)&&void 0!==s?s:new t.StandardMaterial(o.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,o.material=i,o._internalMetadata&&(o._internalMetadata._isLine=void 0)}}),l})}}Fd.ENCODING="auto",Fd.OPTIMIZE_WITH_UV=!0,Fd.INVERT_Y=!1,Fd.IMPORT_VERTEX_COLORS=!1,Fd.COMPUTE_NORMALS=!1,Fd.OPTIMIZE_NORMALS=!1,Fd.UV_SCALING=new t.Vector2(1,1),Fd.SKIP_MATERIALS=!1,Fd.MATERIAL_LOADING_FAILS_SILENTLY=!0,Fd.USE_LEGACY_BEHAVIOR=!1;let Ed=!1;function Ld(){Ed||(Ed=!0,t.RegisterSceneLoaderPlugin(new Fd))}var Nd={__proto__:null,OBJFileLoader:Fd,RegisterOBJFileLoader:Ld};Ld();var kd={__proto__:null,MTLFileLoader:Rd,OBJFileLoader:Fd,RegisterOBJFileLoader:Ld,SolidParser:Id};const Bd={name:"stl",extensions:{".stl":{isBinary:!0}}};class Pd{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=Bd.name,this.extensions=Bd.extensions}importMesh(e,n,o,s,r){let i;if("string"!=typeof o){if(this._isBinary(o)){const e=new t.Mesh("stlmesh",n);return this._parseBinary(e,o),r&&r.push(e),!0}o=(new TextDecoder).decode(new Uint8Array(o))}for(;i=this.solidPattern.exec(o);){let o=i[1];const s=i[3];if(s&&o!=s)return t.Tools.Error("Error in STL, solid name != endsolid name"),!1;if(e&&o)if(e instanceof Array){if(!e.indexOf(o))continue}else if(o!==e)continue;o=o||"stlmesh";const a=new t.Mesh(o,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,o){const s=new t.AssetContainer(e);return e._blockEntityCollection=!0,this.importMesh(null,e,n,o,s.meshes),e._blockEntityCollection=!1,s}_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 o=new DataView(n),s=o.getUint32(80,!0);let r=0;const i=new Float32Array(3*s*3),a=new Float32Array(3*s*3),l=new Uint32Array(3*s);let u=0;for(let e=0;e<s;e++){const t=84+50*e,n=o.getFloat32(t,!0),s=o.getFloat32(t+4,!0),c=o.getFloat32(t+8,!0);for(let e=1;e<=3;e++){const l=t+12*e;i[r]=o.getFloat32(l,!0),a[r]=n,Pd.DO_NOT_ALTER_FILE_COORDINATES?(i[r+1]=o.getFloat32(l+4,!0),i[r+2]=o.getFloat32(l+8,!0),a[r+1]=s,a[r+2]=c):(i[r+2]=o.getFloat32(l+4,!0),i[r+1]=o.getFloat32(l+8,!0),a[r+2]=s,a[r+1]=c),r+=3}Pd.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 o=[],s=[],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);)Pd.DO_NOT_ALTER_FILE_COORDINATES?(o.push(Number(l[1]),Number(l[3]),Number(l[5])),s.push(n[0],n[2],n[1])):(o.push(Number(l[1]),Number(l[5]),Number(l[3])),s.push(n[0],n[1],n[2]));Pd.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,o),e.setVerticesData(t.VertexBuffer.NormalKind,s),e.setIndices(r),e.computeWorldMatrix(!0)}}Pd.DO_NOT_ALTER_FILE_COORDINATES=!1;let Dd=!1;function Vd(){Dd||(Dd=!0,t.RegisterSceneLoaderPlugin(new Pd))}var Gd={__proto__:null,RegisterSTLFileLoader:Vd,STLFileLoader:Pd};Vd();var $d={__proto__:null,RegisterSTLFileLoader:Vd,STLFileLoader:Pd};const Ud={name:"splat",extensions:{".splat":{isBinary:!0},".ply":{isBinary:!0},".spz":{isBinary:!0},".json":{isBinary:!1},".sog":{isBinary:!0}}},Hd=.28209479177387814;function Kd(e,t,n){return b(this,void 0,void 0,function*(){const o=new Promise((o,s)=>{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 s=t.getImageData(0,0,e.width,e.height);o({bits:new Uint8Array(s.data.buffer),width:s.width,height:s.height})}catch(e){s(`Error loading image ${r.src} with exception: ${e}`)}},r.onerror=e=>{s(`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 o})}function Wd(e,n,o){return b(this,void 0,void 0,function*(){let s,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");s=JSON.parse((new TextDecoder).decode(t))}else s=e;const i=[...s.means.files,...s.scales.files,...s.quats.files,...s.sh0.files];s.shN&&i.push(...s.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 Kd(t,e,o.getEngine())}return yield Kd(n,e,o.getEngine())})));return yield function(e,n,o){return b(this,void 0,void 0,function*(){const s=e.count?e.count:e.means.shape[0],r=new ArrayBuffer(32*s),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<s;n++){const o=4*n;for(let s=0;s<3;s++){const r=e.means.mins[s],a=e.means.maxs[s],l=h[o+s]<<8|d[o+s],u=t.Scalar.Lerp(r,a,l/65535);i[8*n+s]=c(u)}}const f=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<s;t++){const n=4*t;for(let o=0;o<3;o++){const s=e.scales.codebook[f[n+o]],r=Math.exp(s);a[8*t+3+o]=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<s;n++){const o=4*n;for(let s=0;s<3;s++){const r=f[o+s],i=t.Scalar.Lerp(e.scales.mins[s],e.scales.maxs[s],r/255),l=Math.exp(i);a[8*n+3+s]=l}}}const p=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<s;t++){const n=4*t;for(let o=0;o<3;o++){const s=.5+e.sh0.codebook[p[n+o]]*Hd;l[32*t+24+o]=Math.max(0,Math.min(255,Math.round(255*s)))}l[32*t+24+3]=p[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<s;n++){const o=4*n;for(let s=0;s<4;s++){const r=e.sh0.mins[s],i=e.sh0.maxs[s],a=p[o+s],u=t.Scalar.Lerp(r,i,a/255);let c;c=s<3?.5+u*Hd:1/(1+Math.exp(-u)),l[32*n+24+s]=Math.max(0,Math.min(255,Math.round(255*c)))}}}const m=e=>2*(e/255-.5)/Math.SQRT2,_=n[3].bits;for(let e=0;e<s;e++){const t=_[4*e+0],n=_[4*e+1],o=_[4*e+2],s=_[4*e+3],r=m(t),i=m(n),a=m(o),l=s-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),f=o.getEngine().getCaps().maxTextureSize,p=Math.ceil(s/f),m=t.AllocateShBuffers(h,p*f*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<s;t++){const n=u[4*t+0]+(u[4*t+1]<<8),o=n%64*i,s=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=m[a],d=i%16,h=16*t,f=127.5*e.shN.codebook[l[4*(o+n)+r+s*c*4]]+127.5;u[d+h]=Math.max(0,Math.min(255,f))}}}else for(let n=0;n<s;n++){const o=u[4*n+0]+(u[4*n+1]<<8),s=o%64*i,r=Math.floor(o/64),a=e.shN.mins,d=e.shN.maxs;for(let e=0;e<3;e++)for(let o=0;o<i/3;o++){const i=3*o+e,u=Math.floor(i/16),h=m[u],f=i%16,p=16*n,_=127.5*t.Scalar.Lerp(a,d,l[4*(s+o)+e+r*c*4]/255)+127.5;h[f+p]=Math.max(0,Math.min(255,_))}}return yield new Promise(e=>{e({mode:0,data:r,hasVertexColors:!1,sh:m,shDegree:a})})}return yield new Promise(e=>{e({mode:0,data:r,hasVertexColors:!1})})})}(s,a,o)})}function qd(e,n){return function(e,n,o,s){const r=new t.RawTexture(n,o,s,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 zd(e,n,o){return b(this,void 0,void 0,function*(){const s=o.getEngine();if("function"==typeof createImageBitmap)try{const r=n.toLowerCase().endsWith(".png")?"image/png":"image/webp";let i;if("string"==typeof e){const o=yield t.Tools.LoadFileAsync(e+n,!0);i=new Blob([o],{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,o,!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&&s.updateDynamicTexture(n,a,!1,!1),e}finally{a.close()}}catch(e){}const r=yield Kd(e,n,s);return qd(o,r)})}function jd(e,n,o,s){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*s);for(let a=0;a<s;a++){const s=4*a;for(let l=0;l<3;l++){const u=o[s+l]<<8|n[s+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 Xd(e,n,o){return b(this,arguments,void 0,function*(e,n,o,s=!0,r,i){var a,l,u,c,d,h,f;let p,m;if(e instanceof Map){m=e;const t=m.get("meta.json");if(!t)throw new Error("meta.json not found in files Map");p=JSON.parse((new TextDecoder).decode(t))}else p=e;const _=e=>b(this,void 0,void 0,function*(){if(m&&m.has(e))return yield Kd(m.get(e),e,o.getEngine());if(r){const t=new Uint8Array(yield r.loadFileAsync(n+e,i));return yield Kd(t,e,o.getEngine())}return yield Kd(n,e,o.getEngine())}),g=e=>b(this,void 0,void 0,function*(){if(m&&m.has(e))return yield zd(m.get(e),e,o);if(r){const t=new Uint8Array(yield r.loadFileAsync(n+e,i));return yield zd(t,e,o)}return yield zd(n,e,o)}),v=[...p.scales.files,...p.quats.files,...p.sh0.files,...null!==(l=null===(a=p.shN)||void 0===a?void 0:a.files)&&void 0!==l?l:[]];let y,x,T,A,M,w=null;if(s){const[e,t]=yield Promise.all([Promise.all(p.means.files.map(_)),Promise.all(v.map(g))]);w=[e[0],e[1]],M=t,y=qd(o,e[0]),x=qd(o,e[1]),T=e[0].width,A=e[0].height}else{const[e,t]=yield Promise.all([Promise.all(p.means.files.map(g)),Promise.all(v.map(g))]);M=t,y=e[0],x=e[1];const n=y.getSize();T=n.width,A=n.height}const S=null!==(u=p.count)&&void 0!==u?u:p.means.shape[0],C=T*A;if(C<S)throw new Error(`SOG texture contains ${C} texels, but metadata references ${S} splats.`);const R=M[0],I=M[1],O=M[2];let F,E,L,N=0,k=0;if(p.shN&&M.length>=5&&(F=M[3],E=M[4],N=p.shN.bands?Math.pow(p.shN.bands+1,2)-1:p.shN.shape[1]/3,k=null!==(c=p.shN.bands)&&void 0!==c?c:Math.round(Math.sqrt(N+1)-1)),2===p.version){const e=256,n=new Float32Array(3*e);p.scales.codebook&&n.set(p.scales.codebook.slice(0,e),0),p.sh0.codebook&&n.set(p.sh0.codebook.slice(0,e),e),(null===(d=p.shN)||void 0===d?void 0:d.codebook)&&n.set(p.shN.codebook.slice(0,e),2*e),L=new t.RawTexture(n,3*e,1,t.Constants.TEXTUREFORMAT_R,o,!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 B=p.means.mins,P=p.means.maxs,D={version:2===p.version?2:1,splatCount:S,shDegree:k,meansTextureL:y,meansTextureU:x,scalesTexture:R,quatsTexture:I,sh0Texture:O,shCentroidsTexture:F,shLabelsTexture:E,codebookTexture:L,meansMin:[B[0],B[1],B[2]],meansMax:[P[0],P[1],P[2]],scalesMin:Array.isArray(p.scales.mins)?[p.scales.mins[0],p.scales.mins[1],p.scales.mins[2]]:void 0,scalesMax:Array.isArray(p.scales.maxs)?[p.scales.maxs[0],p.scales.maxs[1],p.scales.maxs[2]]:void 0,sh0Min:Array.isArray(p.sh0.mins)?[p.sh0.mins[0],p.sh0.mins[1],p.sh0.mins[2],p.sh0.mins[3]]:void 0,sh0Max:Array.isArray(p.sh0.maxs)?[p.sh0.maxs[0],p.sh0.maxs[1],p.sh0.maxs[2],p.sh0.maxs[3]]:void 0,shnMin:"number"==typeof(null===(h=p.shN)||void 0===h?void 0:h.mins)?p.shN.mins:void 0,shnMax:"number"==typeof(null===(f=p.shN)||void 0===f?void 0:f.maxs)?p.shN.maxs:void 0,shCoeffCount:N,positions:w?jd(p,w[0].bits,w[1].bits,S):new Float32Array(0)};return{mode:0,data:new ArrayBuffer(0),hasVertexColors:!1,shDegree:k,sogTextures:D}})}const Yd="precision highp float;\nattribute vec3 position;\nvoid main() {\n gl_Position = vec4(position.xy, 0.0, 1.0);\n}\n",Qd="\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 Zd{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,o,s){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)),o&&o.textureCount>0){if(o.externalMrts)this._shMrts=o.externalMrts.slice(0,o.textureCount),this._ownsShMrts=!1;else{for(let e=0;e<o.textureCount;e++)this._shMrts.push(this._createShMrt(`gsWorkBufferSh${e}`,!0));this._ownsShMrts=!0}this._shMaterial=this._createShMaterial()}s&&(s.externalMrt?(this._rotMrt=s.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)),o=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,-o),this._shMrts.length&&this._shCopyMaterial){this._backupShMrts||(this._backupShMrts=this._shMrts.map((t,o)=>this._createShMrt(`gsShAtlasBackup${o}`,!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,-o)}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,-o)),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)),o=Math.floor(this._baseOffset/t),s=this._scene.getEngine();s.enableScissor(0,o,t,n);try{if(this._renderRelayoutPass(this._mrt,this._backupMrt.textures,this._backupMrt.textures[0],0,t,t,0,o),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,o);this._backupRotMrt&&this._rotMrt&&this._rotCopyMaterial&&this._renderRotCopyPass(this._rotMrt,this._backupRotMrt.textures,this._mrt.textures[0],0,t,t,0,o)}finally{s.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,o=this._textureSize,s=this._textureSize){const r=this._scene.getEngine()._caps.textureHalfFloatRender?t.Constants.TEXTURETYPE_HALF_FLOAT:t.Constants.TEXTURETYPE_FLOAT,i=new t.MultiRenderTarget(e,{width:o,height:s},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,o=this._textureSize,s=this._textureSize){const r=new t.MultiRenderTarget(e,{width:o,height:s},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,o=this._textureSize,s=this._textureSize){const r=this._scene.getEngine()._caps.textureHalfFloatRender?t.Constants.TEXTURETYPE_HALF_FLOAT:t.Constants.TEXTURETYPE_FLOAT,i=new t.MultiRenderTarget(e,{width:o,height:s},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 o=null!==this._rotMaterial&&null!==this._rotMrt;o&&this._applyRotPack(e),yield new Promise(s=>{const r=()=>{if(this._disposed)return void s();if(!this._material.isReady(this._quad)||n&&!this._shMaterial.isReady(this._quad)||o&&!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),o&&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}o&&(this._quad.material=this._rotMaterial,this._rotMrt.renderList=[this._quad],this._rotMrt.render(),this._quad.material=this._material)}finally{c.disableScissor()}s()};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,o=n,s=this._ownsMrt?n:Math.max(1,Math.floor(this._capacity/n));this._relayoutMapData||(this._relayoutMapData=new Float32Array(o*s));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,o,s,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=s,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,o,s=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",s),l.setInt("uSrcWidth",r),l.setInt("uUseMap",o),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?Qd:Yd,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,o,s=this._textureSize,r=this._textureSize,i=0,a=0){const l=this._shCopyMaterial;l.setTexture("uMapTex",n),l.setTexture("uSrcSh",t),l.setInt("uDstWidth",s),l.setInt("uSrcWidth",r),l.setInt("uUseMap",o),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?Qd:Yd,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,o,s=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",s),l.setInt("uSrcWidth",r),l.setInt("uUseMap",o),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?Qd:Yd,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,o;if(this._disposed||t<=0||!this.supportsAsyncCentersReadback)return null;const s=this._textureSize,r=this._baseOffset+e,i=Math.floor(r/s),a=Math.ceil((r+t)/s)-i,l=4*(r-i*s),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,s,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,f=h._gl,p=null===(o=null===(n=c.getInternalTexture())||void 0===n?void 0:n._hardwareTexture)||void 0===o?void 0:o.underlyingResource;if(!p)return null;const m=new Float32Array(s*a*4);this._readFbo||(this._readFbo=f.createFramebuffer());const _=h._currentFramebuffer;f.bindFramebuffer(f.FRAMEBUFFER,this._readFbo),f.framebufferTexture2D(f.FRAMEBUFFER,f.COLOR_ATTACHMENT0,f.TEXTURE_2D,p,0),f.readBuffer(f.COLOR_ATTACHMENT0);const g=h._readPixelsAsync(0,i,s,a,f.RGBA,f.FLOAT,m);return f.bindFramebuffer(f.FRAMEBUFFER,_),_||f.readBuffer(f.BACK),g?(yield g,this._disposed||m.length<u?null:m.subarray(l,u)):null})}dispose(){var e,t,n,o,s,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===(o=this._copyMaterial)||void 0===o||o.dispose(!0,!1),null===(s=this._shCopyMaterial)||void 0===s||s.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?Qd:Yd,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,o,s,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!==(o=e.scalesMin)&&void 0!==o?o:[0,0,0],c=null!==(s=e.scalesMax)&&void 0!==s?s:[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?Qd:Yd,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,o,s,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!==(o=e.codebookTexture)&&void 0!==o?o:l),i.setFloat("sogShnMin",null!==(s=e.shnMin)&&void 0!==s?s: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?Qd:Yd,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,o,s;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!==(o=e.scalesMin)&&void 0!==o?o:[0,0,0],l=null!==(s=e.scalesMax)&&void 0!==s?s:[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 Jd{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 o={url:e,groupId:t,settled:!1,cancelled:!1,started:!1,slotReleased:!1};if(o.promise=new Promise((e,t)=>{o.resolve=e,o.reject=t}),this._pending.set(e,o),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(o),this._pump(),yield o.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,o;if(e.settled)return;e.cancelled=!0;const s=this._queue.indexOf(e);-1!==s&&this._queue.splice(s,1),null===(n=e.request)||void 0===n||n.abort(),null===(o=e.cancelAttempt)||void 0===o||o.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,o)=>{e.cancelAttempt=o,e.request=t.Tools.LoadFile(e.url,e=>n(e),void 0,void 0,!0,(t,n)=>o(n instanceof Error?n:new Error(`GaussianSplattingDownloadManager: failed to load ${e.url}.`)))})})}}class eh{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 th{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,o=t&&t._free,s=n&&n._free;o&&s?(t._size+=e._size+n._size,this._removeFromMainList(e),this._removeFromMainList(n),this._removeFromBucket(n),this._release(e),this._release(n),this._rebucket(t)):o?(t._size+=e._size,this._removeFromMainList(e),this._release(e),this._rebucket(t)):s?(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],o=this.allocate(n);if(!o){let o=n;for(let n=e+1;n<t.length;n++)o+=t[n];const s=this._usedSize+o,r=Math.ceil(s*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]=o}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 o=this._pool.length>0?this._pool.pop():new eh;return o._offset=e,o._size=t,o._free=n,o._prev=null,o._next=null,o._prevFree=null,o._nextFree=null,o._bucket=-1,o}_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,o=this._freeBucketHeads[t];for(;o&&!(o._size>=e&&(!n||o._size<n._size)&&(n=o,o._size===e));)o=o._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 o=this._capacity-t;if(o>0){const e=this._obtain(t,o,!0);this._insertAfterInMainList(e,this._tailAll),this._addToBucket(e)}}_defragIncremental(e,t){const n=Math.ceil(e/2),o=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 s=this._headAll;for(let e=0;e<o&&s;){const n=s._next;if(s._free&&n&&!n._free){const o=n,r=s;o._offset=r._offset,r._offset=o._offset+o._size;const i=r._prev,a=o._next;if(o._prev=i,o._next=r,r._prev=o,r._next=a,i?i._next=o:this._headAll=o,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(o),e++,s=r._next}else s=n}}_moveBlock(e,t){const n=e._size,o=t._offset,s=e._prev;this._removeFromMainList(e);const r=this._obtain(e._offset,n,!0);if(this._insertAfterInMainList(r,s),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=o,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 nh{constructor(e,t,n){this._blocks=new Map,this._cooldown=new Map,this._pinned=new Set,this._allocator=new th(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 o=this._allocator.allocate(t);return o||(this._evictAllCooled(),o=this._allocator.allocate(t),o)?(this._blocks.set(e,o),o.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,o]of Array.from(this._blocks)){const s=e.get(n);s!==o.offset&&t.push({file:n,oldOffset:s,newOffset:o.offset,count:o.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 oh=Math.tan(22.5*Math.PI/180),sh=new t.Matrix,rh=new t.Vector3,ih=new t.Vector3,ah=new t.Vector3,lh=new t.Vector3(0,0,1),uh=[[0,1],[1,2],[2,3],[3,0],[4,5],[5,6],[6,7],[7,4],[0,4],[1,5],[2,6],[3,7]],ch=2*uh.length,dh=[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 hh 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,o,s,r={}){var i,a,l,u,c;const d=hh._NormalizeResidentLimit(null!==(i=r.maxResidentSplats)&&void 0!==i?i:0,"maxResidentSplats",!0),h=hh._NormalizeResidentLimit(null!==(a=r.memoryBudgetMb)&&void 0!==a?a:0,"memoryBudgetMb",!1);super(e,null,s,!1),this._leafNodes=[],this._lod0SplatCount=Object.freeze({status:"pending"}),this._lodBaseDistance=5,this._lodMultiplier=3,this._lodBehindPenalty=1,this._lodRangeMin=0,this._maxDecodesPerFrame=1,this._lodCooldownFrames=10,this._lodUpdateInterval=4,this._lodUpdateDistance=.5,this._maxDetailLod=0,this._lodPixelThreshold=1,this._hostBudgetAllocation=null,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._cullCameraViewProj=new t.Matrix,this._cullViewProj=new t.Matrix,this._frustumScratch=[],this._workBuffer=null,this._streamShDegree=0,this._shTextureCount=0,this._needsRotationScale=!1,this._useGpuPositionReadback=!1,this._readbackCandidate=!1,this._readbackProbed=!1,this._residency=null,this._fileCounts=new Map,this._fileMeta=new Map,this._baseFileIds=new Set,this._decodedFiles=new Set,this._loadingFiles=new Set,this._decodeQueue=[],this._fileRefs=new Map,this._cancelledDecodes=new Set,this._evictionEnabled=!1,this._residentBudget=0,this._minimumResidentSplats=0,this._maxResidentSplats=0,this._memoryBudgetMb=0,this._evictionCooldownFrames=100,this._decodeGate=Promise.resolve(),this._relayoutOldOffsets=new Map,this._relayoutSrcIndex=null,this._environmentRange=null,this._environmentFiles=null,this._lodObserver=null,this._baseLayerReady=!1,this._metadataReady=!1,this._framesSinceLodUpdate=0,this._lastLodCamPositions=[],this._lastLodSignature="",this._forceLodUpdate=!1,this._boundsMin=new 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=o,this._streamOptions=r,this._hostCompound=null!==(l=r.hostCompound)&&void 0!==l?l:null,this._decodeSh=null===(u=r.decodeSh)||void 0===u||u,this._needsRotationScale=null!==(c=r.needsRotationScale)&&void 0!==c&&c;const f=Math.max(0,n.lodLevels-1);if(this._lodRangeMax=f,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,f))),void 0!==r.lodRangeMax&&(this._lodRangeMax=Math.max(this._lodRangeMin,Math.min(r.lodRangeMax,f))),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))),this._splatBudget=this._resolveSplatBudget(r.splatBudget),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))),this._maxResidentSplats=d,this._memoryBudgetMb=h,this._downloadManager=new Jd({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,o;this._lod0SplatCount=Object.freeze({status:"unavailable"}),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!==(o=null==e?void 0:e.message)&&void 0!==o?o:e)),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 o=0;const s=()=>this._isLoadingIdle()&&this._sinkIsDepthSortSettled?++o>=t:(o=0,!1);if(n.getEngine().activeRenderLoops.length>0)return void(yield new Promise(e=>{let t=null;t=n.onAfterRenderObservable.add(()=>{(this._disposed||s())&&(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(),s())return;yield new Promise(e=>{"function"==typeof i?i(()=>e()):setTimeout(e,16)})}})}_isLoadingIdle(){return this._baseLayerReady&&this._metadataReady&&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 splatBudget(){return this._splatBudget}set splatBudget(e){const t=e>0?Math.floor(e):0;t!==this._splatBudget&&(this._splatBudget=t,this._forceLodUpdate=!0)}get effectiveSplatBudget(){return this._effectiveSplatBudget()}get residentSplatBudget(){return this._residentBudget}get minimumResidentSplats(){return this._minimumResidentSplats}get lod0SplatCount(){return this._lod0SplatCount}_resolveSplatBudget(e){return void 0===e?0:"auto"===e?this._computeDefaultSplatBudget():e>0?Math.floor(e):0}_computeDefaultSplatBudget(){var e;return(null===(e=this._scene.getEngine().hostInformation)||void 0===e?void 0:e.isMobile)?"undefined"!=typeof navigator&&navigator.userAgent&&/iPad|iPhone|iPod/.test(navigator.userAgent)?15e5:1e6:25e5}_effectiveSplatBudget(){if(null!==this._hostBudgetAllocation){const e=Math.max(1,this._hostBudgetAllocation);return this._residentBudget>0?Math.min(e,this._residentBudget):e}return this._splatBudget<=0?0:this._residentBudget>0?Math.min(this._splatBudget,this._residentBudget):this._splatBudget}_splatBudgetEnabled(){return this._effectiveSplatBudget()>0}getBudgetDemand(){var e;if(!this._baseLayerReady)return 0;let t=this._environmentSplatCount();for(const n of this._leafNodes){const o=null!==(e=n.optimalLod)&&void 0!==e?e:n.baseLod;t+=this._countAtLevel(n,this._cappedLevelForNode(n,o))}return t}setBudgetAllocation(e){if(null===e)return void(null!==this._hostBudgetAllocation&&(this._hostBudgetAllocation=null,this._forceLodUpdate=!0));const t=this._hostBudgetAllocation;this._hostBudgetAllocation=e,null!==t&&e===t||(this._forceLodUpdate=!0)}get maxLodLevel(){return Math.max(0,this._metadata.lodLevels-1)}get frustumCulling(){return this._frustumCulling}set frustumCulling(e){this._frustumCulling!==e&&(this._frustumCulling=e,this._forceLodUpdate=!0)}get debugDisplay(){return this._debugDisplay}set debugDisplay(e){this._debugDisplay!==e&&(this._debugDisplay=e,e?this._refreshDebugDisplay():this._clearDebugDisplay())}get debugLodSource(){return this._debugLodSource}set debugLodSource(e){this._debugLodSource!==e&&(this._debugLodSource=e,this._debugDisplay&&this._refreshDebugDisplay())}dispose(e){var t,n,o,s,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===(o=this._hostUnsubRemove)||void 0===o||o.call(this),null===(s=this._hostUnsubDispose)||void 0===s||s.call(this),this._hostUnsubRemove=null,this._hostUnsubDispose=null,this._hostCompound&&!this._hostCompound.isDisposed()&&this._hostCompound.unregisterLodBudgetParticipant(this),this._host&&this._hostCompound&&!this._partReleasedByHost&&!this._hostCompound.isDisposed()&&this._hostCompound.removePart(this._host.partIndex),this._host=null,this._lodObserver&&(this._scene.onBeforeRenderObservable.remove(this._lodObserver),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)}_getActiveLodCameras(){var e;return((null===(e=this._scene.activeCameras)||void 0===e?void 0:e.length)?this._scene.activeCameras:this._scene.activeCamera?[this._scene.activeCamera]:[]).filter(e=>!!e)}evaluateOptimalLods(e=null){const n=e?[e]:this._getActiveLodCameras();if(0===n.length||0===this._leafNodes.length)return;const o=Math.max(0,this._metadata.lodLevels-1),s=this._lodBaseDistance,r=this._lodMultiplier,i=this._lodBehindPenalty,a=this._lodRangeMin,l=this._lodRangeMax,u=this._splatBudgetEnabled(),c=this._scene.getEngine().getRenderHeight()||1,d=this._scene.getEngine();this._getEffectiveWorldMatrix(!1).invertToRef(sh);const h=n.map(e=>{const n=d.getAspectRatio(e)||1;let o=Math.tan(.5*e.fov);e.fovMode===t.Camera.FOVMODE_HORIZONTAL_FIXED&&(o/=n);const s=o*n,r=Math.min(o,s)/oh,a=c*(e.viewport?e.viewport.height:1),l=t.Vector3.TransformCoordinatesToRef(e.globalPosition,sh,rh),u={px:l.x,py:l.y,pz:l.z,fwx:0,fwy:0,fwz:0,fovScale:r,tanHalfV:o,pixelHeight:a};if(i>1){e.getDirectionToRef(lh,ah);const n=t.Vector3.TransformNormalToRef(ah,sh,ih);n.normalize(),u.fwx=n.x,u.fwy=n.y,u.fwz=n.z}return u});for(const e of this._leafNodes){const t=e.bound.min,n=e.bound.max,c=.5*(t[0]+n[0]),d=.5*(t[1]+n[1]),f=.5*(t[2]+n[2]),p=n[0]-t[0],m=n[1]-t[1],_=n[2]-t[2],g=.5*Math.sqrt(p*p+m*m+_*_);let v=Number.POSITIVE_INFINITY,y=0;for(const e of h){const a=e.px<t[0]?t[0]:e.px>n[0]?n[0]:e.px,l=e.py<t[1]?t[1]:e.py>n[1]?n[1]:e.py,h=e.pz<t[2]?t[2]:e.pz>n[2]?n[2]:e.pz,p=a-e.px,m=l-e.py,_=h-e.pz,b=Math.sqrt(p*p+m*m+_*_);let x=b;if(i>1&&b>.01){const t=(e.fwx*p+e.fwy*m+e.fwz*_)/b;t<0&&(x=b*(1+-t*(i-1)))}const T=x*e.fovScale;let A;if(0===o||T<s)A=0;else for(A=o;A>1&&T<s*Math.pow(r,A-1);)A--;if(A<v&&(v=A),u){const t=c-e.px,n=d-e.py,o=f-e.pz,s=Math.sqrt(t*t+n*n+o*o),r=g*e.pixelHeight/(Math.max(s,1e-4)*e.tanHalfV);r>y&&(y=r)}}v<a?v=a:v>l&&(v=l),this._frustumCulling&&!1===e.inFrustum&&(v=l),e.optimalLod=v,u&&(e.pixelSize=y)}}_displayedLodLevel(e){var t,n,o;return"optimal"===this._debugLodSource?null!==(n=null!==(t=e.optimalLod)&&void 0!==t?t:e.activeLod)&&void 0!==n?n:0:null!==(o=e.activeLod)&&void 0!==o?o: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 o of this._leafNodes){const s=dh[this._displayedLodLevel(o)%dh.length],r=o.bound.min,i=o.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 uh)e.push([a[t[0]],a[t[1]]]),n.push([s,s])}if(this._debugSignature=this._computeDebugSignature(),0===e.length)return;const o=t.CreateLineSystem(this.name+"_lodDebug",{lines:e,colors:n,updatable:!0,useVertexAlpha:!1},this._scene);o.parent=this,o.isPickable=!1,o.doNotSerialize=!0,o.reservedDataStore={hidden:!0},this._debugMesh=o,this._debugColorData=new Float32Array(this._leafNodes.length*ch*4)}_updateDebugColors(){if(!this._debugMesh||!this._debugColorData)return;const e=this._debugColorData;let n=0;for(const t of this._leafNodes){const o=dh[this._displayedLodLevel(t)%dh.length];for(let t=0;t<ch;t++)e[n++]=o.r,e[n++]=o.g,e[n++]=o.b,e[n++]=o.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){var n,o;if(e.children){for(const t of e.children)this._collectLodEntries(t);return}if(!e.lods)return;const s=null===(n=e.bound)||void 0===n?void 0:n.min,r=null===(o=e.bound)||void 0===o?void 0:o.max;if(!s||!r||s.length<3||r.length<3||!s.every(e=>Number.isFinite(e))||!r.every(e=>Number.isFinite(e)))return;const i=r[0]-s[0],a=r[1]-s[1],l=r[2]-s[2],u=Math.sqrt(i*i+a*a+l*l);if(!Number.isFinite(u)||u<=0)return;const c=Math.floor(Number(this._metadata.lodLevels)),d=Number.isFinite(c)&&c>0?c-1:0,h=[];for(const t of Object.keys(e.lods)){const n=Number(t),o=e.lods[t],s=o?Math.floor(Number(o.count)):NaN;Number.isInteger(n)&&String(n)===t&&n>=0&&n<=d&&o&&Number.isFinite(s)&&s>0&&(o.count=s,h.push(n))}if(0===h.length)return;h.sort((e,t)=>e-t);const f=[];let p=1/0;for(const t of h){const n=e.lods[String(t)].count;n<=p&&(f.push(t),p=n)}e.availableLevels=f,e.baseLod=f[f.length-1],e.activeLod=void 0,e.lodCooldown=0,e.inFrustum=!0,e.cullBounds=new t.BoundingInfo(t.Vector3.FromArray(s),t.Vector3.FromArray(r)),this._leafNodes.push(e)}_streamAllAsync(){return b(this,void 0,void 0,function*(){const e=this._collectAllFileIds(),n=this._collectBaseFileIds();this._baseFileIds.clear();for(const e of n)this._baseFileIds.add(e);if(this._leafNodes.length>0&&0===n.length)throw new Error("GaussianSplattingStream: no valid coarse source files were referenced.");const o=e.length>32&&n.length<e.length;o&&this._decodeSh&&(this._streamShDegree=4,this._shTextureCount=5);const s=o?n:e,r=yield this._gatherCountsAsync(s);if(this._disposed)return;for(const e of n){const t=this._fileCounts.get(e);if(!this._fileMeta.has(e)||void 0===t||t<=0)throw new Error(`GaussianSplattingStream: required coarse metadata for file ${e} is unavailable or invalid.`)}this._resolveMinimumResidentSplats(n,r),o||(this._resolveLod0SplatCount(),this._metadataReady=!0);let i=null;if(!o){i=1+r;for(const t of e){const e=this._fileCounts.get(t);void 0!==e&&e>0&&(i=hh._SafeAddCounts(i,e,"stream capacity"))}}if(this._minimumResidentSplats<=1)throw new Error("GaussianSplattingStream: stream produced no splats.");let a=0;for(const e of n)a=Math.max(a,this._fileCounts.get(e));const l=this._resolveResidentBudget(i,a);if(this._evictionEnabled=o||null!==i&&l<i,this._residency=new nh(l,this._evictionCooldownFrames,e=>this._onFileEvicted(e)),this._residency.pin(-2,1),r>0){const e=this._residency.allocate(-1,r);null!==e?this._environmentRange={offset:e,count:r}:(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(l,e,this.name+"_part",this._shTextureCount,this._streamShDegree,this._needsRotationScale);this._host=n,this._positionBase=n.base,this._hostCompound.registerLodBudgetParticipant(this);const o=this._hostCompound,s=o.onPartRemovedObservable.add(e=>{!this._disposed&&this._host&&e===this._host.partIndex&&(this._partReleasedByHost=!0,this.dispose())});this._hostUnsubRemove=()=>o.onPartRemovedObservable.remove(s);const r=this._shTextureCount>0&&n.shMrtAtlas?{textureCount:this._shTextureCount,externalMrts:n.shMrtAtlas}:void 0,i=this._needsRotationScale&&n.rotMrtAtlas?{externalMrt:n.rotMrtAtlas}:void 0;this._workBuffer=new Zd(this._scene,n.capacity,{mrt:n.mrtAtlas,width:n.atlasWidth,baseOffset:n.base},r,i),this._readbackCandidate=this._workBuffer.supportsAsyncCentersReadback,this._splatPositions=n.splatPositions,this._vertexCount=l;const a=this._workBuffer;this._unsubBeforeRebuild=n.onBeforeAtlasRebuild(()=>{a.backupRegion(),this._positionSnapshot=this._splatPositions?this._splatPositions.slice(4*this._positionBase,4*(this._positionBase+this._vertexCount)):null}),this._unsubAfterRebuild=n.onAfterAtlasRebuild(()=>{n.mrtAtlas&&a.rebindAtlas(n.mrtAtlas),a.rebindShAtlas(n.shMrtAtlas),a.rebindRotAtlas(n.rotMrtAtlas),this._positionBase=n.base,a.setBaseOffset(n.base),a.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 Zd(this._scene,l,void 0,e,t),this._readbackCandidate=this._workBuffer.supportsAsyncCentersReadback;const n=new Float32Array(4*l),o=this._workBuffer.textures,s=e?this._workBuffer.shTextures:void 0,r=t?this._workBuffer.rotationTextures:void 0;this._setExternalWorkBuffer(o[0],o[1],o[2],o[3],n,l,s,this._streamShDegree,r),this.setSplatIndexRanges([]),this.setEnabled(!0)}if(!(this._host&&this._workBuffer&&(yield this._waitForCanBackupAsync(this._workBuffer),this._disposed))){this._environmentRange&&this._environmentFiles&&(yield this._decodeEnvironmentAsync()),this._environmentFiles=null;for(const e of n){if(this._disposed)return;if(!(yield this._decodeFileAsync(e)))throw new Error(`GaussianSplattingStream: required coarse file ${e} failed to decode.`)}if(!this._disposed){for(const e of this._leafNodes)if(e.activeLod!==e.baseLod||void 0===e.activeFile)throw new Error("GaussianSplattingStream: the complete coarse layer could not be activated.");if(this._baseLayerReady=!0,this._resolvePartReady(),o){const t=e.filter(e=>!this._baseFileIds.has(e));if(yield this._gatherCountsAsync(t,!1),this._resolveLod0SplatCount(),this._metadataReady=!0,this._disposed)return}this._lodObserver||(this._lodObserver=this._scene.onBeforeRenderObservable.add(()=>this._onLodFrame()))}}})}_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(e=null,n=0){var o;const s=this._maxResidentSplats>0||this._memoryBudgetMb>0;let r=this._maxResidentSplats>0?this._maxResidentSplats:Number.POSITIVE_INFINITY;const i=this._bytesPerResidentSplat();if(this._memoryBudgetMb>0){const e=Math.floor(1024*this._memoryBudgetMb*1024/i);r=Math.min(r,e)}if(s||null===e)if(s)r<this._minimumResidentSplats&&t.Logger.Warn(`GaussianSplattingStream: the requested initial residency (${r} splats) is below the complete coarse minimum (${this._minimumResidentSplats}); using the minimum.`);else{const e=(null===(o=this._scene.getEngine().hostInformation)||void 0===o?void 0:o.isMobile)?256:512,t=Math.floor(1024*e*1024/i),s=Math.max(0,Math.floor(n)),a=hh._SafeAddCounts(this._minimumResidentSplats,s,"automatic resident capacity");r=Math.max(t,a)}else r=e;if(r=Math.max(this._minimumResidentSplats,Math.floor(r)),null!==e&&(r=Math.min(r,e)),null!==e||this._minimumResidentSplats>0){const e=Math.floor(this._scene.getEngine().getCaps().maxTextureSize),t=e*e;if(!Number.isSafeInteger(t)||this._minimumResidentSplats>t)throw new Error(`GaussianSplattingStream: minimum resident splat count ${this._minimumResidentSplats} exceeds the device texture capacity ${t}.`);if(r>t&&(r=t),r<this._minimumResidentSplats)throw new Error(`GaussianSplattingStream: minimum resident splat count ${this._minimumResidentSplats} exceeds the device texture capacity ${t}.`)}if(!Number.isSafeInteger(r)||r<this._minimumResidentSplats||r<1)throw new Error("GaussianSplattingStream: resolved resident capacity is invalid.");return this._residentBudget=r,r}_bytesPerResidentSplat(){const e=this._scene.getEngine().getCaps().textureHalfFloatRender?24:48;return 84+16*this._shTextureCount+(this._needsRotationScale?e:0)}_collectAllFileIds(){const e=new Set;for(const t of this._leafNodes)for(const n of t.availableLevels){const o=t.lods[String(n)];o&&e.add(o.file)}return Array.from(e).sort((e,t)=>e-t)}_collectBaseFileIds(){var e;const t=new Set;for(const n of this._leafNodes){const o=null===(e=n.lods)||void 0===e?void 0:e[String(n.baseLod)];o&&t.add(o.file)}return Array.from(t).sort((e,t)=>e-t)}_resolveMinimumResidentSplats(e,t){let n=hh._SafeAddCounts(1,Math.max(0,Math.floor(t)),"minimum resident splats");for(const t of e){const e=this._fileCounts.get(t);if(void 0===e||!Number.isSafeInteger(e)||e<=0)throw new Error(`GaussianSplattingStream: required coarse metadata for file ${t} is unavailable or invalid.`);n=hh._SafeAddCounts(n,e,"minimum resident splats")}this._minimumResidentSplats=n}_resolveLod0SplatCount(){var e,t;let n=0,o=!1;for(const s of this._leafNodes){if(0!==(null===(e=s.availableLevels)||void 0===e?void 0:e[0]))continue;const r=null===(t=s.lods)||void 0===t?void 0:t[0];if(!r)return void(this._lod0SplatCount=Object.freeze({status:"unavailable"}));if(o=!0,!this._fileCounts.has(r.file)||!this._fileMeta.has(r.file))return void(this._lod0SplatCount=Object.freeze({status:"unavailable"}));if(n+=r.count,!Number.isSafeInteger(n))return void(this._lod0SplatCount=Object.freeze({status:"unavailable"}))}this._lod0SplatCount=o?Object.freeze({status:"available",count:n}):Object.freeze({status:"unavailable"})}_gatherCountsAsync(e){return b(this,arguments,void 0,function*(e,n=!0){var o;let s=0,r=0,i=0;const a=e=>{const t=hh._GetShInfo(e);t.degree>r&&(r=t.degree),t.coeffs>i&&(i=t.coeffs)};if(n&&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=hh._GetSplatCount(e),a(e),this._environmentFiles=n}}catch(e){t.Logger.Warn("GaussianSplattingStream: failed to load environment: "+(null!==(o=null==e?void 0:e.message)&&void 0!==o?o:e))}yield Promise.all(e.map(e=>b(this,void 0,void 0,function*(){var n;const o=this._metadata.filenames[e];if(o)try{const t=this._rootUrl+o,n=t.substring(0,t.lastIndexOf("/")+1),s=yield this._downloadManager.loadFileAsync(t),r=JSON.parse((new TextDecoder).decode(new Uint8Array(s)));this._fileCounts.set(e,hh._GetSplatCount(r)),this._fileMeta.set(e,{sogData:r,subRootUrl:n})}catch(e){t.Logger.Warn(`GaussianSplattingStream: failed to load metadata for ${o}: ${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())a(e);return this._decodeSh&&r>0&&i>0&&(this._streamShDegree=Math.max(this._streamShDegree,r),this._shTextureCount=Math.max(this._shTextureCount,Math.ceil(3*i/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,o){return b(this,void 0,void 0,function*(){if(this._readbackProbed=!0,!this._workBuffer)return;const s=Math.min(n,1024);let r=!1;try{const t=yield this._workBuffer.readCentersRangeAsync(e,s);if(this._disposed)return;if(t&&t.length>=4*s){r=!0;for(let e=0;e<s&&r;e++)for(let n=0;n<3;n++){const s=t[4*e+n],i=o[4*e+n];if(Math.abs(s-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 o=e.positions.length>=4*n?e.positions.subarray(0,4*n):null;return!(!o||!this._splatPositions||(this._applyPositions(o,t,n),!this._readbackProbed&&this._readbackCandidate&&(yield this._probeReadbackAsync(t,n,o)),0))})}_decodeEnvironmentAsync(){return b(this,void 0,void 0,function*(){var e,n,o;if(!this._environmentRange||!this._environmentFiles||!this._workBuffer)return;const s=this._environmentRange;let r=!1;try{const n=(yield Xd(this._environmentFiles,"",this._scene,!this._useGpuPositionReadback,this._downloadManager)).sogTextures;if(!n)return void t.Logger.Warn("GaussianSplattingStream: environment decoding produced no texture data.");try{if(this._disposed||!this._workBuffer)return;if(yield this._workBuffer.decodeAsync(n,s.offset),this._disposed)return;const o=yield this._applyDecodedPositionsAsync(n,s.offset,s.count);if(this._disposed)return;if(!o)return void t.Logger.Warn("GaussianSplattingStream: decoded positions could not be applied for the environment.");if((null===(e=this._residency)||void 0===e?void 0:e.pin(-1,s.count))!==s.offset)throw new Error("GaussianSplattingStream: decoded environment could not be pinned.");r=!0,this._refreshActiveRanges()}finally{hh._DisposePack(n)}}catch(e){t.Logger.Warn("GaussianSplattingStream: failed to decode environment: "+(null!==(n=null==e?void 0:e.message)&&void 0!==n?n:e))}finally{r||(null===(o=this._residency)||void 0===o||o.free(-1),this._environmentRange=null)}})}_decodeFileAsync(e){return b(this,void 0,void 0,function*(){var n;if(this._decodedFiles.has(e))return!0;if(this._loadingFiles.has(e)||!this._residency)return!1;const o=this._fileMeta.get(e),s=this._fileCounts.get(e);if(!o||void 0===s)return!1;this._loadingFiles.add(e),this._cancelledDecodes.delete(e);let r=!1;try{const n=(yield Xd(o.sogData,o.subRootUrl,this._scene,!this._useGpuPositionReadback,this._downloadManager,e)).sogTextures;if(!n)return!1;const i=yield this._acquireDecodeGateAsync();try{if(this._disposed||!this._workBuffer||this._cancelledDecodes.has(e))return!1;const o=this._residency;if(!o)return!1;let i=o.allocate(e,s);if(null===i&&(i=yield this._relayoutAndAllocateAsync(e,s)),null===i)return this._cancelledDecodes.has(e)||t.Logger.Warn(`GaussianSplattingStream: resident memory budget full; skipping LOD file ${e}.`),!1;if(r=!0,this._disposed||!this._workBuffer||this._cancelledDecodes.has(e))return!1;if(yield this._workBuffer.decodeAsync(n,i),this._disposed||this._cancelledDecodes.has(e))return!1;const a=yield this._applyDecodedPositionsAsync(n,i,s);if(this._disposed)return!1;if(!a)return t.Logger.Warn(`GaussianSplattingStream: decoded positions could not be applied for LOD file ${e}.`),!1;if(this._baseFileIds.has(e)&&o.pin(e,s)!==i)throw new Error(`GaussianSplattingStream: required coarse file ${e} could not be pinned.`);return this._decodedFiles.add(e),this._applyDesiredLods()&&this._refreshActiveRanges(),!0}finally{hh._DisposePack(n),i()}}catch(t){if(!this._cancelledDecodes.has(e))throw t;return!1}finally{r&&!this._decodedFiles.has(e)&&(null===(n=this._residency)||void 0===n||n.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 o=()=>{!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(o):n(null)};this._scene.onBeforeRenderObservable.addOnce(o)}):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 o=this._residency.getResidentBlocks();for(const t of o){const o=e.get(t.file);for(let e=0;e<t.count;e++)n[t.offset+e]=o+e}this._workBuffer.relayoutSync(n);const s=this._splatPositions,r=this._positionBase;o.sort((e,t)=>e.offset-t.offset);for(const t of o){const n=e.get(t.file);n!==t.offset&&s.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,o=this._maxDetailLod;let s=-1,r=Number.POSITIVE_INFINITY;for(const e of n){if(e<o)continue;const n=Math.abs(e-t);n<r&&(s=e,r=n)}return s<0?e.baseLod:s}_computeTargetLevels(){var e;const t=this._effectiveSplatBudget();if(t<=0){for(const t of this._leafNodes){const n=null!==(e=t.optimalLod)&&void 0!==e?e:t.baseLod;t.targetLevel=this._cappedLevelForNode(t,n)}return}const n=Math.max(0,t-this._environmentSplatCount());this._convergePixelThreshold(n);const o=this._lodPixelThreshold;for(const e of this._leafNodes)e.targetLevel=this._budgetedLevel(e,o)}_environmentSplatCount(){const e=this._environmentRange?Math.floor(Number(this._environmentRange.count)):0;return Number.isFinite(e)&&e>0?e:0}_budgetedLevel(e,t){var n,o;const s=null!==(n=e.optimalLod)&&void 0!==n?n:e.baseLod,r=null!==(o=e.pixelSize)&&void 0!==o?o:0;let i=0;return r>0&&t>r&&(i=Math.max(0,Math.round(Math.log(t/r)/Math.log(this._lodMultiplier)))),this._cappedLevelForNode(e,s+i)}_countAtLevel(e,t){const n=e.lods[String(t)];return n?n.count:0}_totalSplatsAtThreshold(e){let t=0;for(const n of this._leafNodes)t+=this._countAtLevel(n,this._budgetedLevel(n,e));return t}_convergePixelThreshold(e){if(this._totalSplatsAtThreshold(1)<=e)return void(this._lodPixelThreshold=1);let t=1;for(const e of this._leafNodes)e.pixelSize&&e.pixelSize>t&&(t=e.pixelSize);const n=Math.min(32,Math.max(1,this._metadata.lodLevels)),o=t*Math.pow(this._lodMultiplier,n+1);if(this._totalSplatsAtThreshold(o)>e)return void(this._lodPixelThreshold=o);let s=1,r=o;for(let t=0;t<40&&r-s>.001*r;t++){const t=.5*(s+r);this._totalSplatsAtThreshold(t)<=e?r=t:s=t}this._lodPixelThreshold=r}_residentLevelAtLeast(e,t){for(const n of e.availableLevels)if(n>=t&&this._decodedFiles.has(e.lods[String(n)].file))return n;return null}_applyDesiredLods(){var e;let t=!1;for(const n of this._leafNodes){const o=null!==(e=n.targetLevel)&&void 0!==e?e:n.baseLod;if(this._splatBudgetEnabled()&&void 0!==n.activeLod&&n.activeLod<o){const e=this._residentLevelAtLeast(n,o);null!==e&&e!==n.activeLod&&(this._switchActiveFile(n,n.lods[String(e)].file),n.activeLod=e,n.lodCooldown=this._lodCooldownFrames,t=!0)}if(n.lodCooldown&&n.lodCooldown>0)continue;let s;if(o!==n.activeLod){const e=n.lods[String(o)];e&&(this._decodedFiles.has(e.file)?(this._switchActiveFile(n,e.file),n.activeLod=o,n.lodCooldown=this._lodCooldownFrames,t=!0):s=e.file)}n.pendingFile!==s&&(void 0!==n.pendingFile&&this._releaseFileRef(n.pendingFile),void 0!==s&&this._acquirePendingFile(s),n.pendingFile=s)}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 o=(null!==(t=this._fileRefs.get(e))&&void 0!==t?t:0)+1;this._fileRefs.set(e,o),1===o&&(null===(n=this._residency)||void 0===n||n.cancelEviction(e))}_acquirePendingFile(e){this._acquireFileRef(e),this._enqueueDecode(e)}_releaseFileRef(e){var t,n;const o=(null!==(t=this._fileRefs.get(e))&&void 0!==t?t:0)-1;if(o>0)return void this._fileRefs.set(e,o);if(this._fileRefs.delete(e),this._decodedFiles.has(e))return void(this._evictionEnabled&&(null===(n=this._residency)||void 0===n||n.scheduleEviction(e)));const s=this._decodeQueue.indexOf(e);-1!==s&&this._decodeQueue.splice(s,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 o=this._updateNodeFrustum();let s=this._forceLodUpdate||o||n;if(!s&&++this._framesSinceLodUpdate>=this._lodUpdateInterval){const e=this._getActiveLodCameras(),n=this._lodUpdateDistance;if(e.length!==this._lastLodCamPositions.length||this._computeLodSignature(e)!==this._lastLodSignature)s=!0;else for(let o=0;o<e.length;o++)if(t.Vector3.DistanceSquared(e[o].globalPosition,this._lastLodCamPositions[o])>=n*n){s=!0;break}}if(s){this._forceLodUpdate=!1,this._framesSinceLodUpdate=0;const e=this._getActiveLodCameras();this._lastLodCamPositions.length=0;for(const t of e)this._lastLodCamPositions.push(t.globalPosition.clone());this._lastLodSignature=this._computeLodSignature(e),this.evaluateOptimalLods(),this._computeTargetLevels(),this._applyDesiredLods()&&this._refreshActiveRanges()}}_computeLodSignature(e){const t=this._scene.getEngine();let n=`${t.getRenderWidth()}x${t.getRenderHeight()}#${this._getEffectiveWorldMatrix(!1).updateFlag}`;for(const t of e){const e=t.viewport;n+=`|${t.uniqueId}:${t.fov}:${t.fovMode}:${e.x},${e.y},${e.width},${e.height}`}return n}_updateNodeFrustum(){const e=this._getActiveLodCameras();let n=!1;if(!this._frustumCulling||0===e.length){for(const e of this._leafNodes)!1===e.inFrustum&&(e.inFrustum=!0,n=!0);return n}const o=this._leafNodes,s=this._frustumScratch,r=this._getEffectiveWorldMatrix(!1);for(let e=0;e<o.length;e++)s[e]=!1;for(const n of e){n.getViewMatrix().multiplyToRef(n.getProjectionMatrix(),this._cullCameraViewProj),r.multiplyToRef(this._cullCameraViewProj,this._cullViewProj),t.Frustum.GetPlanesToRef(this._cullViewProj,this._frustumPlanes);let e=!0;for(const t of this._frustumPlanes)if(!(Number.isFinite(t.normal.x)&&Number.isFinite(t.normal.y)&&Number.isFinite(t.normal.z)&&Number.isFinite(t.d)&&0!==t.normal.lengthSquared())){e=!1;break}if(e)for(let e=0;e<o.length;e++)!s[e]&&o[e].cullBounds.isInFrustum(this._frustumPlanes)&&(s[e]=!0);else for(let e=0;e<o.length;e++)s[e]=!0}for(let e=0;e<o.length;e++)s[e]!==o[e].inFrustum&&(o[e].inFrustum=s[e],n=!0);return n}static _NormalizeResidentLimit(e,t,n){if(!Number.isFinite(e))throw new RangeError(`GaussianSplattingStream: ${t} must be finite.`);if(e<=0)return 0;const o=n?Math.max(1,Math.floor(e)):e;if(o>Number.MAX_SAFE_INTEGER)throw new RangeError(`GaussianSplattingStream: ${t} is outside the supported range.`);return o}static _SafeAddCounts(e,t,n){const o=e+t;if(!Number.isSafeInteger(e)||e<0||!Number.isSafeInteger(t)||t<0||!Number.isSafeInteger(o))throw new Error(`GaussianSplattingStream: ${n} exceeds the supported integer range.`);return o}static _GetSplatCount(e){var t;const n=null!==(t=e.count)&&void 0!==t?t:Array.isArray(e.means.shape)?e.means.shape[0]:0,o=Math.floor(Number(n));return Number.isFinite(o)&&o>0?o:0}static _GetShInfo(e){if(!e.shN)return{degree:0,coeffs:0};let n=0;const o=e.shN.bands;if("number"==typeof o&&Number.isFinite(o)&&o>0)n=Math.floor(o);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,o;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===(o=e.codebookTexture)||void 0===o||o.dispose()}_updateBounds(e,n){const o=this._boundsMin,s=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];o.minimizeInPlaceFromFloats(n,r,i),s.maximizeInPlaceFromFloats(n,r,i)}this._host?this._host.expandBounds(o,s):this.setBoundingInfo(new t.BoundingInfo(o,s))}_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 o=n.lods[String(n.activeLod)];if(!o)continue;const s=null===(e=this._residency)||void 0===e?void 0:e.offset(o.file);void 0!==s&&t.push({offset:s+o.offset,count:o.count})}this._sinkSetActiveRanges(hh._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 o=n[n.length-1],s=t[e],r=o.offset+o.count;if(s.offset<=r){const e=Math.max(r,s.offset+s.count);o.count=e-o.offset}else n.push({offset:s.offset,count:s.count})}return n}_unzipAsync(e){return b(this,void 0,void 0,function*(){var n;let o=this._streamOptions.fflate;o||(void 0===window.fflate&&(yield t.Tools.LoadScriptAsync(null!==(n=this._streamOptions.deflateURL)&&void 0!==n?n:"https://unpkg.com/fflate/umd/index.js")),o=window.fflate);const s=o.unzipSync(e),r=new Map;for(const[e,t]of Object.entries(s))r.set(e,t);return r})}}const fh=.28209479177387814;let ph=null,mh=null;class _h{constructor(e={}){this.name=Ud.name,this._assetContainer=null,this.extensions=Ud.extensions,this._loadingOptions=Object.assign(Object.assign({},_h._DefaultLoadingOptions),e)}createPlugin(e){return new _h(e[Ud.name])}importMeshAsync(e,t,n,o,s,r){return b(this,void 0,void 0,function*(){const s=this._tryCreateLODStream(t,n,o);return s?{meshes:[s],particleSystems:[],skeletons:[],animationGroups:[],transformNodes:[],geometries:[],lights:[],spriteManagers:[]}:yield this._parseAsync(e,t,n,o).then(e=>({meshes:e,particleSystems:[],skeletons:[],animationGroups:[],transformNodes:[],geometries:[],lights:[],spriteManagers:[]}))})}_tryCreateLODStream(e,t,n){if("string"!=typeof t)return null;let o;try{o=JSON.parse(t)}catch(e){return null}if(!hh.IsLODMetadata(o))return null;const s=e._blockEntityCollection;e._blockEntityCollection=!!this._assetContainer;try{const t=new hh("GaussianSplattingStream",o,n,e,{deflateURL:this._loadingOptions.deflateURL,fflate:this._loadingOptions.fflate});return t._parentContainer=this._assetContainer,t}finally{e._blockEntityCollection=s}}static _BuildPointCloud(e,n){if(!n.byteLength)return!1;const o=new Uint8Array(n),s=new Float32Array(n),r=o.length/32;return e.addPoints(r,function(e,n){const r=s[8*n+0],i=s[8*n+1],a=s[8*n+2];e.position=new t.Vector3(r,i,a);const l=o[32*n+24+0]/255,u=o[32*n+24+1]/255,c=o[32*n+24+2]/255;e.color=new t.Color4(l,u,c,1)}),!0}static _BuildMesh(e,n){const o=new t.Mesh("PLYMesh",e),s=new Uint8Array(n.data),r=new Float32Array(n.data),i=s.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],o=r[8*e+2];a.push(t,n,o)}if(n.hasVertexColors){const e=new Float32Array(4*i);for(let t=0;t<i;t++){const n=s[32*t+24+0]/255,o=s[32*t+24+1]/255,r=s[32*t+24+2]/255;e[4*t+0]=n,e[4*t+1]=o,e[4*t+2]=r,e[4*t+3]=1}l.colors=e}return l.positions=a,l.indices=n.faces,l.applyToMesh(o),o}_unzipWithFFlateAsync(e){return b(this,void 0,void 0,function*(){var n;let o=this._loadingOptions.fflate;o||(void 0===window.fflate&&(yield t.Tools.LoadScriptAsync(null!==(n=this._loadingOptions.deflateURL)&&void 0!==n?n:"https://unpkg.com/fflate/umd/index.js")),o=window.fflate);const{unzipSync:s}=o,r=s(e),i=new Map;for(const[e,t]of Object.entries(r))i.set(e,t);return i})}_parseAsync(e,n,o,s){const r=[],i=e=>{var o;n._blockEntityCollection=!!this._assetContainer;const s=null!==(o=this._loadingOptions.gaussianSplattingMesh)&&void 0!==o?o:new t.GaussianSplattingMesh("GaussianSplatting",null,n,this._loadingOptions.keepInRam,this._loadingOptions.needsRotationScaleTextures);s._parentContainer=this._assetContainer,r.push(s),e.sogTextures?s.setSogTextureData(e.sogTextures):s.updateData(e.data,e.sh,{flipY:!1},void 0,e.shDegree),s.scaling.y*=-1,s.computeWorldMatrix(!0),s.safeOrbitCameraLimits=_h._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?Xd:Wd;if("string"==typeof o){const e=JSON.parse(o);if(e&&e.means&&e.scales&&e.quats&&e.sh0)return new Promise((t,o)=>{u(e,s,n).then(e=>{i(e),t(r)}).catch(e=>{o(new Error("Failed to parse SOG data.",{cause:e}))})})}const c=o instanceof ArrayBuffer?new Uint8Array(o):o;if(80===c[0]&&75===c[1])return new Promise((e,t)=>{this._unzipWithFFlateAsync(c).then(o=>{u(o,s,n).then(t=>{i(t),e(r)}).catch(e=>{t(new Error("Failed to parse SOG zip data.",{cause:e}))})})});const d=e=>{_h._ConvertPLYToSplat(o).then(o=>b(this,void 0,void 0,function*(){var s;switch(n._blockEntityCollection=!!this._assetContainer,o.mode){case 0:{const e=null!==(s=this._loadingOptions.gaussianSplattingMesh)&&void 0!==s?s:new t.GaussianSplattingMesh("GaussianSplatting",null,n,this._loadingOptions.keepInRam,this._loadingOptions.needsRotationScaleTextures);switch(e._parentContainer=this._assetContainer,r.push(e),e.updateData(o.data,o.sh,{flipY:!1},void 0,o.shDegree),e.scaling.y*=-1,"RightHanded"===o.chirality&&(e.scaling.y*=-1),o.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=_h._ExtractSafeOrbitLimits(o)}break;case 1:{const e=new t.PointsCloudSystem("PointCloud",1,n);_h._BuildPointCloud(e,o.data)?yield e.buildMeshAsync().then(e=>{r.push(e)}):e.dispose()}break;case 2:if(!o.faces)throw new Error("PLY mesh doesn't contain face informations.");r.push(_h._BuildMesh(n,o));break;default:throw new Error("Unsupported Splat mode")}n._blockEntityCollection=!1,this.applyAutoCameraLimits(_h._ExtractSafeOrbitLimits(o),n),e(r)}))},h=31===c[0]&&139===c[1],f=78===c[0]&&71===c[1]&&83===c[2]&&80===c[3];if(!h&&!f)return new Promise(e=>{d(e)});const p=(e,o)=>{var s;n._blockEntityCollection=!!this._assetContainer;const i=null!==(s=this._loadingOptions.gaussianSplattingMesh)&&void 0!==s?s: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=_h._ExtractSafeOrbitLimits(e);i.safeOrbitCameraLimits=a,this.applyAutoCameraLimits(a,n),o(r)};if(this._loadingOptions.spzLibraryUrl)return function(e){return b(this,void 0,void 0,function*(){if(ph&&mh===e)return yield ph;const n=t._LoadScriptModuleAsync(`import createSpzModule from '${e}';\n const module = await createSpzModule();\n const returnedValue = module;`);return mh=e,ph=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,o=!1){const s=e.numPoints,r=new ArrayBuffer(32*s),i=new Float32Array(r),a=new Uint8Array(r),l=e.positions,u=e.scales,c=e.colors,d=e.alphas,h=e.rotations;let f=null;const p=e.shDegree;let m,_,g=null,v=0,y=null,b=null,x=null;if(p>0&&e.sh.length>0){v=3*((p+1)*(p+1)-1);const o=Math.ceil(v/16),r=n.getEngine().getCaps().maxTextureSize,i=Math.ceil(s/r);f=t.AllocateShBuffers(o,i*r*4*4),y=new Int32Array(o),b=new Int32Array(o);for(let e=0;e<o;e++)y[e]=16*e,b[e]=Math.min(16*(e+1),v);x=f,g=e.sh}for(let e=0;e<s;e++){const t=8*e,n=32*e,s=3*e,r=4*e;i[t+0]=l[s+0],i[t+1]=l[s+1],i[t+2]=l[s+2],i[t+3]=Math.exp(u[s+0]),i[t+4]=Math.exp(u[s+1]),i[t+5]=Math.exp(u[s+2]);const f=255*(.5+fh*c[s+0]),p=255*(.5+fh*c[s+1]),m=255*(.5+fh*c[s+2]);a[n+24]=f<=0?0:f>=255?255:f+.5|0,a[n+25]=p<=0?0:p>=255?255:p+.5|0,a[n+26]=m<=0?0:m>=255?255:m+.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&&y&&b){const t=e*v,n=16*e;for(let e=0;e<x.length;e++){const o=x[e],s=y[e],r=b[e];for(let e=s;e<r;e++){const r=128*g[t+e]+128;o[n+e-s]=r<=0?0:r>=255?255:r+.5|0}}}e%32768==0&&o&&(yield)}if(e.extensions)for(const t of e.extensions){const e=t;if(void 0!==e.safeOrbitRadiusMin){m=e.safeOrbitRadiusMin,_=[e.safeOrbitElevationMin,e.safeOrbitElevationMax];break}}return{mode:0,data:r,hasVertexColors:!1,sh:null!==f?f:void 0,shDegree:p>0?p:void 0,trainedWithAntialiasing:!!e.antialiased,safeOrbitCameraRadiusMin:m,safeOrbitCameraElevationMinMax:_}}(e,n,!0),t.createYieldingScheduler())})}(e.loadSpzFromBuffer(new Uint8Array(o),{to:e.CoordinateSystem.RUB}),n).then(e=>new Promise(t=>{p(e,t)})));if(f)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 m=new ReadableStream({start(e){e.enqueue(new Uint8Array(o)),e.close()}}),_=new DecompressionStream("gzip"),g=m.pipeThrough(_);return new Promise(e=>{new Response(g).arrayBuffer().then(o=>{(function(e,n){const o=new Uint8Array(e),s=new Uint32Array(e.slice(0,12)),r=s[2],i=o[12],a=o[13],l=o[14],u=o[15],c=s[1];if(u||1347635022!=s[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),f=new Int32Array(1),p=new Uint8Array(f.buffer),m=function(e,t){return p[0]=e[t+0],p[1]=e[t+1],p[2]=e[t+2],p[3]=128&e[t+2]?255:0,f[0]*h};let _=16;const g=new Float32Array(d),v=new Float32Array(d),y=new Uint8ClampedArray(d),b=new Uint8ClampedArray(d);for(let e=0;e<r;e++)g[8*e+0]=m(o,_+0),g[8*e+1]=m(o,_+3),g[8*e+2]=m(o,_+6),_+=9;for(let e=0;e<r;e++){for(let n=0;n<3;n++){const s=(o[_+r+3*e+n]-127.5)/38.25;y[32*e+24+n]=t.Scalar.Clamp(255*(.5+fh*s),0,255)}y[32*e+24+3]=o[_+e]}_+=4*r;for(let e=0;e<r;e++)v[8*e+3+0]=Math.exp(o[_+0]/16-10),v[8*e+3+1]=Math.exp(o[_+1]/16-10),v[8*e+3+2]=Math.exp(o[_+2]/16-10),_+=3;if(c>=3){const e=Math.SQRT1_2;for(let t=0;t<r;t++){const n=[o[_+0],o[_+1],o[_+2],o[_+3]],s=n[0]+(n[1]<<8)+(n[2]<<16)+(n[3]<<24),r=511,i=[],a=s>>>30;let l=s,u=0;for(let t=3;t>=0;--t)if(t!==a){const n=l&r,o=l>>>9&1;l>>>=10,i[t]=e*(n/r),1===o&&(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=o[_+0],n=o[_+1],s=o[_+2],r=t/127.5-1,i=n/127.5-1,a=s/127.5-1;b[32*e+28+1]=t,b[32*e+28+2]=n,b[32*e+28+3]=s;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),s=Math.ceil(e/16);let a=_;const u=n.getEngine().getCaps().maxTextureSize,c=Math.ceil(r/u),h=t.AllocateShBuffers(s,c*u*4*4);for(let t=0;t<r;t++)for(let n=0;n<e;n++){const e=o[a++],s=Math.floor(n/16);h[s][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})})})(o,n,this._loadingOptions).then(t=>{p(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,o){const s=new t.AssetContainer(e);return this._assetContainer=s,this.importMeshAsync(null,e,n,o).then(e=>{for(const t of e.meshes)s.meshes.push(t);return this._assetContainer=null,s}).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),o=(new TextDecoder).decode(n.slice(0,10240)),s=o.indexOf("end_header\n");if(s<0||!o)return new Promise(t=>{t({mode:0,data:e,rawSplat:!0})});const r=parseInt(/element vertex (\d+)\n/.exec(o)[1]),i=/element face (\d+)\n/.exec(o);let a=0;i&&(a=parseInt(i[1]));const l=/element chunk (\d+)\n/.exec(o);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 f=1;const p=[],m=[],_=o.slice(0,s).split("\n"),g={};for(const n of _)if(n.startsWith("property ")){const[,o,s]=n.split(" ");if(1==f)m.push({name:s,type:o,offset:d}),d+=h[o];else if(0==f)p.push({name:s,type:o,offset:c}),c+=h[o];else if(2==f)p.push({name:s,type:o,offset:c});else if(3==f){const t=new DataView(e,d,2*h.float);g.safeOrbitCameraElevationMinMax=[t.getFloat32(0,!0),t.getFloat32(4,!0)]}else if(4==f){const t=new DataView(e,d,h.float);g.safeOrbitCameraRadiusMin=t.getFloat32(0,!0)}else if(5==f){const t=new DataView(e,d,h.uchar);"up_axis"==s?g.upAxis=0==t.getUint8(0)?"X":1==t.getUint8(0)?"Y":"Z":"chirality"==s&&(g.chirality=0==t.getUint8(0)?"LeftHanded":"RightHanded")}h[o]||t.Logger.Warn(`Unsupported property type: ${o}.`)}else if(n.startsWith("element ")){const[,e]=n.split(" ");"chunk"==e?f=1:"vertex"==e?f=0:"sh"==e?f=2:"safe_orbit_camera_elevation_min_max_radians"==e?f=3:"safe_orbit_camera_radius_min"==e?f=4:"up_axis"!=e&&"chirality"!=e||(f=5)}const v=c,y=d;return t.GaussianSplattingMesh.ConvertPLYWithSHToSplatAsync(e).then(t=>b(this,void 0,void 0,function*(){const n=new DataView(e,s+11);let o=y*u+v*r;const i=[];if(a)for(let e=0;e<a;e++){const e=n.getUint8(o);if(3==e){o+=1;for(let t=0;t<e;t++){const e=n.getUint32(o+4*(2-t),!0);i.push(e)}o+=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<p.length;e++){const t=p[e];d.includes(t.name)&&l++,h.includes(t.name)&&c++}const f=l==d.length&&c>=3,m=a?2:f?0:1;return yield new Promise(e=>{e(Object.assign(Object.assign({},g),{mode:m,data:t.buffer,sh:t.sh,shDegree:t.shDegree,faces:i,hasVertexColors:!!c,compressed:!1,rawSplat:!1}))})}))}}_h._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 gh=!1;function vh(){gh||(gh=!0,t.RegisterSceneLoaderPlugin(new _h))}var yh={__proto__:null,RegisterSPLATFileLoader:vh,SPLATFileLoader:_h};vh();const bh={name:"usd",extensions:{".usd":{isBinary:!0},".usda":{isBinary:!0},".usdc":{isBinary:!0},".usdz":{isBinary:!0}}};var xh,Th,Ah,Mh;const wh=4294967295;var Sh,Ch,Rh,Ih,Oh,Fh,Eh,Lh,Nh,kh;function Bh(e){switch(e){case 1:case 11:return 12;case 2:return 48;case 3:return 96;case 4:case 5:return 20;case 6:return 60;case 7:return 40;case 8:return 16;case 9:case 12:return 32;case 10:return 44;default:throw new Error(`Unknown OpenUSD Babylon command opcode ${e}.`)}}!function(e){e[e.Scene=1]="Scene",e[e.Texture=2]="Texture",e[e.Material=3]="Material",e[e.TransformNode=4]="TransformNode",e[e.Skeleton=5]="Skeleton",e[e.Geometry=6]="Geometry",e[e.Mesh=7]="Mesh",e[e.Instance=8]="Instance",e[e.Animation=9]="Animation",e[e.AnalyticPrimitive=10]="AnalyticPrimitive",e[e.ThinInstances=11]="ThinInstances",e[e.MorphTarget=12]="MorphTarget"}(Sh||(Sh={})),function(e){e[e.Cube=0]="Cube",e[e.Sphere=1]="Sphere",e[e.Cylinder=2]="Cylinder",e[e.Cone=3]="Cone"}(Ch||(Ch={})),function(e){e[e.X=0]="X",e[e.Y=1]="Y",e[e.Z=2]="Z"}(Rh||(Rh={})),function(e){e[e.Node=0]="Node",e[e.Bone=1]="Bone",e[e.MorphTarget=2]="MorphTarget"}(Ih||(Ih={})),function(e){e[e.Position=0]="Position",e[e.RotationQuaternion=1]="RotationQuaternion",e[e.Scaling=2]="Scaling",e[e.Matrix=3]="Matrix",e[e.Influence=4]="Influence"}(Oh||(Oh={})),function(e){e[e.DoubleSided=1]="DoubleSided",e[e.Unlit=2]="Unlit",e[e.AlphaBlend=4]="AlphaBlend"}(Fh||(Fh={})),function(e){e[e.R=0]="R",e[e.G=1]="G",e[e.B=2]="B",e[e.A=3]="A",e[e.RGB=4]="RGB"}(Eh||(Eh={})),function(e){e[e.Auto=0]="Auto",e[e.Raw=1]="Raw",e[e.SRGB=2]="SRGB"}(Lh||(Lh={})),function(e){e[e.DoubleSided=1]="DoubleSided",e[e.LeftHanded=2]="LeftHanded"}(Nh||(Nh={})),function(e){e[e.Normals=1]="Normals",e[e.Tangents=2]="Tangents",e[e.Uv0=4]="Uv0",e[e.Colors=8]="Colors",e[e.Skin0=16]="Skin0",e[e.Skin1=32]="Skin1"}(kh||(kh={}));class Ph{constructor(e,t,n){xh.add(this),Th.set(this,void 0),Ah.set(this,void 0),T(this,Th,new DataView(e),"f"),this.offset=t,T(this,Ah,t+n,"f")}u32(){x(this,xh,"m",Mh).call(this,4);const e=x(this,Th,"f").getUint32(this.offset,!0);return this.offset+=4,e}f32(){x(this,xh,"m",Mh).call(this,4);const e=x(this,Th,"f").getFloat32(this.offset,!0);return this.offset+=4,e}}Th=new WeakMap,Ah=new WeakMap,xh=new WeakSet,Mh=function(e){if(this.offset+e>x(this,Ah,"f"))throw new Error("OpenUSD Babylon command payload read exceeded its bounds.")};class Dh extends t.AbstractAssetContainer{dispose(){for(const e of this.animationGroups.splice(0))e.dispose();for(const e of this.meshes.splice(0))e.dispose();for(const e of this.morphTargetManagers.splice(0))e.dispose();for(const e of this.skeletons.splice(0))e.dispose();for(const e of this.multiMaterials.splice(0))e.dispose();for(const e of this.materials.splice(0))e.dispose();for(const e of this.geometries.splice(0))e.dispose();for(const e of this.transformNodes.splice(0))e.dispose();for(const e of this.textures.splice(0))e.dispose();this.rootNodes.length=0}}const Vh=new TextDecoder,Gh="__babylonUsdLocalMatrix";function $h(e,t,n,o,s){if(!Number.isInteger(t)||!Number.isInteger(n)||t<0||n<0||t%Math.min(o,4)!==0||n>Math.floor((e.byteLength-t)/o))throw new Error(`Invalid ${s} range in OpenUSD Babylon data buffer.`)}function Uh(e,t,n){return $h(e,t,n,1,"string"),Vh.decode(new Uint8Array(e,t,n))}function Hh(e,n){$h(e,n,16,4,"matrix");const o=new Float32Array(e,n,16);return t.Matrix.FromValues(o[0],o[1],o[2],o[3],o[4],o[5],o[6],o[7],o[8],o[9],o[10],o[11],o[12],o[13],o[14],o[15])}function Kh(e){switch(e){case 2:return"image/jpeg";case 3:return"image/bmp";case 4:return"image/webp";default:return"image/png"}}function Wh(e){switch(e){case 0:return t.Texture.CLAMP_ADDRESSMODE;case 1:return t.Texture.WRAP_ADDRESSMODE;case 2:return t.Texture.MIRROR_ADDRESSMODE;default:throw new Error(`Invalid texture wrap mode ${e}.`)}}function qh(e,t){return b(this,void 0,void 0,function*(){if(!t)return yield e;let n;const o=new Promise((e,o)=>{n=()=>o(t.reason instanceof Error?t.reason:new Error("USD materialization was aborted.")),t.addEventListener("abort",n,{once:!0}),t.aborted&&n()});try{return yield Promise.race([e,o])}finally{n&&t.removeEventListener("abort",n)}})}const zh=`${t.Tools._DefaultCdnUrl}/babylonUsdImporter/5/`,jh=/\.(?:usd|usda|usdc|usdz)$/i;function Xh(e){return e instanceof Uint8Array?e.slice():e instanceof ArrayBuffer?new Uint8Array(e.slice(0)):new Uint8Array(e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength))}function Yh(e,t,n){const o=null==e?void 0:e.replace(/\\/g,"/").replace(/^\.\/+/,""),s=n?o:null==o?void 0:o.split(/[?#]/,1)[0],r=null==s?void 0:s.split("/").filter(Boolean);return s&&!s.startsWith("/")&&(null==r?void 0:r.length)&&!r.includes("..")&&jh.test(s)?r.join("/"):t.length>=4&&80===t[0]&&75===t[1]&&3===t[2]&&4===t[3]?"scene.usdz":"scene.usd"}class Qh{constructor(e={}){var t,n,o,s,r;this.name=bh.name,this.extensions=bh.extensions,this._nextRequestId=1,this._pending=new Map,this._activeLoads=new Set,this._options=Object.assign(Object.assign({},e),{resolveByFileName:null===(t=e.resolveByFileName)||void 0===t||t,glueUrl:null!==(n=e.glueUrl)&&void 0!==n?n:Qh.DefaultConfiguration.glueUrl,wasmUrl:null!==(o=e.wasmUrl)&&void 0!==o?o:Qh.DefaultConfiguration.wasmUrl,dataUrl:null!==(s=e.dataUrl)&&void 0!==s?s:Qh.DefaultConfiguration.dataUrl,workerUrl:null!==(r=e.workerUrl)&&void 0!==r?r:Qh.DefaultConfiguration.workerUrl})}createPlugin(e){return ef(),new Qh(e[bh.name])}importMeshAsync(e,t,n,o,s,r){return b(this,void 0,void 0,function*(){return{meshes:(e=(yield this._loadAsync(t,n,o,s,r,!0)).container).meshes,particleSystems:e.particleSystems,skeletons:e.skeletons,animationGroups:e.animationGroups,transformNodes:e.transformNodes,geometries:e.geometries,lights:e.lights,spriteManagers:e.spriteManagers};var e})}loadAsync(e,t,n,o,s){return b(this,void 0,void 0,function*(){yield this._loadAsync(e,t,n,o,s,!0)})}loadAssetContainerAsync(e,n,o,s,r){return b(this,void 0,void 0,function*(){const i=(yield this._loadAsync(e,n,o,s,r,!1)).container;if(!(i instanceof t.AssetContainer))throw new Error("USDFileLoader failed to create an asset container.");return i})}dispose(){this._terminateWorker();const e=new Error("USDFileLoader was disposed.");for(const t of this._activeLoads)t.abort(e);for(const t of this._pending.values())t.reject(e);this._pending.clear()}_loadAsync(e,n,o,s,r,i){return b(this,void 0,void 0,function*(){var o,a,l,u,c,d;if(!(n instanceof ArrayBuffer||ArrayBuffer.isView(n)))throw new Error("USDFileLoader expects binary USD data.");const h=Xh(n),f=function(e){if(!e)return;const t={};for(const[n,o]of Object.entries(e))t[n]=Xh(o);return t}(this._options.files),p=this._nextRequestId++,m={type:"extract",requestId:p,asset:{bytes:h,files:f,fileName:Yh(null!==(o=this._options.rootFileName)&&void 0!==o?o:r,h,void 0!==this._options.rootFileName),resolveByFileName:null===(a=this._options.resolveByFileName)||void 0===a||a,glueUrl:this._options.glueUrl,wasmUrl:this._options.wasmUrl,dataUrl:this._options.dataUrl}},_=[...new Set([h.buffer,...Object.values(null!=f?f:{}).map(e=>e.buffer)])],g=new AbortController,v=g.signal;this._activeLoads.add(g);try{const n=this._getWorker(this._options.workerUrl),o=yield new Promise((e,t)=>{this._pending.set(p,{resolve:e,reject:t,onProgress:e=>{var t,n;null===(n=(t=this._options).onProgress)||void 0===n||n.call(t,e),null==s||s({lengthComputable:!1,loaded:Zh[e.phase],total:4})},onLog:this._options.onLog});try{n.postMessage(m,_)}catch(e){this._pending.delete(p),t(e instanceof Error?e:new Error(String(e)))}}),r={phase:"materializing",message:"Creating Babylon.js objects..."};null===(u=(l=this._options).onProgress)||void 0===u||u.call(l,r),null==s||s({lengthComputable:!1,loaded:4,total:4}),v.throwIfAborted();const a=yield function(e,n,o,s,r){return b(this,void 0,void 0,function*(){var i,a,l,u,c,d,h,f,p;null==r||r.throwIfAborted();const m=performance.now(),_=function(e){const t=new DataView(e);if(t.byteLength<16||1111774037!==t.getUint32(0,!0))throw new Error("Invalid OpenUSD Babylon command buffer.");if(5!==t.getUint16(4,!0))throw new Error(`Unsupported OpenUSD Babylon protocol ${t.getUint16(4,!0)}.`);const n=t.getUint32(8,!0),o=[];let s=16;for(let e=0;e<n;++e){if(s+8>t.byteLength)throw new Error("Truncated OpenUSD Babylon command header.");const e=t.getUint16(s,!0),n=t.getUint16(s+2,!0),r=t.getUint32(s+4,!0),i=s+8,a=Bh(e);if(r!==a)throw new Error(`Invalid payload length ${r} for command ${e}; expected ${a}.`);if(i+r>t.byteLength)throw new Error("Truncated OpenUSD Babylon command payload.");o.push({opcode:e,flags:n,payloadOffset:i,payloadLength:r}),s=i+r}if(s!==t.byteLength)throw new Error("Unexpected trailing data in OpenUSD Babylon command buffer.");return o}(n),g=s?new Dh:new t.AssetContainer(e),v=new Map,y=[],x=new Map,T=new Map,A=new Map,M=new Map,w=new Map,S=new Map,C=new Map,R=new Map,I=new Map,O=new Set,F=new Set,E=new Map,L=[],N=new Set,k=[],B=new Map,P=g instanceof t.AssetContainer?g:void 0;let D,V=24,G=!1;const $=e.getEngine().getCaps(),U=$.textureHalfFloatRender&&$.textureHalfFloatLinearFiltering?t.Constants.TEXTURETYPE_HALF_FLOAT:$.textureFloatRender&&$.textureFloatLinearFiltering?t.Constants.TEXTURETYPE_FLOAT:t.Constants.TEXTURETYPE_UNSIGNED_BYTE,H=(e,t)=>{e.push(t),P&&(t._parentContainer=P)},K=(n,o)=>{const s=!(2&o);n.sideOrientation=e.useRightHandedSystem===s?t.Material.CounterClockWiseSideOrientation:t.Material.ClockWiseSideOrientation},W=(e,t)=>{const n=T.get(e);if(!n||!t||!n.backFaceCulling)return null!=n?n:null;let o=A.get(e);return o||(o=n.clone(`${n.name} (double-sided)`),H(g.materials,o),o.backFaceCulling=!1,o.twoSidedLighting=!0,A.set(e,o)),o},q=(e,t,n)=>{if(e===wh){if(t!==wh)throw new Error(`USD ${n} binding has a channel without a texture.`);return}const o=x.get(e);if(!o)throw new Error(`USD ${n} binding references missing texture ${e}.`);if(t<0||t>4)throw new Error(`USD ${n} binding has invalid output channel ${t}.`);return{descriptor:o,channel:t}},z=e=>{if(4===e)throw new Error("A scalar USD texture binding cannot use the RGB output.");return e},j=e=>1===e.descriptor.sourceColorSpace,X=(e,t,n)=>t.every((t,n)=>e.scale[n]===t)&&n.every((t,n)=>e.bias[n]===t),Y=(n,o,s,i,...a)=>b(this,[n,o,s,i,...a],void 0,function*(n,o,s,i,a=o.channel,l=!1){const u=o.descriptor,c=u.texture.getSize(),d=!(e.getEngine().needPOTTextures&&(c.width&c.width-1||c.height&c.height-1)),h={textureType:l?U:t.Constants.TEXTURETYPE_UNSIGNED_BYTE,samplingMode:d?t.Constants.TEXTURE_TRILINEAR_SAMPLINGMODE:t.Constants.TEXTURE_BILINEAR_SAMPLINGMODE,generateMipMaps:d};if(l&&U===t.Constants.TEXTURETYPE_UNSIGNED_BYTE&&s.slice(0,3).some((e,t)=>Math.min(i[t],i[t]+e)<0))throw new Error(`USD texture processing for '${n}' requires a floating-point render target to preserve signed values.`);const f=`${u.id}:${a}:${s.join(",")}:${i.join(",")}:${l}`,p=B.get(f);if(p)return yield p;const m=(()=>b(this,void 0,void 0,function*(){var o;const l=new t.Color4(i[0],i[1],i[2],i[3]),c=new t.Color4(i[0]+s[0],i[1]+s[1],i[2]+s[2],i[3]+s[3]),d=e._blockEntityCollection;let f;e._blockEntityCollection=!0;try{f=t.LerpTexturesAsync(n,t.CreateFactorOperand(l),t.CreateFactorOperand(c),t.CreateTextureOperand(u.texture,(e=>{switch(e){case 0:return t.TextureChannel.R;case 1:return t.TextureChannel.G;case 2:return t.TextureChannel.B;case 3:return t.TextureChannel.A;default:return t.TextureChannel.RGBA}})(a),1===u.sourceColorSpace?t.TextureColorSpace.Linear:t.TextureColorSpace.SRGB),e,t.TextureColorSpace.Linear,void 0,h)}finally{e._blockEntityCollection=d}const p=yield f;if(!p.texture)throw new Error(`USD texture processing for '${n}' did not produce a texture.`);if(G||(null==r?void 0:r.aborted))throw null===(o=p.dispose)||void 0===o||o.call(p),(null==r?void 0:r.aborted)&&r.throwIfAborted(),new Error("USD materialization was rolled back.");P||e.addTexture(p.texture);const m=(e=>(H(g.textures,e),e))(p.texture);m.gammaSpace=!1;const _=m;return _.uRotationCenter=u.texture.uRotationCenter,_.vRotationCenter=u.texture.vRotationCenter,_.wRotationCenter=u.texture.wRotationCenter,_.homogeneousRotationInUVTransform=u.texture.homogeneousRotationInUVTransform,m}))();B.set(f,m);try{return yield m}catch(e){throw B.delete(f),e}}),Q=(e,t)=>b(this,void 0,void 0,function*(){const n=z(t.channel),o=t.descriptor.scale[n],s=t.descriptor.bias[n];return yield Y(e,t,[o,o,o,1],[s,s,s,0],t.channel)}),Z=e=>b(this,void 0,void 0,function*(){var n,o,s,r;const{material:i,normalScale:a,base:l,opacity:u,normal:c,metallic:d,roughness:h,occlusion:f,emissive:p}=e;if(l){if(4!==l.channel)throw new Error("A USD base-color texture must use the RGB output.");i.albedoColor=t.Color3.White(),i.albedoTexture=X(l.descriptor,[1,1,1,1],[0,0,0,0])?l.descriptor.texture:yield Y(`${i.name} base color`,l,l.descriptor.scale,l.descriptor.bias)}if(p){if(4!==p.channel)throw new Error("A USD emissive texture must use the RGB output.");const e=p.descriptor;if(e.bias.slice(0,3).every(e=>0===e))i.emissiveColor=new t.Color3(e.scale[0],e.scale[1],e.scale[2]),i.emissiveTexture=e.texture;else{const n=Array.from({length:3},(t,n)=>Math.max(1,Math.abs(e.bias[n]),Math.abs(e.bias[n]+e.scale[n]))),o=e.scale.map((e,t)=>t<3?e/n[t]:e),s=e.bias.map((e,t)=>t<3?e/n[t]:e);i.emissiveColor=new t.Color3(n[0],n[1],n[2]),i.emissiveTexture=yield Y(`${i.name} emissive`,p,o,s,p.channel,!0)}}if(c){if(4!==c.channel)throw new Error("A USD normal texture must use the RGB output.");if(1===c.descriptor.sourceColorSpace&&X(c.descriptor,[2,2,2,1],[-1,-1,-1,0]))i.bumpTexture=c.descriptor.texture;else{const e=Array.from(c.descriptor.scale,e=>.5*e),t=Array.from(c.descriptor.bias,(e,t)=>t<3?.5*(e+1):e);i.bumpTexture=yield Y(`${i.name} normal`,c,e,t)}i.bumpTexture.gammaSpace=!1,i.bumpTexture.level=a}let m=!1;if(!d||!h||d.descriptor!==h.descriptor||0!==d.channel&&2!==d.channel||1!==h.channel&&3!==h.channel||!j(d)||0!==d.descriptor.bias[z(d.channel)]||0!==h.descriptor.bias[z(h.channel)]){if(d){const e=z(d.channel),t=j(d)&&(0===d.channel||2===d.channel)&&0===d.descriptor.bias[e];i.metallicTexture=t?d.descriptor.texture:yield Q(`${i.name} metallic`,d),i.useRoughnessFromMetallicTextureAlpha=!1,i.useRoughnessFromMetallicTextureGreen=!1,i.useMetallnessFromMetallicTextureBlue=t&&2===d.channel,i.metallic=t?(null!==(s=i.metallic)&&void 0!==s?s:1)*d.descriptor.scale[e]:1}if(h){const e=z(h.channel),t=j(h)&&0===h.channel&&0===h.descriptor.bias[e];i.microSurfaceTexture=t?h.descriptor.texture:yield Q(`${i.name} roughness`,h),i.microSurfaceTexture.gammaSpace=!!t&&h.descriptor.texture.gammaSpace,i.roughness=t?(null!==(r=i.roughness)&&void 0!==r?r:1)*h.descriptor.scale[e]:1}}else{const e=d.descriptor;i.metallicTexture=e.texture,i.metallic=(null!==(n=i.metallic)&&void 0!==n?n:1)*e.scale[z(d.channel)],i.roughness=(null!==(o=i.roughness)&&void 0!==o?o:1)*e.scale[z(h.channel)],i.useRoughnessFromMetallicTextureAlpha=3===h.channel,i.useRoughnessFromMetallicTextureGreen=1===h.channel,i.useMetallnessFromMetallicTextureBlue=2===d.channel,m=(null==f?void 0:f.descriptor)===e&&0===f.channel&&1===e.scale[0]&&0===e.bias[0],i.useAmbientOcclusionFromMetallicTextureRed=m}if(f&&!m){const e=z(f.channel),t=j(f)&&0===f.channel&&1===f.descriptor.scale[e]&&0===f.descriptor.bias[e];i.ambientTexture=t?f.descriptor.texture:yield Q(`${i.name} occlusion`,f),i.useAmbientInGrayScale=!0}if(u)if(l&&i.albedoTexture&&u.descriptor===l.descriptor&&3===u.channel&&1===u.descriptor.scale[3]&&0===u.descriptor.bias[3])i.albedoTexture.hasAlpha=!0,i.useAlphaFromAlbedoTexture=!0;else{const e=3===u.channel&&1===u.descriptor.scale[3]&&0===u.descriptor.bias[3];i.opacityTexture=e?u.descriptor.texture:yield Q(`${i.name} opacity`,u),i.opacityTexture.gammaSpace=!!e&&u.descriptor.texture.gammaSpace,i.opacityTexture.getAlphaFromRGB=!e}const _=A.get(e.id);_&&(_.albedoColor.copyFrom(i.albedoColor),_.albedoTexture=i.albedoTexture,_.emissiveColor.copyFrom(i.emissiveColor),_.emissiveTexture=i.emissiveTexture,_.bumpTexture=i.bumpTexture,_.metallic=i.metallic,_.roughness=i.roughness,_.metallicTexture=i.metallicTexture,_.microSurfaceTexture=i.microSurfaceTexture,_.ambientTexture=i.ambientTexture,_.opacityTexture=i.opacityTexture,_.alpha=i.alpha,_.useAlphaFromAlbedoTexture=i.useAlphaFromAlbedoTexture,_.useRoughnessFromMetallicTextureAlpha=i.useRoughnessFromMetallicTextureAlpha,_.useRoughnessFromMetallicTextureGreen=i.useRoughnessFromMetallicTextureGreen,_.useMetallnessFromMetallicTextureBlue=i.useMetallnessFromMetallicTextureBlue,_.useAmbientOcclusionFromMetallicTextureRed=i.useAmbientOcclusionFromMetallicTextureRed,_.useAmbientInGrayScale=i.useAmbientInGrayScale)});try{const A=e._blockEntityCollection;s||(e._blockEntityCollection=!0);try{for(const s of _){const r=new Ph(n,s.payloadOffset,s.payloadLength);switch(s.opcode){case 1:{const n=1===r.u32(),o=r.f32();V=r.f32()||24,D=new t.TransformNode("USD Root",e),H(g.transformNodes,D),g.rootNodes.push(D),D.rotationQuaternion=n?t.Quaternion.FromArray([-.7071068,0,0,.7071068]):t.Quaternion.Identity(),D.scaling.copyFrom(e.useRightHandedSystem?new t.Vector3(o,o,o):n?new t.Vector3(o,-o,o):new t.Vector3(o,o,-o));break}case 2:{const n=r.u32();if(x.has(n))throw new Error(`Duplicate USD texture ${n}.`);const s=r.u32(),i=r.u32(),a=Kh(r.u32()),l=r.u32(),u=r.u32(),c=r.u32(),d=r.u32(),h=r.u32(),f=r.u32(),p=r.u32(),m=r.u32();if($h(o,d,5,4,"texture transform"),$h(o,m,8,4,"texture value transform"),$h(o,l,u,1,"texture image"),p<0||p>2)throw new Error(`Invalid USD texture color space ${p}.`);const _=new Float32Array(o,d,5),v=new Float32Array(o,m,8);if(![..._,...v].every(Number.isFinite))throw new Error(`USD texture ${n} has a non-finite transform.`);const y=new Uint8Array(o,l,u),b=URL.createObjectURL(new Blob([y],{type:a}));let T,A;N.add(b);const M=new Promise((e,t)=>{T=e,A=t});L.push(M);const w=new t.Texture(b,e,!1,!1,t.Texture.TRILINEAR_SAMPLINGMODE,T,(e,t)=>{URL.revokeObjectURL(b),A(t instanceof Error?t:new Error(e||`Could not load texture '${b}'.`))});H(g.textures,w),w.onDisposeObservable.addOnce(()=>URL.revokeObjectURL(b)),w.name=Uh(o,s,i),w.coordinatesIndex=c,w.uScale=_[0],w.vScale=_[1],w.uRotationCenter=0,w.vRotationCenter=0,w.uOffset=_[2]-_[1]*Math.sin(_[4]),w.vOffset=1-_[1]*Math.cos(_[4])-_[3],w.wAng=-_[4],w.wrapU=Wh(h),w.wrapV=Wh(f),w.gammaSpace=1!==p,x.set(n,{id:n,texture:w,sourceColorSpace:p,scale:v.subarray(0,4),bias:v.subarray(4,8)});break}case 3:{const n=r.u32(),s=r.u32(),i=r.u32(),a=r.u32(),l=r.u32(),u=r.f32(),c=r.f32(),d=r.f32(),h=r.f32(),f=r.u32(),p=Array.from({length:7},()=>r.u32()),m=Array.from({length:7},()=>r.u32());$h(o,a,4,4,"material base color"),$h(o,l,3,4,"material emissive color");const _=new Float32Array(o,a,4),v=new Float32Array(o,l,3),y=new t.PBRMaterial(Uh(o,s,i),e);H(g.materials,y),y.id=`usd-material-${n}`,y.albedoColor=new t.Color3(_[0],_[1],_[2]),y.alpha=_[3],y.metallic=u,y.roughness=c,y.emissiveColor=new t.Color3(v[0],v[1],v[2]);const b=Boolean(1&f);y.backFaceCulling=!b,y.twoSidedLighting=b,y.unlit=Boolean(2&f),4&f&&(y.transparencyMode=2),h>0&&(y.transparencyMode=1,y.alphaCutOff=h),k.push({id:n,material:y,normalScale:d,base:q(p[0],m[0],"base-color texture"),opacity:q(p[1],m[1],"opacity texture"),normal:q(p[2],m[2],"normal texture"),metallic:q(p[3],m[3],"metallic texture"),roughness:q(p[4],m[4],"roughness texture"),occlusion:q(p[5],m[5],"occlusion texture"),emissive:q(p[6],m[6],"emissive texture")}),T.set(n,y);break}case 4:{const n=r.u32(),s=r.u32(),i=r.u32(),a=r.u32(),l=r.u32(),u=new t.TransformNode(Uh(o,i,a),e);H(g.transformNodes,u),u.setPreTransformMatrix(Hh(o,l)),Object.defineProperty(u,Gh,{configurable:!0,get:()=>u.getPivotMatrix(),set:e=>u.setPreTransformMatrix(e)}),v.set(n,u),s===wh?u.parent=null!=D?D:null:y.push({node:u,parentId:s});break}case 5:{const n=r.u32(),s=r.u32(),i=r.u32(),a=r.u32(),l=r.u32(),u=new t.Skeleton(Uh(o,s,i),`usd-skeleton-${n}`,e);H(g.skeletons,u);const c=new DataView(o);$h(o,l,6*a,4,"skeleton joints");const d=[];for(let e=0;e<a;++e){const s=l+24*e,r=c.getUint32(s,!0),i=c.getUint32(s+4,!0),a=c.getUint32(s+8,!0),h=c.getUint32(s+12,!0),f=c.getUint32(s+16,!0),p=c.getUint32(s+20,!0);if(r!==wh&&r>=e)throw new Error(`Skeleton ${n} has an invalid parent joint index.`);const m=new t.Bone(Uh(o,a,h),u,r===wh?null:d[r],Hh(o,f),Hh(o,f),Hh(o,p),e);d.push(m),w.set(i,m)}M.set(n,u);break}case 6:{const e=r.u32();S.set(e,{vertexCount:r.u32(),indexCount:r.u32(),flags:r.u32(),positions:r.u32(),normals:r.u32(),tangents:r.u32(),uv0:r.u32(),colors:r.u32(),joints0:r.u32(),weights0:r.u32(),joints1:r.u32(),weights1:r.u32(),indices:r.u32(),influences:r.u32()});break}case 7:{const n=r.u32(),s=r.u32(),u=r.u32(),c=r.u32(),d=r.u32(),h=r.u32(),f=r.u32(),p=r.u32(),m=r.u32(),_=r.u32(),y=S.get(u);if(!y)throw new Error(`Mesh ${n} references missing geometry ${u}.`);const b=new t.Mesh(Uh(o,d,h),e);H(g.meshes,b),K(b,f),b.parent=null!==(a=null!==(i=v.get(s))&&void 0!==i?i:D)&&void 0!==a?a:null;const x=new t.VertexData;$h(o,y.positions,3*y.vertexCount,4,"positions"),x.positions=new Float32Array(o,y.positions,3*y.vertexCount),1&y.flags&&($h(o,y.normals,3*y.vertexCount,4,"normals"),x.normals=new Float32Array(o,y.normals,3*y.vertexCount)),2&y.flags&&($h(o,y.tangents,4*y.vertexCount,4,"tangents"),x.tangents=new Float32Array(o,y.tangents,4*y.vertexCount)),4&y.flags&&($h(o,y.uv0,2*y.vertexCount,4,"texture coordinates"),x.uvs=new Float32Array(o,y.uv0,2*y.vertexCount)),8&y.flags&&($h(o,y.colors,4*y.vertexCount,4,"vertex colors"),x.colors=new Float32Array(o,y.colors,4*y.vertexCount)),16&y.flags&&($h(o,y.joints0,4*y.vertexCount,2,"joint indices"),$h(o,y.weights0,4*y.vertexCount,4,"joint weights"),x.matricesIndices=Float32Array.from(new Uint16Array(o,y.joints0,4*y.vertexCount)),x.matricesWeights=new Float32Array(o,y.weights0,4*y.vertexCount)),32&y.flags&&($h(o,y.joints1,4*y.vertexCount,2,"extra joint indices"),$h(o,y.weights1,4*y.vertexCount,4,"extra joint weights"),x.matricesIndicesExtra=Float32Array.from(new Uint16Array(o,y.joints1,4*y.vertexCount)),x.matricesWeightsExtra=new Float32Array(o,y.weights1,4*y.vertexCount)),$h(o,y.indices,y.indexCount,4,"indices"),x.indices=new Uint32Array(o,y.indices,y.indexCount),x.applyToMesh(b,!0),b.geometry&&H(g.geometries,b.geometry),b.numBoneInfluencers=Math.min(y.influences,8),p!==wh&&(b.skeleton=null!==(l=M.get(p))&&void 0!==l?l:null);const T=new DataView(o);$h(o,m,5*_,4,"submeshes");const A=Boolean(1&f);if(1===_&&c!==wh)b.material=W(c,A);else{const n=new t.MultiMaterial(`${b.name} materials`,e);H(g.multiMaterials,n);for(let e=0;e<_;++e){const t=m+20*e;n.subMaterials.push(W(T.getUint32(t,!0),A))}b.material=n}b.releaseSubMeshes();for(let e=0;e<_;++e){const n=m+20*e;new t.SubMesh(e,T.getUint32(n+12,!0),T.getUint32(n+16,!0),T.getUint32(n+4,!0),T.getUint32(n+8,!0),b)}C.set(n,b);break}case 12:{const n=r.u32(),s=r.u32(),i=r.u32(),a=r.u32(),l=r.u32(),u=r.u32(),c=r.u32(),d=r.f32(),h=C.get(s);if(!h)throw new Error(`Morph target references missing mesh ${s}.`);if(I.has(n)||l!==h.getTotalVertices()||!Number.isFinite(d))throw new Error(`Morph target ${n} has invalid metadata.`);$h(o,u,3*l,4,"morph target positions");let f=R.get(s);f||(f=new t.MorphTargetManager(e,h.name),f.areUpdatesFrozen=!0,H(g.morphTargetManagers,f),R.set(s,f));const p=new t.MorphTarget(Uh(o,i,a),d,e,f);p.id=`usd-morph-target-${n}`,p.setPositions(new Float32Array(o,u,3*l)),c!==wh&&($h(o,c,3*l,4,"morph target normals"),p.setNormals(new Float32Array(o,c,3*l))),f.addTarget(p),I.set(n,p);break}case 10:{const n=r.u32(),s=r.u32(),i=r.u32(),a=r.u32(),l=r.u32(),d=r.u32(),h=r.u32(),f=r.u32(),p=r.f32(),m=r.f32(),_=r.u32(),y=Uh(o,l,d);if(!Number.isFinite(p)||p<=0)throw new Error(`Analytic primitive ${n} has an invalid size or radius.`);if((2===i||3===i)&&(!Number.isFinite(m)||m<=0))throw new Error(`Analytic primitive ${n} has an invalid height.`);if(0!==i&&(!Number.isInteger(_)||_<3||_>512))throw new Error(`Analytic primitive ${n} has invalid tessellation.`);let b;switch(i){case 0:b=t.CreateBox(y,{size:p},e);break;case 1:b=t.CreateSphere(y,{diameter:2*p,segments:_},e);break;case 2:case 3:b=t.CreateCylinder(y,{height:m,diameterTop:3===i?0:2*p,diameterBottom:2*p,tessellation:_},e);break;default:throw new Error(`Unsupported analytic primitive type ${i}.`)}if(H(g.meshes,b),b.geometry&&H(g.geometries,b.geometry),!(2&h)){const e=b.getIndices();if(!e)throw new Error(`Analytic primitive ${n} has no generated indices.`);const t=Array.from(e);for(let e=0;e<t.length;e+=3)[t[e],t[e+2]]=[t[e+2],t[e]];b.setIndices(t)}if(0===f)b.rotationQuaternion=t.Quaternion.RotationAxis(new t.Vector3(0,0,1),-Math.PI/2);else if(2===f)b.rotationQuaternion=t.Quaternion.RotationAxis(new t.Vector3(1,0,0),Math.PI/2);else if(1!==f)throw new Error(`Unsupported analytic primitive axis ${f}.`);K(b,h),b.parent=null!==(c=null!==(u=v.get(s))&&void 0!==u?u:D)&&void 0!==c?c:null,b.material=W(a,Boolean(1&h)),C.set(n,b);break}case 8:{const e=r.u32(),t=r.u32(),n=r.u32(),s=r.u32(),i=C.get(e);if(!i)throw new Error(`Instance references missing mesh ${e}.`);if(F.has(e))throw new Error(`Mesh ${e} cannot mix classic and thin instances.`);O.add(e);const a=i.createInstance(Uh(o,n,s));H(g.meshes,a),a.parent=null!==(h=null!==(d=v.get(t))&&void 0!==d?d:D)&&void 0!==h?h:null;break}case 11:{const e=r.u32(),t=r.u32(),n=r.u32(),s=C.get(e);if(!s)throw new Error(`Thin instances reference missing mesh ${e}.`);if(F.has(e)||O.has(e))throw new Error(`Mesh ${e} has duplicate or mixed thin instances.`);$h(o,t,16*n,4,"thin instance transforms"),s.thinInstanceSetBuffer("matrix",new Float32Array(o,t,16*n),16,!0),s.thinInstanceEnablePicking=!0,F.add(e);break}case 9:{const n=r.u32(),s=r.u32(),i=r.u32(),a=r.u32(),l=r.u32(),u=r.u32(),c=r.u32(),d=r.u32();if(0!==n&&1!==n&&2!==n)throw new Error(`Invalid animation target kind ${n}.`);if(2===n!=(4===i))throw new Error(`Invalid animation property ${i} for target kind ${n}.`);if(d!==(4===i?1:0===i||2===i?3:1===i?4:3===i?16:0))throw new Error(`Invalid animation value stride ${d} for property ${i}.`);const h=0===n?v.get(s):1===n?w.get(s):I.get(s);if(!h)break;const f=0===i?"position":1===i?"rotationQuaternion":2===i?"scaling":4===i?"influence":0===n?Gh:"_matrix",p=4===i?t.Animation.ANIMATIONTYPE_FLOAT:1===i?t.Animation.ANIMATIONTYPE_QUATERNION:3===i?t.Animation.ANIMATIONTYPE_MATRIX:t.Animation.ANIMATIONTYPE_VECTOR3,m=new t.Animation(`USD ${f}`,f,V,p,t.Animation.ANIMATIONLOOPMODE_CYCLE);$h(o,u,l,4,"animation times"),$h(o,c,l*d,4,"animation values");const _=new Float32Array(o,u,l),y=new Float32Array(o,c,l*d);m.setKeys(Array.from({length:l},(e,n)=>({frame:_[n],value:p===t.Animation.ANIMATIONTYPE_QUATERNION?t.Quaternion.FromArray(y,n*d):p===t.Animation.ANIMATIONTYPE_MATRIX?t.Matrix.FromArray(y,n*d):p===t.Animation.ANIMATIONTYPE_FLOAT?y[n*d]:t.Vector3.FromArray(y,n*d)})));let b=E.get(a);b||(b=new t.AnimationGroup(`USD Animation ${a+1}`,e),E.set(a,b),H(g.animationGroups,b)),b.addTargetedAnimation(m,h);break}}}for(const[e,n]of R)n.areUpdatesFrozen=!1,!n.isUsingTextureForTargets&&n.numTargets<=t.MorphTargetManager.MaxActiveMorphTargetsInVertexAttributeMode&&(n.optimizeInfluencers=!1,n.numMaxInfluencers=n.numTargets),C.get(e).morphTargetManager=n}finally{s||(e._blockEntityCollection=A)}yield qh(Promise.all(L),r),yield qh(Promise.all(k.map(e=>b(this,void 0,void 0,function*(){yield Z(e)}))),r);for(const{node:e,parentId:t}of y)e.parent=null!==(p=null!==(f=v.get(t))&&void 0!==f?f:D)&&void 0!==p?p:null;return{container:g,materializeMs:performance.now()-m}}catch(e){G=!0,Promise.allSettled(L),Promise.allSettled(B.values()),g.dispose();for(const e of N)URL.revokeObjectURL(e);throw e}})}(e,o.commands,o.data,i,v),h={container:a.container,timings:Object.assign(Object.assign({},o.timings),{materializeMs:a.materializeMs}),statistics:o.statistics,missingAssets:o.missingAssets};try{v.throwIfAborted(),null===(d=(c=this._options).onComplete)||void 0===d||d.call(c,{timings:h.timings,statistics:h.statistics,missingAssets:h.missingAssets}),v.throwIfAborted()}catch(e){throw a.container.dispose(),e}return h}finally{this._activeLoads.delete(g),0===this._pending.size&&this._terminateWorker()}})}_getWorker(e){var t;if(!e)throw new Error("The USD worker URL was not configured.");const n=globalThis.location,o=new URL(String(e),null!==(t=null==n?void 0:n.href)&&void 0!==t?t:"http://localhost/").href;if(this._worker&&this._workerUrl!==o){if(this._pending.size>0)throw new Error("Cannot change the USD worker URL while requests are pending.");this._terminateWorker()}if(this._worker)return this._worker;this._workerUrl=o,n&&new URL(o).origin!==n.origin?(this._workerBlobUrl=URL.createObjectURL(new Blob([`import ${JSON.stringify(o)};`],{type:"application/javascript"})),this._worker=new Worker(this._workerBlobUrl,{type:"module"})):this._worker=new Worker(o,{type:"module"}),this._worker.addEventListener("message",e=>{var t,n;const o=e.data,s=this._pending.get(o.requestId);if(s)if("progress"!==o.type)if("log"!==o.type)if(this._pending.delete(o.requestId),"error"===o.type){const e=new Error(o.message);e.stack=o.stack,s.reject(e)}else s.resolve(o);else null===(n=s.onLog)||void 0===n||n.call(s,o.level>=2?"error":1===o.level?"warning":"info",o.message);else null===(t=s.onProgress)||void 0===t||t.call(s,o.progress)});const s=e=>{this._terminateWorker();for(const t of this._pending.values())t.reject(e);this._pending.clear()};return this._worker.addEventListener("error",e=>{var t;s(null!==(t=e.error)&&void 0!==t?t:new Error(e.message||`Could not load the USD worker from '${o}'.`))}),this._worker.addEventListener("messageerror",()=>{s(new Error("The USD worker returned a message that could not be deserialized."))}),this._worker}_terminateWorker(){var e;null===(e=this._worker)||void 0===e||e.terminate(),this._worker=void 0,this._workerUrl=void 0,this._workerBlobUrl&&(URL.revokeObjectURL(this._workerBlobUrl),this._workerBlobUrl=void 0)}}Qh.DefaultConfiguration={glueUrl:`${zh}babylon-usd-importer.js`,wasmUrl:`${zh}babylon-usd-importer.wasm`,dataUrl:`${zh}babylon-usd-importer.data`,workerUrl:`${zh}babylon-usd-importer.worker.js`};const Zh={initializing:1,staging:2,extracting:3,materializing:4};let Jh=!1;function ef(){t.RegisterPbrMaterial(),t.RegisterInstancedMesh(),t.RegisterThinInstanceMesh()}function tf(){Jh||(Jh=!0,ef(),t.RegisterSceneLoaderPlugin(new Qh))}var nf={__proto__:null,RegisterUSDFileLoader:tf,USDFileLoader:Qh,_RegisterUSDLoaderDependencies:ef};function of(){t.RegisterSceneLoaderPlugin(Object.assign(Object.assign({},p),{createPlugin:e=>b(this,void 0,void 0,function*(){const{BVHFileLoader:t}=yield Promise.resolve().then(function(){return v});return new t(e[p.name])})})),t.RegisterSceneLoaderPlugin(Object.assign(Object.assign({},xo),{createPlugin:e=>b(this,void 0,void 0,function*(){const{FBXFileLoader:t}=yield Promise.resolve().then(function(){return Go});return new t(e[xo.name])})})),t.RegisterSceneLoaderPlugin(Object.assign(Object.assign({},qo),{createPlugin:e=>b(this,void 0,void 0,function*(){const[{GLTFFileLoader:t,RegisterGLTF2Loader:n},{RegisterInstancedMesh:o}]=yield Promise.all([Promise.resolve().then(function(){return Tr}),Promise.resolve(BABYLON)]);return o(),n(),new t(e[qo.name])})})),function(){Ys("EXT_lights_image_based"),Xs("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 Gr});return new t(e)})),Ys("EXT_mesh_gpu_instancing"),Xs("EXT_mesh_gpu_instancing",!0,e=>b(this,void 0,void 0,function*(){const[{EXT_mesh_gpu_instancing:t},{RegisterThinInstanceMesh:n}]=yield Promise.all([Promise.resolve().then(function(){return Wr}),Promise.resolve(BABYLON)]);return n(),new t(e)})),Ys("EXT_meshopt_compression"),Xs("EXT_meshopt_compression",!0,e=>b(this,void 0,void 0,function*(){const{EXT_meshopt_compression:t}=yield Promise.resolve().then(function(){return Yr});return new t(e)})),Ys("EXT_texture_avif"),Xs("EXT_texture_avif",!0,e=>b(this,void 0,void 0,function*(){const{EXT_texture_avif:t}=yield Promise.resolve().then(function(){return ii});return new t(e)})),Ys("EXT_texture_webp"),Xs("EXT_texture_webp",!0,e=>b(this,void 0,void 0,function*(){const{EXT_texture_webp:t}=yield Promise.resolve().then(function(){return ti});return new t(e)})),Ys("ExtrasAsMetadata"),Xs("ExtrasAsMetadata",!1,e=>b(this,void 0,void 0,function*(){const{ExtrasAsMetadata:t}=yield Promise.resolve().then(function(){return md});return new t(e)})),Ys("KHR_animation_pointer"),Xs("KHR_animation_pointer",!0,e=>b(this,void 0,void 0,function*(){const[{KHR_animation_pointer:t},{_RegisterKHRAnimationPointerData:n}]=yield Promise.all([Promise.resolve().then(function(){return Hl}),Promise.resolve().then(function(){return ou})]);return n(),new t(e)})),Ys("KHR_draco_mesh_compression"),Xs("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 _i});return new t(e)})),Ys("KHR_gaussian_splatting"),Xs("KHR_gaussian_splatting",!0,e=>b(this,void 0,void 0,function*(){const{KHR_gaussian_splatting:t}=yield Promise.resolve().then(function(){return Mi});return new t(e)})),Ys("KHR_interactivity"),Xs("KHR_interactivity",!0,e=>b(this,void 0,void 0,function*(){const{KHR_interactivity:t,_RegisterKHRInteractivityRuntime:n}=yield Promise.resolve().then(function(){return Oc});return n(),new t(e)})),Ys("KHR_lights_punctual"),Xs("KHR_lights_punctual",!0,e=>b(this,void 0,void 0,function*(){const{KHR_lights:t}=yield Promise.resolve().then(function(){return Ii});return new t(e)})),Ys("EXT_lights_area"),Xs("EXT_lights_area",!0,e=>b(this,void 0,void 0,function*(){const{EXT_lights_area:t}=yield Promise.resolve().then(function(){return Ni});return new t(e)})),Ys("EXT_lights_ies"),Xs("EXT_lights_ies",!0,e=>b(this,void 0,void 0,function*(){const{EXT_lights_ies:t}=yield Promise.resolve().then(function(){return di});return new t(e)})),Ys("KHR_materials_anisotropy"),Xs("KHR_materials_anisotropy",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_anisotropy:t}=yield Promise.resolve().then(function(){return ca});return new t(e)})),Ys("KHR_materials_clearcoat"),Xs("KHR_materials_clearcoat",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_clearcoat:t}=yield Promise.resolve().then(function(){return Xi});return new t(e)})),Ys("KHR_materials_diffuse_roughness"),Xs("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 vl});return new t(e)})),Ys("KHR_materials_diffuse_transmission"),Xs("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 Za});return new t(e)})),Ys("KHR_materials_dispersion"),Xs("KHR_materials_dispersion",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_dispersion:t}=yield Promise.resolve().then(function(){return fl});return new t(e)})),Ys("KHR_materials_emissive_strength"),Xs("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 ma});return new t(e)})),Ys("KHR_materials_ior"),Xs("KHR_materials_ior",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_ior:t}=yield Promise.resolve().then(function(){return ka});return new t(e)})),Ys("KHR_materials_iridescence"),Xs("KHR_materials_iridescence",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_iridescence:t}=yield Promise.resolve().then(function(){return ra});return new t(e)})),Ys("KHR_materials_pbrSpecularGlossiness"),Xs("KHR_materials_pbrSpecularGlossiness",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_pbrSpecularGlossiness:t}=yield Promise.resolve().then(function(){return Vi});return new t(e)})),Ys("KHR_materials_sheen"),Xs("KHR_materials_sheen",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_sheen:t}=yield Promise.resolve().then(function(){return ba});return new t(e)})),Ys("KHR_materials_specular"),Xs("KHR_materials_specular",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_specular:t}=yield Promise.resolve().then(function(){return Oa});return new t(e)})),Ys("KHR_materials_transmission"),Xs("KHR_materials_transmission",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_transmission:t}=yield Promise.resolve().then(function(){return za});return new t(e)})),Ys("KHR_materials_unlit"),Xs("KHR_materials_unlit",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_unlit:t}=yield Promise.resolve().then(function(){return Ki});return new t(e)})),Ys("KHR_materials_variants"),Xs("KHR_materials_variants",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_variants:t}=yield Promise.resolve().then(function(){return Ga});return new t(e)})),Ys("KHR_materials_volume"),Xs("KHR_materials_volume",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_volume:t}=yield Promise.resolve().then(function(){return ol});return new t(e)})),Ys("KHR_mesh_quantization"),Xs("KHR_mesh_quantization",!0,e=>b(this,void 0,void 0,function*(){const{KHR_mesh_quantization:t}=yield Promise.resolve().then(function(){return Al});return new t(e)})),Ys("KHR_texture_basisu"),Xs("KHR_texture_basisu",!0,e=>b(this,void 0,void 0,function*(){const{KHR_texture_basisu:t}=yield Promise.resolve().then(function(){return Rl});return new t(e)})),Ys("KHR_texture_transform"),Xs("KHR_texture_transform",!0,e=>b(this,void 0,void 0,function*(){const{KHR_texture_transform:t}=yield Promise.resolve().then(function(){return Ll});return new t(e)})),Ys("KHR_xmp_json_ld"),Xs("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 Dl});return new t(e)})),Ys("MSFT_audio_emitter"),Xs("MSFT_audio_emitter",!0,e=>b(this,void 0,void 0,function*(){const[{MSFT_audio_emitter:t},{RegisterAudioSceneComponent:n},{Sound:o}]=yield Promise.all([Promise.resolve().then(function(){return lu}),Promise.resolve(BABYLON),Promise.resolve(BABYLON)]);return n(o),new t(e)})),Ys("MSFT_lod"),Xs("MSFT_lod",!0,e=>b(this,void 0,void 0,function*(){const{MSFT_lod:t}=yield Promise.resolve().then(function(){return fu});return new t(e)})),Ys("MSFT_minecraftMesh"),Xs("MSFT_minecraftMesh",!0,e=>b(this,void 0,void 0,function*(){const{MSFT_minecraftMesh:t}=yield Promise.resolve().then(function(){return vu});return new t(e)})),Ys("MSFT_sRGBFactors"),Xs("MSFT_sRGBFactors",!0,e=>b(this,void 0,void 0,function*(){const{MSFT_sRGBFactors:t}=yield Promise.resolve().then(function(){return Au});return new t(e)})),Ys("KHR_node_visibility"),Xs("KHR_node_visibility",!0,e=>b(this,void 0,void 0,function*(){const{KHR_node_visibility:t,_RegisterKHRNodeVisibilityRuntime:n}=yield Promise.resolve().then(function(){return Pc});return n(),new t(e)})),Ys("KHR_node_hoverability"),Xs("KHR_node_hoverability",!0,e=>b(this,void 0,void 0,function*(){const{KHR_node_hoverability:t,_RegisterKHRNodeHoverabilityRuntime:n}=yield Promise.resolve().then(function(){return cd});return n(),new t(e)})),Ys("KHR_node_selectability"),Xs("KHR_node_selectability",!0,e=>b(this,void 0,void 0,function*(){const{KHR_node_selectability:t,_RegisterKHRNodeSelectabilityRuntime:n}=yield Promise.resolve().then(function(){return td});return n(),new t(e)})),Ys("KHR_materials_coat"),Xs("KHR_materials_coat",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_coat:t}=yield Promise.resolve().then(function(){return ea});return new t(e)})),Ys("KHR_materials_fuzz"),Xs("KHR_materials_fuzz",!0,e=>b(this,void 0,void 0,function*(){const{KHR_materials_fuzz:t}=yield Promise.resolve().then(function(){return wa});return new t(e)})),Ys("KHR_materials_volume_scatter"),Xs("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 ll});return new t(e)}))}(),t.RegisterSceneLoaderPlugin(Object.assign(Object.assign({},Od),{createPlugin:e=>b(this,void 0,void 0,function*(){const{OBJFileLoader:t}=yield Promise.resolve().then(function(){return Nd});return new t(e[Od.name])})})),t.RegisterSceneLoaderPlugin(Object.assign(Object.assign({},Ud),{createPlugin:e=>b(this,void 0,void 0,function*(){const[{SPLATFileLoader:t},{RegisterEnginesExtensionsEngineDynamicTexture:n}]=yield Promise.all([Promise.resolve().then(function(){return yh}),Promise.resolve(BABYLON)]);return n(),new t(e[Ud.name])})})),t.RegisterSceneLoaderPlugin(Object.assign(Object.assign({},Bd),{createPlugin:()=>b(this,void 0,void 0,function*(){const[{STLFileLoader:e},{RegisterStandardMaterial:t}]=yield Promise.all([Promise.resolve().then(function(){return Gd}),Promise.resolve(BABYLON)]);return t(),new e})})),t.RegisterSceneLoaderPlugin(Object.assign(Object.assign({},bh),{createPlugin:e=>b(this,void 0,void 0,function*(){const{USDFileLoader:t,_RegisterUSDLoaderDependencies:n}=yield Promise.resolve().then(function(){return nf});return n(),new t(e[bh.name])})}))}tf();var sf={__proto__:null,registerBuiltInLoaders:of};const rf="undefined"!=typeof global?global:"undefined"!=typeof window?window:void 0;if(void 0!==rf)for(const e in y)rf.BABYLON[e]||(rf.BABYLON[e]=y[e]);const af="undefined"!=typeof global?global:"undefined"!=typeof window?window:void 0;if(void 0!==af){af.BABYLON=af.BABYLON||{};for(const e in sf)af.BABYLON[e]=sf[e]}const lf="undefined"!=typeof global?global:"undefined"!=typeof window?window:void 0;if(void 0!==lf){lf.BABYLON=lf.BABYLON||{};for(const e in fs)lf.BABYLON[e]=fs[e];for(const e in Ko)lf.BABYLON[e]=Ko[e]}const uf="undefined"!=typeof global?global:"undefined"!=typeof window?window:void 0;if(void 0!==uf){uf.BABYLON=uf.BABYLON||{},uf.BABYLON.GLTF1=uf.BABYLON.GLTF1||{};for(const e in qs)uf.BABYLON.GLTF1[e]=qs[e]}const cf=Object.assign({},Sd),df=Object.assign(Object.assign({},{__proto__:null}),{Extensions:cf}),hf=Object.assign(Object.assign({},Cd),{Loader:df}),ff="undefined"!=typeof global?global:"undefined"!=typeof window?window:void 0;if(void 0!==ff){ff.BABYLON=ff.BABYLON||{};const e=ff.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 cf)e.GLTF2.Loader.Extensions[n]=cf[n],t.push(n);for(const n in df)"Extensions"!==n&&(e.GLTF2.Loader[n]=df[n],t.push(n));for(const n in hf)t.indexOf(n)>-1||(e.GLTF2[n]=hf[n])}const pf="undefined"!=typeof global?global:"undefined"!=typeof window?window:void 0;if(void 0!==pf)for(const e in kd)pf.BABYLON[e]||(pf.BABYLON[e]=kd[e]);const mf="undefined"!=typeof global?global:"undefined"!=typeof window?window:void 0;if(void 0!==mf)for(const e in $d)mf.BABYLON[e]||(mf.BABYLON[e]=$d[e]);e.AddGaussianSplattingStreamPart=function(e,t,n,o,s={}){return new hh(t,n,o,e.getScene(),Object.assign(Object.assign({},s),{hostCompound:e}))},e.AddGaussianSplattingStreamPartAsync=function(e,t,n,o){return b(this,arguments,void 0,function*(e,t,n,o,s={}){const r=new hh(t,n,o,e.getScene(),Object.assign(Object.assign({},s),{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=m,e.FBXConstraintBehavior=bo,e.FBXConstraintSolver=yo,e.FBXFileLoader=To,e.FBXFileLoaderMetadata=xo,e.GLTF1=qs,e.GLTF2=hf,e.GLTFFileLoader=ts,e.GLTFLoaderDefaultOptions=Jo,e.GLTFValidation=Ho,e.GaussianSplattingStream=hh,e.MTLFileLoader=Rd,e.OBJFileLoader=Fd,e.ReadBvh=f,e.RegisterBVHFileLoader=g,e.RegisterGLTFFileLoader=os,e.RegisterOBJFileLoader=Ld,e.RegisterSPLATFileLoader=vh,e.RegisterSTLFileLoader=Vd,e.RegisterUSDFileLoader=tf,e.SPLATFileLoader=_h,e.STLFileLoader=Pd,e.SolidParser=Id,e.USDFileLoader=Qh,e._RegisterUSDLoaderDependencies=ef,e.registerBuiltInLoaders=of});
2
2
  //# sourceMappingURL=babylonjs.loaders.min.js.map